BaseStreamingService.cs 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  1. using System.Text;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Dlna;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Drawing;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Library;
  18. using MediaBrowser.Model.LiveTv;
  19. using System;
  20. using System.Collections.Generic;
  21. using System.Diagnostics;
  22. using System.Globalization;
  23. using System.IO;
  24. using System.Linq;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. namespace MediaBrowser.Api.Playback
  28. {
  29. /// <summary>
  30. /// Class BaseStreamingService
  31. /// </summary>
  32. public abstract class BaseStreamingService : BaseApiService
  33. {
  34. /// <summary>
  35. /// Gets or sets the application paths.
  36. /// </summary>
  37. /// <value>The application paths.</value>
  38. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  39. /// <summary>
  40. /// Gets or sets the user manager.
  41. /// </summary>
  42. /// <value>The user manager.</value>
  43. protected IUserManager UserManager { get; private set; }
  44. /// <summary>
  45. /// Gets or sets the library manager.
  46. /// </summary>
  47. /// <value>The library manager.</value>
  48. protected ILibraryManager LibraryManager { get; private set; }
  49. /// <summary>
  50. /// Gets or sets the iso manager.
  51. /// </summary>
  52. /// <value>The iso manager.</value>
  53. protected IIsoManager IsoManager { get; private set; }
  54. /// <summary>
  55. /// Gets or sets the media encoder.
  56. /// </summary>
  57. /// <value>The media encoder.</value>
  58. protected IMediaEncoder MediaEncoder { get; private set; }
  59. protected IEncodingManager EncodingManager { get; private set; }
  60. protected IDtoService DtoService { get; private set; }
  61. protected IFileSystem FileSystem { get; private set; }
  62. protected IItemRepository ItemRepository { get; private set; }
  63. protected ILiveTvManager LiveTvManager { get; private set; }
  64. protected IDlnaManager DlnaManager { get; private set; }
  65. /// <summary>
  66. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  67. /// </summary>
  68. /// <param name="serverConfig">The server configuration.</param>
  69. /// <param name="userManager">The user manager.</param>
  70. /// <param name="libraryManager">The library manager.</param>
  71. /// <param name="isoManager">The iso manager.</param>
  72. /// <param name="mediaEncoder">The media encoder.</param>
  73. /// <param name="dtoService">The dto service.</param>
  74. /// <param name="fileSystem">The file system.</param>
  75. /// <param name="itemRepository">The item repository.</param>
  76. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager, IEncodingManager encodingManager, IDlnaManager dlnaManager)
  77. {
  78. DlnaManager = dlnaManager;
  79. EncodingManager = encodingManager;
  80. LiveTvManager = liveTvManager;
  81. ItemRepository = itemRepository;
  82. FileSystem = fileSystem;
  83. DtoService = dtoService;
  84. ServerConfigurationManager = serverConfig;
  85. UserManager = userManager;
  86. LibraryManager = libraryManager;
  87. IsoManager = isoManager;
  88. MediaEncoder = mediaEncoder;
  89. }
  90. /// <summary>
  91. /// Gets the command line arguments.
  92. /// </summary>
  93. /// <param name="outputPath">The output path.</param>
  94. /// <param name="state">The state.</param>
  95. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  96. /// <returns>System.String.</returns>
  97. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions);
  98. /// <summary>
  99. /// Gets the type of the transcoding job.
  100. /// </summary>
  101. /// <value>The type of the transcoding job.</value>
  102. protected abstract TranscodingJobType TranscodingJobType { get; }
  103. /// <summary>
  104. /// Gets the output file extension.
  105. /// </summary>
  106. /// <param name="state">The state.</param>
  107. /// <returns>System.String.</returns>
  108. protected virtual string GetOutputFileExtension(StreamState state)
  109. {
  110. return Path.GetExtension(state.RequestedUrl);
  111. }
  112. /// <summary>
  113. /// Gets the output file path.
  114. /// </summary>
  115. /// <param name="state">The state.</param>
  116. /// <returns>System.String.</returns>
  117. protected virtual string GetOutputFilePath(StreamState state)
  118. {
  119. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  120. var outputFileExtension = GetOutputFileExtension(state);
  121. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  122. }
  123. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  124. /// <summary>
  125. /// The fast seek offset seconds
  126. /// </summary>
  127. private const int FastSeekOffsetSeconds = 1;
  128. /// <summary>
  129. /// Gets the fast seek command line parameter.
  130. /// </summary>
  131. /// <param name="request">The request.</param>
  132. /// <returns>System.String.</returns>
  133. /// <value>The fast seek command line parameter.</value>
  134. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  135. {
  136. var time = request.StartTimeTicks;
  137. if (time.HasValue)
  138. {
  139. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds;
  140. if (seconds > 0)
  141. {
  142. return string.Format("-ss {0}", seconds.ToString(UsCulture));
  143. }
  144. }
  145. return string.Empty;
  146. }
  147. /// <summary>
  148. /// Gets the slow seek command line parameter.
  149. /// </summary>
  150. /// <param name="request">The request.</param>
  151. /// <returns>System.String.</returns>
  152. /// <value>The slow seek command line parameter.</value>
  153. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  154. {
  155. return string.Empty;
  156. }
  157. /// <summary>
  158. /// Gets the map args.
  159. /// </summary>
  160. /// <param name="state">The state.</param>
  161. /// <returns>System.String.</returns>
  162. protected virtual string GetMapArgs(StreamState state)
  163. {
  164. var args = string.Empty;
  165. if (state.IsRemote || !state.HasMediaStreams)
  166. {
  167. return string.Empty;
  168. }
  169. if (state.VideoStream != null)
  170. {
  171. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  172. }
  173. else
  174. {
  175. args += "-map -0:v";
  176. }
  177. if (state.AudioStream != null)
  178. {
  179. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  180. }
  181. else
  182. {
  183. args += " -map -0:a";
  184. }
  185. if (state.SubtitleStream == null)
  186. {
  187. args += " -map -0:s";
  188. }
  189. return args;
  190. }
  191. /// <summary>
  192. /// Determines which stream will be used for playback
  193. /// </summary>
  194. /// <param name="allStream">All stream.</param>
  195. /// <param name="desiredIndex">Index of the desired.</param>
  196. /// <param name="type">The type.</param>
  197. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  198. /// <returns>MediaStream.</returns>
  199. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  200. {
  201. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  202. if (desiredIndex.HasValue)
  203. {
  204. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  205. if (stream != null)
  206. {
  207. return stream;
  208. }
  209. }
  210. if (type == MediaStreamType.Video)
  211. {
  212. streams = streams.Where(i => !string.Equals(i.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)).ToList();
  213. }
  214. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  215. {
  216. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  217. streams.FirstOrDefault();
  218. }
  219. // Just return the first one
  220. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  221. }
  222. protected EncodingQuality GetQualitySetting()
  223. {
  224. var quality = ServerConfigurationManager.Configuration.MediaEncodingQuality;
  225. if (quality == EncodingQuality.Auto)
  226. {
  227. var cpuCount = Environment.ProcessorCount;
  228. if (cpuCount >= 4)
  229. {
  230. //return EncodingQuality.HighQuality;
  231. }
  232. return EncodingQuality.HighSpeed;
  233. }
  234. return quality;
  235. }
  236. /// <summary>
  237. /// Gets the number of threads.
  238. /// </summary>
  239. /// <returns>System.Int32.</returns>
  240. /// <exception cref="System.Exception">Unrecognized MediaEncodingQuality value.</exception>
  241. protected int GetNumberOfThreads(StreamState state, bool isWebm)
  242. {
  243. // Use more when this is true. -re will keep cpu usage under control
  244. if (state.ReadInputAtNativeFramerate)
  245. {
  246. if (isWebm)
  247. {
  248. return Math.Max(Environment.ProcessorCount - 1, 2);
  249. }
  250. return 0;
  251. }
  252. // Webm: http://www.webmproject.org/docs/encoder-parameters/
  253. // The decoder will usually automatically use an appropriate number of threads according to how many cores are available but it can only use multiple threads
  254. // for the coefficient data if the encoder selected --token-parts > 0 at encode time.
  255. switch (GetQualitySetting())
  256. {
  257. case EncodingQuality.HighSpeed:
  258. return 2;
  259. case EncodingQuality.HighQuality:
  260. return isWebm ? Math.Max(Environment.ProcessorCount - 1, 2) : 0;
  261. case EncodingQuality.MaxQuality:
  262. return isWebm ? Math.Max(Environment.ProcessorCount - 1, 2) : 0;
  263. default:
  264. throw new Exception("Unrecognized MediaEncodingQuality value.");
  265. }
  266. }
  267. /// <summary>
  268. /// Gets the video bitrate to specify on the command line
  269. /// </summary>
  270. /// <param name="state">The state.</param>
  271. /// <param name="videoCodec">The video codec.</param>
  272. /// <param name="isHls">if set to <c>true</c> [is HLS].</param>
  273. /// <returns>System.String.</returns>
  274. protected string GetVideoQualityParam(StreamState state, string videoCodec, bool isHls)
  275. {
  276. var param = string.Empty;
  277. var isVc1 = state.VideoStream != null &&
  278. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  279. var qualitySetting = GetQualitySetting();
  280. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  281. {
  282. switch (qualitySetting)
  283. {
  284. case EncodingQuality.HighSpeed:
  285. param = "-preset ultrafast";
  286. break;
  287. case EncodingQuality.HighQuality:
  288. param = "-preset superfast";
  289. break;
  290. case EncodingQuality.MaxQuality:
  291. param = "-preset superfast";
  292. break;
  293. }
  294. switch (qualitySetting)
  295. {
  296. case EncodingQuality.HighSpeed:
  297. param += " -crf 23";
  298. break;
  299. case EncodingQuality.HighQuality:
  300. param += " -crf 20";
  301. break;
  302. case EncodingQuality.MaxQuality:
  303. param += " -crf 18";
  304. break;
  305. }
  306. }
  307. // webm
  308. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  309. {
  310. // Values 0-3, 0 being highest quality but slower
  311. var profileScore = 0;
  312. string crf;
  313. switch (qualitySetting)
  314. {
  315. case EncodingQuality.HighSpeed:
  316. crf = "18";
  317. profileScore++;
  318. break;
  319. case EncodingQuality.HighQuality:
  320. crf = "10";
  321. break;
  322. case EncodingQuality.MaxQuality:
  323. crf = "4";
  324. break;
  325. default:
  326. throw new ArgumentException("Unrecognized quality setting");
  327. }
  328. if (isVc1)
  329. {
  330. profileScore++;
  331. }
  332. // http://www.webmproject.org/docs/encoder-parameters/
  333. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1}",
  334. profileScore.ToString(UsCulture),
  335. crf);
  336. }
  337. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  338. {
  339. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  340. }
  341. // asf/wmv
  342. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  343. {
  344. param = "-qmin 2";
  345. }
  346. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  347. {
  348. param = "-mbd 2";
  349. }
  350. param += GetVideoBitrateParam(state, videoCodec, isHls);
  351. var framerate = GetFramerateParam(state);
  352. if (framerate.HasValue)
  353. {
  354. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  355. }
  356. if (!string.IsNullOrEmpty(state.VideoSync))
  357. {
  358. param += " -vsync " + state.VideoSync;
  359. }
  360. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  361. {
  362. param += " -profile:v " + state.VideoRequest.Profile;
  363. }
  364. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  365. {
  366. param += " -level " + state.VideoRequest.Level;
  367. }
  368. return param;
  369. }
  370. protected string GetAudioFilterParam(StreamState state, bool isHls)
  371. {
  372. var volParam = string.Empty;
  373. var audioSampleRate = string.Empty;
  374. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  375. // Boost volume to 200% when downsampling from 6ch to 2ch
  376. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  377. {
  378. volParam = ",volume=2.000000";
  379. }
  380. if (state.Request.AudioSampleRate.HasValue)
  381. {
  382. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  383. }
  384. var adelay = isHls ? "adelay=1," : string.Empty;
  385. var pts = string.Empty;
  386. if (state.SubtitleStream != null)
  387. {
  388. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  389. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  390. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  391. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  392. {
  393. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  394. pts = string.Format(",asetpts=PTS-{0}/TB",
  395. Math.Round(seconds).ToString(UsCulture));
  396. }
  397. }
  398. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  399. adelay,
  400. audioSampleRate,
  401. volParam,
  402. pts,
  403. state.AudioSync);
  404. }
  405. /// <summary>
  406. /// If we're going to put a fixed size on the command line, this will calculate it
  407. /// </summary>
  408. /// <param name="state">The state.</param>
  409. /// <param name="outputVideoCodec">The output video codec.</param>
  410. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  411. /// <returns>System.String.</returns>
  412. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  413. {
  414. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  415. var assSubtitleParam = string.Empty;
  416. var copyTsParam = string.Empty;
  417. var yadifParam = state.DeInterlace ? "yadif=0:-1:0," : string.Empty;
  418. var request = state.VideoRequest;
  419. if (state.SubtitleStream != null)
  420. {
  421. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  422. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  423. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  424. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  425. {
  426. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  427. copyTsParam = " -copyts";
  428. }
  429. }
  430. // If fixed dimensions were supplied
  431. if (request.Width.HasValue && request.Height.HasValue)
  432. {
  433. var widthParam = request.Width.Value.ToString(UsCulture);
  434. var heightParam = request.Height.Value.ToString(UsCulture);
  435. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  436. }
  437. // If Max dimensions were supplied, for width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size
  438. if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  439. {
  440. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  441. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  442. return string.Format("{4} -vf \"{0}scale=trunc(min(iw\\,{1})/2)*2:trunc(min((iw/dar)\\,{2})/2)*2{3}\"", yadifParam, maxWidthParam, maxHeightParam, assSubtitleParam, copyTsParam);
  443. }
  444. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  445. // If a fixed width was requested
  446. if (request.Width.HasValue)
  447. {
  448. var widthParam = request.Width.Value.ToString(UsCulture);
  449. return isH264Output ?
  450. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  451. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam);
  452. }
  453. // If a fixed height was requested
  454. if (request.Height.HasValue)
  455. {
  456. var heightParam = request.Height.Value.ToString(UsCulture);
  457. return isH264Output ?
  458. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  459. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam);
  460. }
  461. // If a max width was requested
  462. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  463. {
  464. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  465. return isH264Output ?
  466. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  467. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  468. }
  469. // If a max height was requested
  470. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  471. {
  472. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  473. return isH264Output ?
  474. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  475. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  476. }
  477. if (state.VideoStream == null)
  478. {
  479. // No way to figure this out
  480. return string.Empty;
  481. }
  482. // Need to perform calculations manually
  483. // Try to account for bad media info
  484. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  485. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  486. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  487. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  488. if (isH264Output)
  489. {
  490. var widthParam = outputSize.Width.ToString(UsCulture);
  491. var heightParam = outputSize.Height.ToString(UsCulture);
  492. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  493. }
  494. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  495. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  496. }
  497. /// <summary>
  498. /// Gets the text subtitle param.
  499. /// </summary>
  500. /// <param name="state">The state.</param>
  501. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  502. /// <returns>System.String.</returns>
  503. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  504. {
  505. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  506. GetExtractedAssPath(state, performConversion);
  507. if (string.IsNullOrEmpty(path))
  508. {
  509. return string.Empty;
  510. }
  511. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  512. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  513. path.Replace('\\', '/').Replace(":/", "\\:/"),
  514. Math.Round(seconds).ToString(UsCulture));
  515. }
  516. /// <summary>
  517. /// Gets the extracted ass path.
  518. /// </summary>
  519. /// <param name="state">The state.</param>
  520. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  521. /// <returns>System.String.</returns>
  522. private string GetExtractedAssPath(StreamState state, bool performConversion)
  523. {
  524. var path = EncodingManager.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream.Index, ".ass");
  525. if (performConversion)
  526. {
  527. InputType type;
  528. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  529. try
  530. {
  531. var parentPath = Path.GetDirectoryName(path);
  532. Directory.CreateDirectory(parentPath);
  533. // Don't re-encode ass/ssa to ass because ffmpeg ass encoder fails if there's more than one ass rectangle. Affect Anime mostly.
  534. // See https://lists.ffmpeg.org/pipermail/ffmpeg-cvslog/2013-April/063616.html
  535. var isAssSubtitle = string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase);
  536. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, isAssSubtitle, path, CancellationToken.None);
  537. Task.WaitAll(task);
  538. }
  539. catch
  540. {
  541. return null;
  542. }
  543. }
  544. return path;
  545. }
  546. /// <summary>
  547. /// Gets the converted ass path.
  548. /// </summary>
  549. /// <param name="mediaPath">The media path.</param>
  550. /// <param name="subtitleStream">The subtitle stream.</param>
  551. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  552. /// <returns>System.String.</returns>
  553. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  554. {
  555. var path = EncodingManager.GetSubtitleCachePath(subtitleStream.Path, ".ass");
  556. if (performConversion)
  557. {
  558. try
  559. {
  560. var parentPath = Path.GetDirectoryName(path);
  561. Directory.CreateDirectory(parentPath);
  562. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  563. Task.WaitAll(task);
  564. }
  565. catch
  566. {
  567. return null;
  568. }
  569. }
  570. return path;
  571. }
  572. /// <summary>
  573. /// Gets the internal graphical subtitle param.
  574. /// </summary>
  575. /// <param name="state">The state.</param>
  576. /// <param name="outputVideoCodec">The output video codec.</param>
  577. /// <returns>System.String.</returns>
  578. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  579. {
  580. var outputSizeParam = string.Empty;
  581. var request = state.VideoRequest;
  582. // Add resolution params, if specified
  583. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  584. {
  585. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  586. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  587. }
  588. var videoSizeParam = string.Empty;
  589. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  590. {
  591. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  592. }
  593. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  594. state.SubtitleStream.Index,
  595. state.VideoStream.Index,
  596. outputSizeParam,
  597. videoSizeParam);
  598. }
  599. /// <summary>
  600. /// Gets the probe size argument.
  601. /// </summary>
  602. /// <param name="mediaPath">The media path.</param>
  603. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  604. /// <param name="videoType">Type of the video.</param>
  605. /// <param name="isoType">Type of the iso.</param>
  606. /// <returns>System.String.</returns>
  607. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  608. {
  609. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  610. MediaEncoderHelpers.GetInputType(videoType, isoType);
  611. return MediaEncoder.GetProbeSizeArgument(type);
  612. }
  613. /// <summary>
  614. /// Gets the number of audio channels to specify on the command line
  615. /// </summary>
  616. /// <param name="request">The request.</param>
  617. /// <param name="audioStream">The audio stream.</param>
  618. /// <returns>System.Nullable{System.Int32}.</returns>
  619. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  620. {
  621. if (audioStream != null)
  622. {
  623. var codec = request.AudioCodec ?? string.Empty;
  624. if (audioStream.Channels > 2 && codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  625. {
  626. // wmav2 currently only supports two channel output
  627. return 2;
  628. }
  629. }
  630. if (request.MaxAudioChannels.HasValue)
  631. {
  632. if (audioStream != null && audioStream.Channels.HasValue)
  633. {
  634. return Math.Min(request.MaxAudioChannels.Value, audioStream.Channels.Value);
  635. }
  636. return request.MaxAudioChannels.Value;
  637. }
  638. return request.AudioChannels;
  639. }
  640. /// <summary>
  641. /// Determines whether the specified stream is H264.
  642. /// </summary>
  643. /// <param name="stream">The stream.</param>
  644. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  645. protected bool IsH264(MediaStream stream)
  646. {
  647. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  648. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  649. }
  650. /// <summary>
  651. /// Gets the name of the output audio codec
  652. /// </summary>
  653. /// <param name="request">The request.</param>
  654. /// <returns>System.String.</returns>
  655. protected string GetAudioCodec(StreamRequest request)
  656. {
  657. var codec = request.AudioCodec;
  658. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  659. {
  660. return "aac -strict experimental";
  661. }
  662. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  663. {
  664. return "libmp3lame";
  665. }
  666. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  667. {
  668. return "libvorbis";
  669. }
  670. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  671. {
  672. return "wmav2";
  673. }
  674. return codec.ToLower();
  675. }
  676. /// <summary>
  677. /// Gets the name of the output video codec
  678. /// </summary>
  679. /// <param name="request">The request.</param>
  680. /// <returns>System.String.</returns>
  681. protected string GetVideoCodec(VideoStreamRequest request)
  682. {
  683. var codec = request.VideoCodec;
  684. if (!string.IsNullOrEmpty(codec))
  685. {
  686. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  687. {
  688. return "libx264";
  689. }
  690. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  691. {
  692. return "libvpx";
  693. }
  694. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  695. {
  696. return "wmv2";
  697. }
  698. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  699. {
  700. return "libtheora";
  701. }
  702. return codec.ToLower();
  703. }
  704. return "copy";
  705. }
  706. /// <summary>
  707. /// Gets the input argument.
  708. /// </summary>
  709. /// <param name="state">The state.</param>
  710. /// <returns>System.String.</returns>
  711. protected string GetInputArgument(StreamState state)
  712. {
  713. var type = InputType.File;
  714. var inputPath = new[] { state.MediaPath };
  715. if (state.IsInputVideo)
  716. {
  717. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  718. {
  719. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  720. }
  721. }
  722. return MediaEncoder.GetInputArgument(inputPath, type);
  723. }
  724. /// <summary>
  725. /// Starts the FFMPEG.
  726. /// </summary>
  727. /// <param name="state">The state.</param>
  728. /// <param name="outputPath">The output path.</param>
  729. /// <returns>Task.</returns>
  730. protected async Task StartFfMpeg(StreamState state, string outputPath)
  731. {
  732. if (!File.Exists(MediaEncoder.EncoderPath))
  733. {
  734. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  735. }
  736. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  737. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  738. {
  739. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  740. }
  741. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  742. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  743. {
  744. commandLineArgs = "-loglevel debug " + commandLineArgs;
  745. }
  746. var process = new Process
  747. {
  748. StartInfo = new ProcessStartInfo
  749. {
  750. CreateNoWindow = true,
  751. UseShellExecute = false,
  752. // Must consume both stdout and stderr or deadlocks may occur
  753. RedirectStandardOutput = true,
  754. RedirectStandardError = true,
  755. FileName = MediaEncoder.EncoderPath,
  756. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  757. Arguments = commandLineArgs,
  758. WindowStyle = ProcessWindowStyle.Hidden,
  759. ErrorDialog = false
  760. },
  761. EnableRaisingEvents = true
  762. };
  763. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  764. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  765. Logger.Info(commandLineLogMessage);
  766. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  767. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  768. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  769. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  770. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  771. await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length).ConfigureAwait(false);
  772. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  773. try
  774. {
  775. process.Start();
  776. }
  777. catch (Exception ex)
  778. {
  779. Logger.ErrorException("Error starting ffmpeg", ex);
  780. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  781. state.LogFileStream.Dispose();
  782. throw;
  783. }
  784. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  785. process.BeginOutputReadLine();
  786. #pragma warning disable 4014
  787. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  788. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  789. #pragma warning restore 4014
  790. // Wait for the file to exist before proceeeding
  791. while (!File.Exists(outputPath))
  792. {
  793. await Task.Delay(100).ConfigureAwait(false);
  794. }
  795. // Allow a small amount of time to buffer a little
  796. if (state.IsInputVideo)
  797. {
  798. await Task.Delay(500).ConfigureAwait(false);
  799. }
  800. // This is arbitrary, but add a little buffer time when internet streaming
  801. if (state.IsRemote)
  802. {
  803. await Task.Delay(3000).ConfigureAwait(false);
  804. }
  805. }
  806. protected int? GetVideoBitrateParamValue(StreamState state)
  807. {
  808. var bitrate = state.VideoRequest.VideoBitRate;
  809. if (state.VideoStream != null)
  810. {
  811. var isUpscaling = state.VideoRequest.Height.HasValue && state.VideoStream.Height.HasValue &&
  812. state.VideoRequest.Height.Value > state.VideoStream.Height.Value;
  813. if (state.VideoRequest.Width.HasValue && state.VideoStream.Width.HasValue &&
  814. state.VideoRequest.Width.Value > state.VideoStream.Width.Value)
  815. {
  816. isUpscaling = true;
  817. }
  818. // Don't allow bitrate increases unless upscaling
  819. if (!isUpscaling)
  820. {
  821. if (bitrate.HasValue && state.VideoStream.BitRate.HasValue)
  822. {
  823. bitrate = Math.Min(bitrate.Value, state.VideoStream.BitRate.Value);
  824. }
  825. }
  826. }
  827. return bitrate;
  828. }
  829. protected string GetVideoBitrateParam(StreamState state, string videoCodec, bool isHls)
  830. {
  831. var bitrate = GetVideoBitrateParamValue(state);
  832. if (bitrate.HasValue)
  833. {
  834. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  835. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  836. {
  837. if (hasFixedResolution)
  838. {
  839. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  840. }
  841. // With vpx when crf is used, b:v becomes a max rate
  842. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide. But higher bitrate source files -b:v causes judder so limite the bitrate but dont allow it to "saturate" the bitrate. So dont contrain it down just up.
  843. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  844. }
  845. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  846. {
  847. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  848. }
  849. // H264
  850. if (hasFixedResolution)
  851. {
  852. if (isHls)
  853. {
  854. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  855. }
  856. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  857. }
  858. return string.Format(" -maxrate {0} -bufsize {1}",
  859. bitrate.Value.ToString(UsCulture),
  860. (bitrate.Value * 2).ToString(UsCulture));
  861. }
  862. return string.Empty;
  863. }
  864. protected int? GetAudioBitrateParam(StreamState state)
  865. {
  866. if (state.Request.AudioBitRate.HasValue)
  867. {
  868. // Make sure we don't request a bitrate higher than the source
  869. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  870. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  871. }
  872. return null;
  873. }
  874. /// <summary>
  875. /// Gets the user agent param.
  876. /// </summary>
  877. /// <param name="path">The path.</param>
  878. /// <returns>System.String.</returns>
  879. private string GetUserAgentParam(string path)
  880. {
  881. var useragent = GetUserAgent(path);
  882. if (!string.IsNullOrEmpty(useragent))
  883. {
  884. return "-user-agent \"" + useragent + "\"";
  885. }
  886. return string.Empty;
  887. }
  888. /// <summary>
  889. /// Gets the user agent.
  890. /// </summary>
  891. /// <param name="path">The path.</param>
  892. /// <returns>System.String.</returns>
  893. protected string GetUserAgent(string path)
  894. {
  895. if (string.IsNullOrEmpty(path))
  896. {
  897. throw new ArgumentNullException("path");
  898. }
  899. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  900. {
  901. return "QuickTime/7.7.4";
  902. }
  903. return string.Empty;
  904. }
  905. /// <summary>
  906. /// Processes the exited.
  907. /// </summary>
  908. /// <param name="process">The process.</param>
  909. /// <param name="state">The state.</param>
  910. protected async void OnFfMpegProcessExited(Process process, StreamState state)
  911. {
  912. if (state.IsoMount != null)
  913. {
  914. state.IsoMount.Dispose();
  915. state.IsoMount = null;
  916. }
  917. if (state.StandardInputCancellationTokenSource != null)
  918. {
  919. state.StandardInputCancellationTokenSource.Cancel();
  920. }
  921. var outputFilePath = GetOutputFilePath(state);
  922. state.LogFileStream.Dispose();
  923. try
  924. {
  925. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  926. }
  927. catch
  928. {
  929. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  930. }
  931. if (!string.IsNullOrEmpty(state.LiveTvStreamId))
  932. {
  933. try
  934. {
  935. await LiveTvManager.CloseLiveStream(state.LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  936. }
  937. catch (Exception ex)
  938. {
  939. Logger.ErrorException("Error closing live tv stream", ex);
  940. }
  941. }
  942. }
  943. protected double? GetFramerateParam(StreamState state)
  944. {
  945. if (state.VideoRequest != null)
  946. {
  947. if (state.VideoRequest.Framerate.HasValue)
  948. {
  949. return state.VideoRequest.Framerate.Value;
  950. }
  951. var maxrate = state.VideoRequest.MaxFramerate ?? 23.97602;
  952. if (state.VideoStream != null)
  953. {
  954. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  955. if (contentRate.HasValue && contentRate.Value > maxrate)
  956. {
  957. return maxrate;
  958. }
  959. }
  960. }
  961. return null;
  962. }
  963. /// <summary>
  964. /// Parses the parameters.
  965. /// </summary>
  966. /// <param name="request">The request.</param>
  967. private void ParseParams(StreamRequest request)
  968. {
  969. var vals = request.Params.Split(';');
  970. var videoRequest = request as VideoStreamRequest;
  971. for (var i = 0; i < vals.Length; i++)
  972. {
  973. var val = vals[i];
  974. if (string.IsNullOrWhiteSpace(val))
  975. {
  976. continue;
  977. }
  978. if (i == 0)
  979. {
  980. request.DeviceProfileId = val;
  981. }
  982. else if (i == 1)
  983. {
  984. request.DeviceId = val;
  985. }
  986. else if (i == 2)
  987. {
  988. request.MediaSourceId = val;
  989. }
  990. else if (i == 3)
  991. {
  992. request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  993. }
  994. else if (i == 4)
  995. {
  996. if (videoRequest != null)
  997. {
  998. videoRequest.VideoCodec = val;
  999. }
  1000. }
  1001. else if (i == 5)
  1002. {
  1003. request.AudioCodec = val;
  1004. }
  1005. else if (i == 6)
  1006. {
  1007. if (videoRequest != null)
  1008. {
  1009. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  1010. }
  1011. }
  1012. else if (i == 7)
  1013. {
  1014. if (videoRequest != null)
  1015. {
  1016. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  1017. }
  1018. }
  1019. else if (i == 8)
  1020. {
  1021. if (videoRequest != null)
  1022. {
  1023. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  1024. }
  1025. }
  1026. else if (i == 9)
  1027. {
  1028. request.AudioBitRate = int.Parse(val, UsCulture);
  1029. }
  1030. else if (i == 10)
  1031. {
  1032. request.MaxAudioChannels = int.Parse(val, UsCulture);
  1033. }
  1034. else if (i == 11)
  1035. {
  1036. if (videoRequest != null)
  1037. {
  1038. videoRequest.MaxFramerate = double.Parse(val, UsCulture);
  1039. }
  1040. }
  1041. else if (i == 12)
  1042. {
  1043. if (videoRequest != null)
  1044. {
  1045. videoRequest.MaxWidth = int.Parse(val, UsCulture);
  1046. }
  1047. }
  1048. else if (i == 13)
  1049. {
  1050. if (videoRequest != null)
  1051. {
  1052. videoRequest.MaxHeight = int.Parse(val, UsCulture);
  1053. }
  1054. }
  1055. else if (i == 14)
  1056. {
  1057. request.StartTimeTicks = long.Parse(val, UsCulture);
  1058. }
  1059. else if (i == 15)
  1060. {
  1061. if (videoRequest != null)
  1062. {
  1063. videoRequest.Level = val;
  1064. }
  1065. }
  1066. }
  1067. }
  1068. /// <summary>
  1069. /// Parses the dlna headers.
  1070. /// </summary>
  1071. /// <param name="request">The request.</param>
  1072. private void ParseDlnaHeaders(StreamRequest request)
  1073. {
  1074. if (!request.StartTimeTicks.HasValue)
  1075. {
  1076. var timeSeek = GetHeader("TimeSeekRange.dlna.org");
  1077. request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
  1078. }
  1079. }
  1080. /// <summary>
  1081. /// Parses the time seek header.
  1082. /// </summary>
  1083. private long? ParseTimeSeekHeader(string value)
  1084. {
  1085. if (string.IsNullOrWhiteSpace(value))
  1086. {
  1087. return null;
  1088. }
  1089. if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
  1090. {
  1091. throw new ArgumentException("Invalid timeseek header");
  1092. }
  1093. value = value.Substring(4).Split(new[] { '-' }, 2)[0];
  1094. if (value.IndexOf(':') == -1)
  1095. {
  1096. // Parses npt times in the format of '417.33'
  1097. double seconds;
  1098. if (double.TryParse(value, NumberStyles.Any, UsCulture, out seconds))
  1099. {
  1100. return TimeSpan.FromSeconds(seconds).Ticks;
  1101. }
  1102. throw new ArgumentException("Invalid timeseek header");
  1103. }
  1104. // Parses npt times in the format of '10:19:25.7'
  1105. var tokens = value.Split(new[] { ':' }, 3);
  1106. double secondsSum = 0;
  1107. var timeFactor = 3600;
  1108. foreach (var time in tokens)
  1109. {
  1110. double digit;
  1111. if (double.TryParse(time, NumberStyles.Any, UsCulture, out digit))
  1112. {
  1113. secondsSum += (digit * timeFactor);
  1114. }
  1115. else
  1116. {
  1117. throw new ArgumentException("Invalid timeseek header");
  1118. }
  1119. timeFactor /= 60;
  1120. }
  1121. return TimeSpan.FromSeconds(secondsSum).Ticks;
  1122. }
  1123. /// <summary>
  1124. /// Gets the state.
  1125. /// </summary>
  1126. /// <param name="request">The request.</param>
  1127. /// <param name="cancellationToken">The cancellation token.</param>
  1128. /// <returns>StreamState.</returns>
  1129. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  1130. {
  1131. ParseDlnaHeaders(request);
  1132. if (!string.IsNullOrWhiteSpace(request.Params))
  1133. {
  1134. ParseParams(request);
  1135. }
  1136. var user = AuthorizationRequestFilterAttribute.GetCurrentUser(Request, UserManager);
  1137. var url = Request.PathInfo;
  1138. if (string.IsNullOrEmpty(request.AudioCodec))
  1139. {
  1140. request.AudioCodec = InferAudioCodec(url);
  1141. }
  1142. var state = new StreamState
  1143. {
  1144. Request = request,
  1145. RequestedUrl = url
  1146. };
  1147. var item = string.IsNullOrEmpty(request.MediaSourceId) ?
  1148. DtoService.GetItemByDtoId(request.Id) :
  1149. DtoService.GetItemByDtoId(request.MediaSourceId);
  1150. if (user != null && item.GetPlayAccess(user) != PlayAccess.Full)
  1151. {
  1152. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  1153. }
  1154. if (item is ILiveTvRecording)
  1155. {
  1156. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  1157. state.VideoType = VideoType.VideoFile;
  1158. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1159. state.PlayableStreamFileNames = new List<string>();
  1160. var path = recording.RecordingInfo.Path;
  1161. var mediaUrl = recording.RecordingInfo.Url;
  1162. if (string.IsNullOrWhiteSpace(path) && string.IsNullOrWhiteSpace(mediaUrl))
  1163. {
  1164. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  1165. state.LiveTvStreamId = streamInfo.Id;
  1166. path = streamInfo.Path;
  1167. mediaUrl = streamInfo.Url;
  1168. }
  1169. if (!string.IsNullOrEmpty(path) && File.Exists(path))
  1170. {
  1171. state.MediaPath = path;
  1172. state.IsRemote = false;
  1173. }
  1174. else if (!string.IsNullOrEmpty(mediaUrl))
  1175. {
  1176. state.MediaPath = mediaUrl;
  1177. state.IsRemote = true;
  1178. }
  1179. state.RunTimeTicks = recording.RunTimeTicks;
  1180. if (recording.RecordingInfo.Status == RecordingStatus.InProgress && !state.IsRemote)
  1181. {
  1182. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1183. }
  1184. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  1185. state.AudioSync = "1000";
  1186. state.DeInterlace = true;
  1187. state.InputVideoSync = "-1";
  1188. state.InputAudioSync = "1";
  1189. }
  1190. else if (item is LiveTvChannel)
  1191. {
  1192. var channel = LiveTvManager.GetInternalChannel(request.Id);
  1193. state.VideoType = VideoType.VideoFile;
  1194. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1195. state.PlayableStreamFileNames = new List<string>();
  1196. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  1197. state.LiveTvStreamId = streamInfo.Id;
  1198. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  1199. {
  1200. state.MediaPath = streamInfo.Path;
  1201. state.IsRemote = false;
  1202. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1203. }
  1204. else if (!string.IsNullOrEmpty(streamInfo.Url))
  1205. {
  1206. state.MediaPath = streamInfo.Url;
  1207. state.IsRemote = true;
  1208. }
  1209. state.ReadInputAtNativeFramerate = true;
  1210. state.AudioSync = "1000";
  1211. state.DeInterlace = true;
  1212. state.InputVideoSync = "-1";
  1213. state.InputAudioSync = "1";
  1214. }
  1215. else
  1216. {
  1217. state.MediaPath = item.Path;
  1218. state.IsRemote = item.LocationType == LocationType.Remote;
  1219. var video = item as Video;
  1220. if (video != null)
  1221. {
  1222. state.IsInputVideo = true;
  1223. state.VideoType = video.VideoType;
  1224. state.IsoType = video.IsoType;
  1225. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  1226. ? new List<string>()
  1227. : video.PlayableStreamFileNames.ToList();
  1228. }
  1229. state.RunTimeTicks = item.RunTimeTicks;
  1230. }
  1231. var videoRequest = request as VideoStreamRequest;
  1232. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  1233. {
  1234. ItemId = item.Id
  1235. }).ToList();
  1236. if (videoRequest != null)
  1237. {
  1238. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  1239. {
  1240. videoRequest.VideoCodec = InferVideoCodec(url);
  1241. }
  1242. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1243. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1244. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1245. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  1246. {
  1247. state.DeInterlace = true;
  1248. }
  1249. EnforceResolutionLimit(state, videoRequest);
  1250. }
  1251. else
  1252. {
  1253. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1254. }
  1255. state.HasMediaStreams = mediaStreams.Count > 0;
  1256. state.SegmentLength = state.ReadInputAtNativeFramerate ? 5 : 10;
  1257. state.HlsListSize = state.ReadInputAtNativeFramerate ? 100 : 1440;
  1258. ApplyDeviceProfileSettings(state);
  1259. if (videoRequest != null && state.VideoStream != null)
  1260. {
  1261. if (CanStreamCopyVideo(videoRequest, state.VideoStream, state.VideoType))
  1262. {
  1263. videoRequest.VideoCodec = "copy";
  1264. }
  1265. }
  1266. return state;
  1267. }
  1268. private bool CanStreamCopyVideo(VideoStreamRequest request, MediaStream videoStream, VideoType videoType)
  1269. {
  1270. if (videoStream.IsInterlaced)
  1271. {
  1272. return false;
  1273. }
  1274. // Not going to attempt this with folder rips
  1275. if (videoType != VideoType.VideoFile)
  1276. {
  1277. return false;
  1278. }
  1279. // Source and target codecs must match
  1280. if (!string.Equals(request.VideoCodec, videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  1281. {
  1282. return false;
  1283. }
  1284. // If client is requesting a specific video profile, it must match the source
  1285. if (!string.IsNullOrEmpty(request.Profile) && !string.Equals(request.Profile, videoStream.Profile))
  1286. {
  1287. return false;
  1288. }
  1289. // Video width must fall within requested value
  1290. if (request.MaxWidth.HasValue)
  1291. {
  1292. if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
  1293. {
  1294. return false;
  1295. }
  1296. }
  1297. // Video height must fall within requested value
  1298. if (request.MaxHeight.HasValue)
  1299. {
  1300. if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
  1301. {
  1302. return false;
  1303. }
  1304. }
  1305. // Video framerate must fall within requested value
  1306. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  1307. if (requestedFramerate.HasValue)
  1308. {
  1309. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  1310. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  1311. {
  1312. return false;
  1313. }
  1314. }
  1315. // Video bitrate must fall within requested value
  1316. if (request.VideoBitRate.HasValue)
  1317. {
  1318. if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
  1319. {
  1320. return false;
  1321. }
  1322. }
  1323. // If a specific level was requested, the source must match or be less than
  1324. if (!string.IsNullOrEmpty(request.Level))
  1325. {
  1326. double requestLevel;
  1327. if (double.TryParse(request.Level, NumberStyles.Any, UsCulture, out requestLevel))
  1328. {
  1329. if (!videoStream.Level.HasValue)
  1330. {
  1331. return false;
  1332. }
  1333. if (videoStream.Level.Value > requestLevel)
  1334. {
  1335. return false;
  1336. }
  1337. }
  1338. return false;
  1339. }
  1340. return SupportsAutomaticVideoStreamCopy;
  1341. }
  1342. protected virtual bool SupportsAutomaticVideoStreamCopy
  1343. {
  1344. get
  1345. {
  1346. return false;
  1347. }
  1348. }
  1349. private void ApplyDeviceProfileSettings(StreamState state)
  1350. {
  1351. var headers = new Dictionary<string, string>();
  1352. foreach (var key in Request.Headers.AllKeys)
  1353. {
  1354. headers[key] = Request.Headers[key];
  1355. }
  1356. var profile = string.IsNullOrWhiteSpace(state.Request.DeviceProfileId) ?
  1357. DlnaManager.GetProfile(headers) :
  1358. DlnaManager.GetProfile(state.Request.DeviceProfileId);
  1359. if (profile == null)
  1360. {
  1361. // Don't use settings from the default profile.
  1362. // Only use a specific profile if it was requested.
  1363. return;
  1364. }
  1365. var container = Path.GetExtension(state.RequestedUrl);
  1366. if (string.IsNullOrEmpty(container))
  1367. {
  1368. container = Path.GetExtension(GetOutputFilePath(state));
  1369. }
  1370. var audioCodec = state.Request.AudioCodec;
  1371. if (string.Equals(audioCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.AudioStream != null)
  1372. {
  1373. audioCodec = state.AudioStream.Codec;
  1374. }
  1375. var videoCodec = state.VideoRequest == null ? null : state.VideoRequest.VideoCodec;
  1376. if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.VideoStream != null)
  1377. {
  1378. videoCodec = state.VideoStream.Codec;
  1379. }
  1380. var mediaProfile = state.VideoRequest == null ?
  1381. profile.GetAudioMediaProfile(container, audioCodec, state.AudioStream) :
  1382. profile.GetVideoMediaProfile(container, audioCodec, videoCodec, state.AudioStream, state.VideoStream);
  1383. if (mediaProfile != null)
  1384. {
  1385. state.MimeType = mediaProfile.MimeType;
  1386. state.OrgPn = mediaProfile.OrgPn;
  1387. }
  1388. var transcodingProfile = state.VideoRequest == null ?
  1389. profile.GetAudioTranscodingProfile(container, audioCodec) :
  1390. profile.GetVideoTranscodingProfile(container, audioCodec, videoCodec);
  1391. if (transcodingProfile != null)
  1392. {
  1393. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  1394. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  1395. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  1396. if (state.VideoRequest != null && string.IsNullOrWhiteSpace(state.VideoRequest.Profile))
  1397. {
  1398. state.VideoRequest.Profile = transcodingProfile.VideoProfile;
  1399. }
  1400. }
  1401. }
  1402. /// <summary>
  1403. /// Adds the dlna headers.
  1404. /// </summary>
  1405. /// <param name="state">The state.</param>
  1406. /// <param name="responseHeaders">The response headers.</param>
  1407. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  1408. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1409. protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  1410. {
  1411. var transferMode = GetHeader("transferMode.dlna.org");
  1412. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  1413. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  1414. var contentFeatures = string.Empty;
  1415. var extension = GetOutputFileExtension(state);
  1416. // first bit means Time based seek supported, second byte range seek supported (not sure about the order now), so 01 = only byte seek, 10 = time based, 11 = both, 00 = none
  1417. var orgOp = ";DLNA.ORG_OP=";
  1418. if (state.RunTimeTicks.HasValue)
  1419. {
  1420. // Time-based seeking currently only possible when transcoding
  1421. orgOp += isStaticallyStreamed ? "0" : "1";
  1422. // Byte-based seeking only possible when not transcoding
  1423. orgOp += isStaticallyStreamed || state.TranscodeSeekInfo == TranscodeSeekInfo.Bytes ? "1" : "0";
  1424. if (!isStaticallyStreamed)
  1425. {
  1426. AddTimeSeekResponseHeaders(state, responseHeaders);
  1427. }
  1428. }
  1429. else
  1430. {
  1431. // No seeking is available if we don't know the content runtime
  1432. orgOp += "00";
  1433. }
  1434. // 0 = native, 1 = transcoded
  1435. var orgCi = isStaticallyStreamed ? ";DLNA.ORG_CI=0" : ";DLNA.ORG_CI=1";
  1436. const string dlnaflags = ";DLNA.ORG_FLAGS=01500000000000000000000000000000";
  1437. if (!string.IsNullOrWhiteSpace(state.OrgPn))
  1438. {
  1439. contentFeatures = "DLNA.ORG_PN=" + state.OrgPn;
  1440. }
  1441. else if (string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase))
  1442. {
  1443. contentFeatures = "DLNA.ORG_PN=MP3";
  1444. }
  1445. else if (string.Equals(extension, ".aac", StringComparison.OrdinalIgnoreCase))
  1446. {
  1447. contentFeatures = "DLNA.ORG_PN=AAC_ISO";
  1448. }
  1449. else if (string.Equals(extension, ".wma", StringComparison.OrdinalIgnoreCase))
  1450. {
  1451. contentFeatures = "DLNA.ORG_PN=WMABASE";
  1452. }
  1453. else if (string.Equals(extension, ".avi", StringComparison.OrdinalIgnoreCase))
  1454. {
  1455. contentFeatures = "DLNA.ORG_PN=AVI";
  1456. }
  1457. else if (string.Equals(extension, ".mkv", StringComparison.OrdinalIgnoreCase))
  1458. {
  1459. contentFeatures = "DLNA.ORG_PN=MATROSKA";
  1460. }
  1461. else if (string.Equals(extension, ".mp4", StringComparison.OrdinalIgnoreCase))
  1462. {
  1463. contentFeatures = "DLNA.ORG_PN=AVC_MP4_MP_HD_720p_AAC";
  1464. }
  1465. else if (string.Equals(extension, ".mpeg", StringComparison.OrdinalIgnoreCase))
  1466. {
  1467. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1468. }
  1469. else if (string.Equals(extension, ".ts", StringComparison.OrdinalIgnoreCase))
  1470. {
  1471. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1472. }
  1473. if (!string.IsNullOrEmpty(contentFeatures))
  1474. {
  1475. responseHeaders["contentFeatures.dlna.org"] = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
  1476. }
  1477. foreach (var item in responseHeaders)
  1478. {
  1479. Request.Response.AddHeader(item.Key, item.Value);
  1480. }
  1481. }
  1482. private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
  1483. {
  1484. var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
  1485. var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
  1486. responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
  1487. responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
  1488. }
  1489. /// <summary>
  1490. /// Enforces the resolution limit.
  1491. /// </summary>
  1492. /// <param name="state">The state.</param>
  1493. /// <param name="videoRequest">The video request.</param>
  1494. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1495. {
  1496. // If enabled, allow whatever the client asks for
  1497. if (ServerConfigurationManager.Configuration.AllowVideoUpscaling)
  1498. {
  1499. return;
  1500. }
  1501. // Switch the incoming params to be ceilings rather than fixed values
  1502. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1503. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1504. videoRequest.Width = null;
  1505. videoRequest.Height = null;
  1506. }
  1507. protected string GetInputModifier(StreamState state)
  1508. {
  1509. var inputModifier = string.Empty;
  1510. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  1511. inputModifier += " " + probeSize;
  1512. inputModifier = inputModifier.Trim();
  1513. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  1514. inputModifier = inputModifier.Trim();
  1515. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1516. inputModifier = inputModifier.Trim();
  1517. if (state.VideoRequest != null)
  1518. {
  1519. inputModifier += " -fflags genpts";
  1520. }
  1521. if (!string.IsNullOrEmpty(state.InputFormat))
  1522. {
  1523. inputModifier += " -f " + state.InputFormat;
  1524. }
  1525. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  1526. {
  1527. inputModifier += " -vcodec " + state.InputVideoCodec;
  1528. }
  1529. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  1530. {
  1531. inputModifier += " -acodec " + state.InputAudioCodec;
  1532. }
  1533. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1534. {
  1535. inputModifier += " -async " + state.InputAudioSync;
  1536. }
  1537. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1538. {
  1539. inputModifier += " -vsync " + state.InputVideoSync;
  1540. }
  1541. if (state.ReadInputAtNativeFramerate)
  1542. {
  1543. inputModifier += " -re";
  1544. }
  1545. return inputModifier;
  1546. }
  1547. /// <summary>
  1548. /// Infers the audio codec based on the url
  1549. /// </summary>
  1550. /// <param name="url">The URL.</param>
  1551. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1552. private string InferAudioCodec(string url)
  1553. {
  1554. var ext = Path.GetExtension(url);
  1555. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1556. {
  1557. return "mp3";
  1558. }
  1559. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1560. {
  1561. return "aac";
  1562. }
  1563. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1564. {
  1565. return "wma";
  1566. }
  1567. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1568. {
  1569. return "vorbis";
  1570. }
  1571. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1572. {
  1573. return "vorbis";
  1574. }
  1575. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1576. {
  1577. return "vorbis";
  1578. }
  1579. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1580. {
  1581. return "vorbis";
  1582. }
  1583. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1584. {
  1585. return "vorbis";
  1586. }
  1587. return "copy";
  1588. }
  1589. /// <summary>
  1590. /// Infers the video codec.
  1591. /// </summary>
  1592. /// <param name="url">The URL.</param>
  1593. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1594. private string InferVideoCodec(string url)
  1595. {
  1596. var ext = Path.GetExtension(url);
  1597. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1598. {
  1599. return "wmv";
  1600. }
  1601. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1602. {
  1603. return "vpx";
  1604. }
  1605. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1606. {
  1607. return "theora";
  1608. }
  1609. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1610. {
  1611. return "h264";
  1612. }
  1613. return "copy";
  1614. }
  1615. }
  1616. }