BaseStreamingService.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Dto;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.LiveTv;
  8. using MediaBrowser.Controller.MediaInfo;
  9. using MediaBrowser.Controller.Persistence;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.Drawing;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.LiveTv;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Diagnostics;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. namespace MediaBrowser.Api.Playback
  25. {
  26. /// <summary>
  27. /// Class BaseStreamingService
  28. /// </summary>
  29. public abstract class BaseStreamingService : BaseApiService
  30. {
  31. /// <summary>
  32. /// Gets or sets the application paths.
  33. /// </summary>
  34. /// <value>The application paths.</value>
  35. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  36. /// <summary>
  37. /// Gets or sets the user manager.
  38. /// </summary>
  39. /// <value>The user manager.</value>
  40. protected IUserManager UserManager { get; private set; }
  41. /// <summary>
  42. /// Gets or sets the library manager.
  43. /// </summary>
  44. /// <value>The library manager.</value>
  45. protected ILibraryManager LibraryManager { get; private set; }
  46. /// <summary>
  47. /// Gets or sets the iso manager.
  48. /// </summary>
  49. /// <value>The iso manager.</value>
  50. protected IIsoManager IsoManager { get; private set; }
  51. /// <summary>
  52. /// Gets or sets the media encoder.
  53. /// </summary>
  54. /// <value>The media encoder.</value>
  55. protected IMediaEncoder MediaEncoder { get; private set; }
  56. protected IDtoService DtoService { get; private set; }
  57. protected IFileSystem FileSystem { get; private set; }
  58. protected IItemRepository ItemRepository { get; private set; }
  59. protected ILiveTvManager LiveTvManager { get; private set; }
  60. /// <summary>
  61. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  62. /// </summary>
  63. /// <param name="serverConfig">The server configuration.</param>
  64. /// <param name="userManager">The user manager.</param>
  65. /// <param name="libraryManager">The library manager.</param>
  66. /// <param name="isoManager">The iso manager.</param>
  67. /// <param name="mediaEncoder">The media encoder.</param>
  68. /// <param name="dtoService">The dto service.</param>
  69. /// <param name="fileSystem">The file system.</param>
  70. /// <param name="itemRepository">The item repository.</param>
  71. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager)
  72. {
  73. LiveTvManager = liveTvManager;
  74. ItemRepository = itemRepository;
  75. FileSystem = fileSystem;
  76. DtoService = dtoService;
  77. ServerConfigurationManager = serverConfig;
  78. UserManager = userManager;
  79. LibraryManager = libraryManager;
  80. IsoManager = isoManager;
  81. MediaEncoder = mediaEncoder;
  82. }
  83. /// <summary>
  84. /// Gets the command line arguments.
  85. /// </summary>
  86. /// <param name="outputPath">The output path.</param>
  87. /// <param name="state">The state.</param>
  88. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  89. /// <returns>System.String.</returns>
  90. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions);
  91. /// <summary>
  92. /// Gets the type of the transcoding job.
  93. /// </summary>
  94. /// <value>The type of the transcoding job.</value>
  95. protected abstract TranscodingJobType TranscodingJobType { get; }
  96. /// <summary>
  97. /// Gets the output file extension.
  98. /// </summary>
  99. /// <param name="state">The state.</param>
  100. /// <returns>System.String.</returns>
  101. protected virtual string GetOutputFileExtension(StreamState state)
  102. {
  103. return Path.GetExtension(state.RequestedUrl);
  104. }
  105. /// <summary>
  106. /// Gets the output file path.
  107. /// </summary>
  108. /// <param name="state">The state.</param>
  109. /// <returns>System.String.</returns>
  110. protected virtual string GetOutputFilePath(StreamState state)
  111. {
  112. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  113. var outputFileExtension = GetOutputFileExtension(state);
  114. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  115. }
  116. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  117. /// <summary>
  118. /// The fast seek offset seconds
  119. /// </summary>
  120. private const int FastSeekOffsetSeconds = 1;
  121. /// <summary>
  122. /// Gets the fast seek command line parameter.
  123. /// </summary>
  124. /// <param name="request">The request.</param>
  125. /// <returns>System.String.</returns>
  126. /// <value>The fast seek command line parameter.</value>
  127. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  128. {
  129. var time = request.StartTimeTicks;
  130. if (time.HasValue)
  131. {
  132. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds;
  133. if (seconds > 0)
  134. {
  135. return string.Format("-ss {0}", seconds.ToString(UsCulture));
  136. }
  137. }
  138. return string.Empty;
  139. }
  140. /// <summary>
  141. /// Gets the slow seek command line parameter.
  142. /// </summary>
  143. /// <param name="request">The request.</param>
  144. /// <returns>System.String.</returns>
  145. /// <value>The slow seek command line parameter.</value>
  146. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  147. {
  148. var time = request.StartTimeTicks;
  149. if (time.HasValue)
  150. {
  151. if (TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds > 0)
  152. {
  153. return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture));
  154. }
  155. }
  156. return string.Empty;
  157. }
  158. /// <summary>
  159. /// Gets the map args.
  160. /// </summary>
  161. /// <param name="state">The state.</param>
  162. /// <returns>System.String.</returns>
  163. protected virtual string GetMapArgs(StreamState state)
  164. {
  165. var args = string.Empty;
  166. if (state.IsRemote || !state.HasMediaStreams)
  167. {
  168. return string.Empty;
  169. }
  170. if (state.VideoStream != null)
  171. {
  172. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  173. }
  174. else
  175. {
  176. args += "-map -0:v";
  177. }
  178. if (state.AudioStream != null)
  179. {
  180. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  181. }
  182. else
  183. {
  184. args += " -map -0:a";
  185. }
  186. if (state.SubtitleStream == null)
  187. {
  188. args += " -map -0:s";
  189. }
  190. return args;
  191. }
  192. /// <summary>
  193. /// Determines which stream will be used for playback
  194. /// </summary>
  195. /// <param name="allStream">All stream.</param>
  196. /// <param name="desiredIndex">Index of the desired.</param>
  197. /// <param name="type">The type.</param>
  198. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  199. /// <returns>MediaStream.</returns>
  200. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  201. {
  202. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  203. if (desiredIndex.HasValue)
  204. {
  205. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  206. if (stream != null)
  207. {
  208. return stream;
  209. }
  210. }
  211. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  212. {
  213. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  214. streams.FirstOrDefault();
  215. }
  216. // Just return the first one
  217. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  218. }
  219. protected EncodingQuality GetQualitySetting()
  220. {
  221. var quality = ServerConfigurationManager.Configuration.MediaEncodingQuality;
  222. if (quality == EncodingQuality.Auto)
  223. {
  224. var cpuCount = Environment.ProcessorCount;
  225. if (cpuCount >= 4)
  226. {
  227. return EncodingQuality.HighQuality;
  228. }
  229. return EncodingQuality.HighSpeed;
  230. }
  231. return quality;
  232. }
  233. /// <summary>
  234. /// Gets the number of threads.
  235. /// </summary>
  236. /// <returns>System.Int32.</returns>
  237. /// <exception cref="System.Exception">Unrecognized MediaEncodingQuality value.</exception>
  238. protected int GetNumberOfThreads(bool isWebm)
  239. {
  240. // Webm: http://www.webmproject.org/docs/encoder-parameters/
  241. // 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
  242. // for the coefficient data if the encoder selected --token-parts > 0 at encode time.
  243. switch (GetQualitySetting())
  244. {
  245. case EncodingQuality.HighSpeed:
  246. return 2;
  247. case EncodingQuality.HighQuality:
  248. return 2;
  249. case EncodingQuality.MaxQuality:
  250. return isWebm ? 2 : 0;
  251. default:
  252. throw new Exception("Unrecognized MediaEncodingQuality value.");
  253. }
  254. }
  255. /// <summary>
  256. /// Gets the video bitrate to specify on the command line
  257. /// </summary>
  258. /// <param name="state">The state.</param>
  259. /// <param name="videoCodec">The video codec.</param>
  260. /// <returns>System.String.</returns>
  261. protected string GetVideoQualityParam(StreamState state, string videoCodec)
  262. {
  263. // webm
  264. if (videoCodec.Equals("libvpx", StringComparison.OrdinalIgnoreCase))
  265. {
  266. // http://www.webmproject.org/docs/encoder-parameters/
  267. return "-speed 16 -quality good -profile:v 0 -slices 8";
  268. }
  269. // asf/wmv
  270. if (videoCodec.Equals("wmv2", StringComparison.OrdinalIgnoreCase))
  271. {
  272. return "-g 100 -qmax 15";
  273. }
  274. if (videoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase))
  275. {
  276. switch (GetQualitySetting())
  277. {
  278. case EncodingQuality.HighSpeed:
  279. return "-preset ultrafast";
  280. case EncodingQuality.HighQuality:
  281. return "-preset superfast";
  282. case EncodingQuality.MaxQuality:
  283. return "-preset superfast";
  284. default:
  285. throw new Exception("Unrecognized MediaEncodingQuality value.");
  286. }
  287. }
  288. if (videoCodec.Equals("mpeg4", StringComparison.OrdinalIgnoreCase))
  289. {
  290. return "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  291. }
  292. return string.Empty;
  293. }
  294. protected string GetAudioFilterParam(StreamState state, bool isHls)
  295. {
  296. var volParam = string.Empty;
  297. var audioSampleRate = string.Empty;
  298. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  299. // Boost volume to 200% when downsampling from 6ch to 2ch
  300. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  301. {
  302. volParam = ",volume=2.000000";
  303. }
  304. if (state.Request.AudioSampleRate.HasValue)
  305. {
  306. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  307. }
  308. var adelay = isHls ? "adelay=1," : string.Empty;
  309. var pts = string.Empty;
  310. if (state.SubtitleStream != null)
  311. {
  312. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  313. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  314. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  315. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  316. {
  317. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  318. pts = string.Format(",asetpts=PTS-{0}/TB",
  319. Math.Round(seconds).ToString(UsCulture));
  320. }
  321. }
  322. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  323. adelay,
  324. audioSampleRate,
  325. volParam,
  326. pts,
  327. state.AudioSync.ToString(UsCulture));
  328. }
  329. /// <summary>
  330. /// If we're going to put a fixed size on the command line, this will calculate it
  331. /// </summary>
  332. /// <param name="state">The state.</param>
  333. /// <param name="outputVideoCodec">The output video codec.</param>
  334. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  335. /// <returns>System.String.</returns>
  336. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  337. {
  338. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  339. var assSubtitleParam = string.Empty;
  340. var copyTsParam = string.Empty;
  341. var yadifParam = state.DeInterlace ? "yadif=0:-1:0," : string.Empty;
  342. var request = state.VideoRequest;
  343. if (state.SubtitleStream != null)
  344. {
  345. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  346. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  347. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  348. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  349. {
  350. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  351. copyTsParam = " -copyts";
  352. }
  353. }
  354. // If fixed dimensions were supplied
  355. if (request.Width.HasValue && request.Height.HasValue)
  356. {
  357. var widthParam = request.Width.Value.ToString(UsCulture);
  358. var heightParam = request.Height.Value.ToString(UsCulture);
  359. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  360. }
  361. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  362. // If a fixed width was requested
  363. if (request.Width.HasValue)
  364. {
  365. var widthParam = request.Width.Value.ToString(UsCulture);
  366. return isH264Output ?
  367. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  368. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam);
  369. }
  370. // If a fixed height was requested
  371. if (request.Height.HasValue)
  372. {
  373. var heightParam = request.Height.Value.ToString(UsCulture);
  374. return isH264Output ?
  375. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  376. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam);
  377. }
  378. // If a max width was requested
  379. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  380. {
  381. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  382. return isH264Output ?
  383. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  384. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  385. }
  386. // If a max height was requested
  387. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  388. {
  389. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  390. return isH264Output ?
  391. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  392. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  393. }
  394. if (state.VideoStream == null)
  395. {
  396. // No way to figure this out
  397. return string.Empty;
  398. }
  399. // Need to perform calculations manually
  400. // Try to account for bad media info
  401. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  402. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  403. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  404. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  405. if (isH264Output)
  406. {
  407. var widthParam = outputSize.Width.ToString(UsCulture);
  408. var heightParam = outputSize.Height.ToString(UsCulture);
  409. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  410. }
  411. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  412. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  413. }
  414. /// <summary>
  415. /// Gets the text subtitle param.
  416. /// </summary>
  417. /// <param name="state">The state.</param>
  418. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  419. /// <returns>System.String.</returns>
  420. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  421. {
  422. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  423. GetExtractedAssPath(state, performConversion);
  424. if (string.IsNullOrEmpty(path))
  425. {
  426. return string.Empty;
  427. }
  428. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  429. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  430. path.Replace('\\', '/').Replace(":/", "\\:/"),
  431. Math.Round(seconds).ToString(UsCulture));
  432. }
  433. /// <summary>
  434. /// Gets the extracted ass path.
  435. /// </summary>
  436. /// <param name="state">The state.</param>
  437. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  438. /// <returns>System.String.</returns>
  439. private string GetExtractedAssPath(StreamState state, bool performConversion)
  440. {
  441. var path = FFMpegManager.Instance.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream, ".ass");
  442. if (performConversion)
  443. {
  444. InputType type;
  445. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  446. try
  447. {
  448. var parentPath = Path.GetDirectoryName(path);
  449. Directory.CreateDirectory(parentPath);
  450. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, path, CancellationToken.None);
  451. Task.WaitAll(task);
  452. }
  453. catch
  454. {
  455. return null;
  456. }
  457. }
  458. return path;
  459. }
  460. /// <summary>
  461. /// Gets the converted ass path.
  462. /// </summary>
  463. /// <param name="mediaPath">The media path.</param>
  464. /// <param name="subtitleStream">The subtitle stream.</param>
  465. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  466. /// <returns>System.String.</returns>
  467. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  468. {
  469. var path = FFMpegManager.Instance.GetSubtitleCachePath(mediaPath, subtitleStream, ".ass");
  470. if (performConversion)
  471. {
  472. try
  473. {
  474. var parentPath = Path.GetDirectoryName(path);
  475. Directory.CreateDirectory(parentPath);
  476. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  477. Task.WaitAll(task);
  478. }
  479. catch
  480. {
  481. return null;
  482. }
  483. }
  484. return path;
  485. }
  486. /// <summary>
  487. /// Gets the internal graphical subtitle param.
  488. /// </summary>
  489. /// <param name="state">The state.</param>
  490. /// <param name="outputVideoCodec">The output video codec.</param>
  491. /// <returns>System.String.</returns>
  492. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  493. {
  494. var outputSizeParam = string.Empty;
  495. var request = state.VideoRequest;
  496. // Add resolution params, if specified
  497. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  498. {
  499. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  500. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  501. }
  502. var videoSizeParam = string.Empty;
  503. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  504. {
  505. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  506. }
  507. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  508. state.SubtitleStream.Index,
  509. state.VideoStream.Index,
  510. outputSizeParam,
  511. videoSizeParam);
  512. }
  513. /// <summary>
  514. /// Gets the probe size argument.
  515. /// </summary>
  516. /// <param name="mediaPath">The media path.</param>
  517. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  518. /// <param name="videoType">Type of the video.</param>
  519. /// <param name="isoType">Type of the iso.</param>
  520. /// <returns>System.String.</returns>
  521. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  522. {
  523. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  524. MediaEncoderHelpers.GetInputType(videoType, isoType);
  525. return MediaEncoder.GetProbeSizeArgument(type);
  526. }
  527. /// <summary>
  528. /// Gets the number of audio channels to specify on the command line
  529. /// </summary>
  530. /// <param name="request">The request.</param>
  531. /// <param name="audioStream">The audio stream.</param>
  532. /// <returns>System.Nullable{System.Int32}.</returns>
  533. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  534. {
  535. if (audioStream != null)
  536. {
  537. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  538. {
  539. if (request.AudioCodec.Value == AudioCodecs.Wma)
  540. {
  541. // wmav2 currently only supports two channel output
  542. return 2;
  543. }
  544. }
  545. }
  546. return request.AudioChannels;
  547. }
  548. /// <summary>
  549. /// Determines whether the specified stream is H264.
  550. /// </summary>
  551. /// <param name="stream">The stream.</param>
  552. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  553. protected bool IsH264(MediaStream stream)
  554. {
  555. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  556. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  557. }
  558. /// <summary>
  559. /// Gets the name of the output audio codec
  560. /// </summary>
  561. /// <param name="request">The request.</param>
  562. /// <returns>System.String.</returns>
  563. protected string GetAudioCodec(StreamRequest request)
  564. {
  565. var codec = request.AudioCodec;
  566. if (codec.HasValue)
  567. {
  568. if (codec == AudioCodecs.Aac)
  569. {
  570. return "aac -strict experimental";
  571. }
  572. if (codec == AudioCodecs.Mp3)
  573. {
  574. return "libmp3lame";
  575. }
  576. if (codec == AudioCodecs.Vorbis)
  577. {
  578. return "libvorbis";
  579. }
  580. if (codec == AudioCodecs.Wma)
  581. {
  582. return "wmav2";
  583. }
  584. return codec.ToString().ToLower();
  585. }
  586. return "copy";
  587. }
  588. /// <summary>
  589. /// Gets the name of the output video codec
  590. /// </summary>
  591. /// <param name="request">The request.</param>
  592. /// <returns>System.String.</returns>
  593. protected string GetVideoCodec(VideoStreamRequest request)
  594. {
  595. var codec = request.VideoCodec;
  596. if (codec.HasValue)
  597. {
  598. if (codec == VideoCodecs.H264)
  599. {
  600. return "libx264";
  601. }
  602. if (codec == VideoCodecs.Vpx)
  603. {
  604. return "libvpx";
  605. }
  606. if (codec == VideoCodecs.Wmv)
  607. {
  608. return "wmv2";
  609. }
  610. if (codec == VideoCodecs.Theora)
  611. {
  612. return "libtheora";
  613. }
  614. return codec.ToString().ToLower();
  615. }
  616. return "copy";
  617. }
  618. /// <summary>
  619. /// Gets the input argument.
  620. /// </summary>
  621. /// <param name="state">The state.</param>
  622. /// <returns>System.String.</returns>
  623. protected string GetInputArgument(StreamState state)
  624. {
  625. if (state.SendInputOverStandardInput)
  626. {
  627. return "-";
  628. }
  629. var type = InputType.File;
  630. var inputPath = new[] { state.MediaPath };
  631. if (state.IsInputVideo)
  632. {
  633. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  634. {
  635. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  636. }
  637. }
  638. return MediaEncoder.GetInputArgument(inputPath, type);
  639. }
  640. /// <summary>
  641. /// Starts the FFMPEG.
  642. /// </summary>
  643. /// <param name="state">The state.</param>
  644. /// <param name="outputPath">The output path.</param>
  645. /// <returns>Task.</returns>
  646. protected async Task StartFfMpeg(StreamState state, string outputPath)
  647. {
  648. if (!File.Exists(MediaEncoder.EncoderPath))
  649. {
  650. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  651. }
  652. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  653. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  654. {
  655. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  656. }
  657. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  658. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  659. {
  660. commandLineArgs = "-loglevel debug " + commandLineArgs;
  661. }
  662. var process = new Process
  663. {
  664. StartInfo = new ProcessStartInfo
  665. {
  666. CreateNoWindow = true,
  667. UseShellExecute = false,
  668. // Must consume both stdout and stderr or deadlocks may occur
  669. RedirectStandardOutput = true,
  670. RedirectStandardError = true,
  671. FileName = MediaEncoder.EncoderPath,
  672. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  673. Arguments = commandLineArgs,
  674. WindowStyle = ProcessWindowStyle.Hidden,
  675. ErrorDialog = false,
  676. RedirectStandardInput = state.SendInputOverStandardInput
  677. },
  678. EnableRaisingEvents = true
  679. };
  680. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  681. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  682. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  683. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  684. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  685. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  686. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  687. try
  688. {
  689. process.Start();
  690. }
  691. catch (Exception ex)
  692. {
  693. Logger.ErrorException("Error starting ffmpeg", ex);
  694. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  695. state.LogFileStream.Dispose();
  696. throw;
  697. }
  698. if (state.SendInputOverStandardInput)
  699. {
  700. StreamToStandardInput(process, state);
  701. }
  702. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  703. process.BeginOutputReadLine();
  704. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  705. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  706. // Wait for the file to exist before proceeeding
  707. while (!File.Exists(outputPath))
  708. {
  709. await Task.Delay(100).ConfigureAwait(false);
  710. }
  711. // Allow a small amount of time to buffer a little
  712. if (state.IsInputVideo)
  713. {
  714. await Task.Delay(500).ConfigureAwait(false);
  715. }
  716. // This is arbitrary, but add a little buffer time when internet streaming
  717. if (state.IsRemote)
  718. {
  719. await Task.Delay(3000).ConfigureAwait(false);
  720. }
  721. }
  722. private async void StreamToStandardInput(Process process, StreamState state)
  723. {
  724. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  725. try
  726. {
  727. await StreamToStandardInputInternal(process, state).ConfigureAwait(false);
  728. }
  729. catch (OperationCanceledException)
  730. {
  731. Logger.Debug("Stream to standard input closed normally.");
  732. }
  733. catch (Exception ex)
  734. {
  735. Logger.ErrorException("Error writing to standard input", ex);
  736. }
  737. }
  738. private async Task StreamToStandardInputInternal(Process process, StreamState state)
  739. {
  740. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  741. using (var fileStream = FileSystem.GetFileStream(state.MediaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  742. {
  743. await new EndlessStreamCopy().CopyStream(fileStream, process.StandardInput.BaseStream, state.StandardInputCancellationTokenSource.Token).ConfigureAwait(false);
  744. }
  745. }
  746. protected int? GetVideoBitrateParam(StreamState state)
  747. {
  748. return state.VideoRequest.VideoBitRate;
  749. }
  750. protected int? GetAudioBitrateParam(StreamState state)
  751. {
  752. if (state.Request.AudioBitRate.HasValue)
  753. {
  754. // Make sure we don't request a bitrate higher than the source
  755. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  756. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  757. }
  758. return null;
  759. }
  760. /// <summary>
  761. /// Gets the user agent param.
  762. /// </summary>
  763. /// <param name="path">The path.</param>
  764. /// <returns>System.String.</returns>
  765. private string GetUserAgentParam(string path)
  766. {
  767. var useragent = GetUserAgent(path);
  768. if (!string.IsNullOrEmpty(useragent))
  769. {
  770. return "-user-agent \"" + useragent + "\"";
  771. }
  772. return string.Empty;
  773. }
  774. /// <summary>
  775. /// Gets the user agent.
  776. /// </summary>
  777. /// <param name="path">The path.</param>
  778. /// <returns>System.String.</returns>
  779. protected string GetUserAgent(string path)
  780. {
  781. if (string.IsNullOrEmpty(path))
  782. {
  783. throw new ArgumentNullException("path");
  784. }
  785. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  786. {
  787. return "QuickTime/7.7.4";
  788. }
  789. return string.Empty;
  790. }
  791. /// <summary>
  792. /// Processes the exited.
  793. /// </summary>
  794. /// <param name="process">The process.</param>
  795. /// <param name="state">The state.</param>
  796. protected async void OnFfMpegProcessExited(Process process, StreamState state)
  797. {
  798. if (state.IsoMount != null)
  799. {
  800. state.IsoMount.Dispose();
  801. state.IsoMount = null;
  802. }
  803. if (state.StandardInputCancellationTokenSource != null)
  804. {
  805. state.StandardInputCancellationTokenSource.Cancel();
  806. }
  807. var outputFilePath = GetOutputFilePath(state);
  808. state.LogFileStream.Dispose();
  809. try
  810. {
  811. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  812. }
  813. catch
  814. {
  815. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  816. }
  817. if (!string.IsNullOrEmpty(state.LiveTvStreamId))
  818. {
  819. try
  820. {
  821. await LiveTvManager.CloseLiveStream(state.LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  822. }
  823. catch (Exception ex)
  824. {
  825. Logger.ErrorException("Error closing live tv stream", ex);
  826. }
  827. }
  828. }
  829. /// <summary>
  830. /// Gets the state.
  831. /// </summary>
  832. /// <param name="request">The request.</param>
  833. /// <param name="cancellationToken">The cancellation token.</param>
  834. /// <returns>StreamState.</returns>
  835. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  836. {
  837. if (request.ThrowDebugError)
  838. {
  839. throw new InvalidOperationException("You asked for a debug error, you got one.");
  840. }
  841. var url = Request.PathInfo;
  842. if (!request.AudioCodec.HasValue)
  843. {
  844. request.AudioCodec = InferAudioCodec(url);
  845. }
  846. var state = new StreamState
  847. {
  848. Request = request,
  849. RequestedUrl = url
  850. };
  851. var item = DtoService.GetItemByDtoId(request.Id);
  852. if (item is ILiveTvRecording)
  853. {
  854. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  855. state.VideoType = VideoType.VideoFile;
  856. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  857. state.PlayableStreamFileNames = new List<string>();
  858. if (!string.IsNullOrEmpty(recording.RecordingInfo.Path) && File.Exists(recording.RecordingInfo.Path))
  859. {
  860. state.MediaPath = recording.RecordingInfo.Path;
  861. state.IsRemote = false;
  862. }
  863. else if (!string.IsNullOrEmpty(recording.RecordingInfo.Url))
  864. {
  865. state.MediaPath = recording.RecordingInfo.Url;
  866. state.IsRemote = true;
  867. }
  868. else
  869. {
  870. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  871. state.LiveTvStreamId = streamInfo.Id;
  872. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  873. {
  874. state.MediaPath = streamInfo.Path;
  875. state.IsRemote = false;
  876. }
  877. else if (!string.IsNullOrEmpty(streamInfo.Url))
  878. {
  879. state.MediaPath = streamInfo.Url;
  880. state.IsRemote = true;
  881. }
  882. }
  883. //state.RunTimeTicks = recording.RunTimeTicks;
  884. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  885. state.AudioSync = 1000;
  886. state.DeInterlace = true;
  887. state.InputFormat = "mpegts";
  888. }
  889. else if (item is LiveTvChannel)
  890. {
  891. var channel = LiveTvManager.GetInternalChannel(request.Id);
  892. state.VideoType = VideoType.VideoFile;
  893. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  894. state.PlayableStreamFileNames = new List<string>();
  895. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  896. state.LiveTvStreamId = streamInfo.Id;
  897. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  898. {
  899. state.MediaPath = streamInfo.Path;
  900. state.IsRemote = false;
  901. }
  902. else if (!string.IsNullOrEmpty(streamInfo.Url))
  903. {
  904. state.MediaPath = streamInfo.Url;
  905. state.IsRemote = true;
  906. }
  907. state.SendInputOverStandardInput = true;
  908. state.ReadInputAtNativeFramerate = true;
  909. state.AudioSync = 1000;
  910. state.DeInterlace = true;
  911. state.InputFormat = "mpegts";
  912. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  913. }
  914. else
  915. {
  916. state.MediaPath = item.Path;
  917. state.IsRemote = item.LocationType == LocationType.Remote;
  918. var video = item as Video;
  919. if (video != null)
  920. {
  921. state.IsInputVideo = true;
  922. state.VideoType = video.VideoType;
  923. state.IsoType = video.IsoType;
  924. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  925. ? new List<string>()
  926. : video.PlayableStreamFileNames.ToList();
  927. }
  928. state.RunTimeTicks = item.RunTimeTicks;
  929. }
  930. var videoRequest = request as VideoStreamRequest;
  931. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  932. {
  933. ItemId = item.Id
  934. }).ToList();
  935. if (videoRequest != null)
  936. {
  937. if (!videoRequest.VideoCodec.HasValue)
  938. {
  939. videoRequest.VideoCodec = InferVideoCodec(url);
  940. }
  941. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  942. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  943. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  944. }
  945. else
  946. {
  947. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  948. }
  949. state.HasMediaStreams = mediaStreams.Count > 0;
  950. return state;
  951. }
  952. protected string GetInputModifier(StreamState state)
  953. {
  954. var inputModifier = string.Empty;
  955. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  956. inputModifier += " " + probeSize;
  957. inputModifier = inputModifier.Trim();
  958. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  959. inputModifier = inputModifier.Trim();
  960. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  961. inputModifier = inputModifier.Trim();
  962. if (state.VideoRequest != null)
  963. {
  964. inputModifier += " -fflags genpts";
  965. }
  966. if (!string.IsNullOrEmpty(state.InputFormat))
  967. {
  968. inputModifier += " -f " + state.InputFormat;
  969. }
  970. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  971. {
  972. inputModifier += " -vcodec " + state.InputVideoCodec;
  973. }
  974. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  975. {
  976. inputModifier += " -acodec " + state.InputAudioCodec;
  977. }
  978. if (state.ReadInputAtNativeFramerate)
  979. {
  980. inputModifier += " -re";
  981. }
  982. return inputModifier;
  983. }
  984. /// <summary>
  985. /// Infers the audio codec based on the url
  986. /// </summary>
  987. /// <param name="url">The URL.</param>
  988. /// <returns>System.Nullable{AudioCodecs}.</returns>
  989. private AudioCodecs? InferAudioCodec(string url)
  990. {
  991. var ext = Path.GetExtension(url);
  992. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  993. {
  994. return AudioCodecs.Mp3;
  995. }
  996. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  997. {
  998. return AudioCodecs.Aac;
  999. }
  1000. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1001. {
  1002. return AudioCodecs.Wma;
  1003. }
  1004. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1005. {
  1006. return AudioCodecs.Vorbis;
  1007. }
  1008. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1009. {
  1010. return AudioCodecs.Vorbis;
  1011. }
  1012. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1013. {
  1014. return AudioCodecs.Vorbis;
  1015. }
  1016. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1017. {
  1018. return AudioCodecs.Vorbis;
  1019. }
  1020. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1021. {
  1022. return AudioCodecs.Vorbis;
  1023. }
  1024. return null;
  1025. }
  1026. /// <summary>
  1027. /// Infers the video codec.
  1028. /// </summary>
  1029. /// <param name="url">The URL.</param>
  1030. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1031. private VideoCodecs? InferVideoCodec(string url)
  1032. {
  1033. var ext = Path.GetExtension(url);
  1034. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1035. {
  1036. return VideoCodecs.Wmv;
  1037. }
  1038. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1039. {
  1040. return VideoCodecs.Vpx;
  1041. }
  1042. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1043. {
  1044. return VideoCodecs.Theora;
  1045. }
  1046. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1047. {
  1048. return VideoCodecs.H264;
  1049. }
  1050. return VideoCodecs.Copy;
  1051. }
  1052. }
  1053. }