BaseStreamingService.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  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 -crf 18";
  268. }
  269. // asf/wmv
  270. if (videoCodec.Equals("wmv2", StringComparison.OrdinalIgnoreCase))
  271. {
  272. return "-qmin 2";
  273. }
  274. if (videoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase))
  275. {
  276. switch (GetQualitySetting())
  277. {
  278. case EncodingQuality.HighSpeed:
  279. return "-preset ultrafast -crf 18";
  280. case EncodingQuality.HighQuality:
  281. return "-preset superfast -crf 18";
  282. case EncodingQuality.MaxQuality:
  283. return "-preset superfast -crf 18";
  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);
  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. // Don't re-encode ass/ssa to ass because ffmpeg ass encoder fails if there's more than one ass rectangle. Affect Anime mostly.
  451. // See https://lists.ffmpeg.org/pipermail/ffmpeg-cvslog/2013-April/063616.html
  452. bool isAssSubtitle = string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase);
  453. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, isAssSubtitle, path, CancellationToken.None);
  454. Task.WaitAll(task);
  455. }
  456. catch
  457. {
  458. return null;
  459. }
  460. }
  461. return path;
  462. }
  463. /// <summary>
  464. /// Gets the converted ass path.
  465. /// </summary>
  466. /// <param name="mediaPath">The media path.</param>
  467. /// <param name="subtitleStream">The subtitle stream.</param>
  468. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  469. /// <returns>System.String.</returns>
  470. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  471. {
  472. var path = FFMpegManager.Instance.GetSubtitleCachePath(mediaPath, subtitleStream, ".ass");
  473. if (performConversion)
  474. {
  475. try
  476. {
  477. var parentPath = Path.GetDirectoryName(path);
  478. Directory.CreateDirectory(parentPath);
  479. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  480. Task.WaitAll(task);
  481. }
  482. catch
  483. {
  484. return null;
  485. }
  486. }
  487. return path;
  488. }
  489. /// <summary>
  490. /// Gets the internal graphical subtitle param.
  491. /// </summary>
  492. /// <param name="state">The state.</param>
  493. /// <param name="outputVideoCodec">The output video codec.</param>
  494. /// <returns>System.String.</returns>
  495. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  496. {
  497. var outputSizeParam = string.Empty;
  498. var request = state.VideoRequest;
  499. // Add resolution params, if specified
  500. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  501. {
  502. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  503. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  504. }
  505. var videoSizeParam = string.Empty;
  506. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  507. {
  508. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  509. }
  510. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  511. state.SubtitleStream.Index,
  512. state.VideoStream.Index,
  513. outputSizeParam,
  514. videoSizeParam);
  515. }
  516. /// <summary>
  517. /// Gets the probe size argument.
  518. /// </summary>
  519. /// <param name="mediaPath">The media path.</param>
  520. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  521. /// <param name="videoType">Type of the video.</param>
  522. /// <param name="isoType">Type of the iso.</param>
  523. /// <returns>System.String.</returns>
  524. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  525. {
  526. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  527. MediaEncoderHelpers.GetInputType(videoType, isoType);
  528. return MediaEncoder.GetProbeSizeArgument(type);
  529. }
  530. /// <summary>
  531. /// Gets the number of audio channels to specify on the command line
  532. /// </summary>
  533. /// <param name="request">The request.</param>
  534. /// <param name="audioStream">The audio stream.</param>
  535. /// <returns>System.Nullable{System.Int32}.</returns>
  536. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  537. {
  538. if (audioStream != null)
  539. {
  540. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  541. {
  542. if (request.AudioCodec.Value == AudioCodecs.Wma)
  543. {
  544. // wmav2 currently only supports two channel output
  545. return 2;
  546. }
  547. }
  548. }
  549. return request.AudioChannels;
  550. }
  551. /// <summary>
  552. /// Determines whether the specified stream is H264.
  553. /// </summary>
  554. /// <param name="stream">The stream.</param>
  555. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  556. protected bool IsH264(MediaStream stream)
  557. {
  558. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  559. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  560. }
  561. /// <summary>
  562. /// Gets the name of the output audio codec
  563. /// </summary>
  564. /// <param name="request">The request.</param>
  565. /// <returns>System.String.</returns>
  566. protected string GetAudioCodec(StreamRequest request)
  567. {
  568. var codec = request.AudioCodec;
  569. if (codec.HasValue)
  570. {
  571. if (codec == AudioCodecs.Aac)
  572. {
  573. return "aac -strict experimental";
  574. }
  575. if (codec == AudioCodecs.Mp3)
  576. {
  577. return "libmp3lame";
  578. }
  579. if (codec == AudioCodecs.Vorbis)
  580. {
  581. return "libvorbis";
  582. }
  583. if (codec == AudioCodecs.Wma)
  584. {
  585. return "wmav2";
  586. }
  587. return codec.ToString().ToLower();
  588. }
  589. return "copy";
  590. }
  591. /// <summary>
  592. /// Gets the name of the output video codec
  593. /// </summary>
  594. /// <param name="request">The request.</param>
  595. /// <returns>System.String.</returns>
  596. protected string GetVideoCodec(VideoStreamRequest request)
  597. {
  598. var codec = request.VideoCodec;
  599. if (codec.HasValue)
  600. {
  601. if (codec == VideoCodecs.H264)
  602. {
  603. return "libx264";
  604. }
  605. if (codec == VideoCodecs.Vpx)
  606. {
  607. return "libvpx";
  608. }
  609. if (codec == VideoCodecs.Wmv)
  610. {
  611. return "wmv2";
  612. }
  613. if (codec == VideoCodecs.Theora)
  614. {
  615. return "libtheora";
  616. }
  617. return codec.ToString().ToLower();
  618. }
  619. return "copy";
  620. }
  621. /// <summary>
  622. /// Gets the input argument.
  623. /// </summary>
  624. /// <param name="state">The state.</param>
  625. /// <returns>System.String.</returns>
  626. protected string GetInputArgument(StreamState state)
  627. {
  628. if (state.SendInputOverStandardInput)
  629. {
  630. return "-";
  631. }
  632. var type = InputType.File;
  633. var inputPath = new[] { state.MediaPath };
  634. if (state.IsInputVideo)
  635. {
  636. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  637. {
  638. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  639. }
  640. }
  641. return MediaEncoder.GetInputArgument(inputPath, type);
  642. }
  643. /// <summary>
  644. /// Starts the FFMPEG.
  645. /// </summary>
  646. /// <param name="state">The state.</param>
  647. /// <param name="outputPath">The output path.</param>
  648. /// <returns>Task.</returns>
  649. protected async Task StartFfMpeg(StreamState state, string outputPath)
  650. {
  651. if (!File.Exists(MediaEncoder.EncoderPath))
  652. {
  653. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  654. }
  655. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  656. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  657. {
  658. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  659. }
  660. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  661. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  662. {
  663. commandLineArgs = "-loglevel debug " + commandLineArgs;
  664. }
  665. var process = new Process
  666. {
  667. StartInfo = new ProcessStartInfo
  668. {
  669. CreateNoWindow = true,
  670. UseShellExecute = false,
  671. // Must consume both stdout and stderr or deadlocks may occur
  672. RedirectStandardOutput = true,
  673. RedirectStandardError = true,
  674. FileName = MediaEncoder.EncoderPath,
  675. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  676. Arguments = commandLineArgs,
  677. WindowStyle = ProcessWindowStyle.Hidden,
  678. ErrorDialog = false,
  679. RedirectStandardInput = state.SendInputOverStandardInput
  680. },
  681. EnableRaisingEvents = true
  682. };
  683. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  684. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  685. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  686. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  687. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  688. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  689. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  690. try
  691. {
  692. process.Start();
  693. }
  694. catch (Exception ex)
  695. {
  696. Logger.ErrorException("Error starting ffmpeg", ex);
  697. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  698. state.LogFileStream.Dispose();
  699. throw;
  700. }
  701. if (state.SendInputOverStandardInput)
  702. {
  703. StreamToStandardInput(process, state);
  704. }
  705. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  706. process.BeginOutputReadLine();
  707. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  708. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  709. // Wait for the file to exist before proceeeding
  710. while (!File.Exists(outputPath))
  711. {
  712. await Task.Delay(100).ConfigureAwait(false);
  713. }
  714. // Allow a small amount of time to buffer a little
  715. if (state.IsInputVideo)
  716. {
  717. await Task.Delay(500).ConfigureAwait(false);
  718. }
  719. // This is arbitrary, but add a little buffer time when internet streaming
  720. if (state.IsRemote)
  721. {
  722. await Task.Delay(3000).ConfigureAwait(false);
  723. }
  724. }
  725. private async void StreamToStandardInput(Process process, StreamState state)
  726. {
  727. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  728. try
  729. {
  730. await StreamToStandardInputInternal(process, state).ConfigureAwait(false);
  731. }
  732. catch (OperationCanceledException)
  733. {
  734. Logger.Debug("Stream to standard input closed normally.");
  735. }
  736. catch (Exception ex)
  737. {
  738. Logger.ErrorException("Error writing to standard input", ex);
  739. }
  740. }
  741. private async Task StreamToStandardInputInternal(Process process, StreamState state)
  742. {
  743. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  744. using (var fileStream = FileSystem.GetFileStream(state.MediaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  745. {
  746. await new EndlessStreamCopy().CopyStream(fileStream, process.StandardInput.BaseStream, state.StandardInputCancellationTokenSource.Token).ConfigureAwait(false);
  747. }
  748. }
  749. protected int? GetVideoBitrateParam(StreamState state)
  750. {
  751. return state.VideoRequest.VideoBitRate;
  752. }
  753. protected int? GetAudioBitrateParam(StreamState state)
  754. {
  755. if (state.Request.AudioBitRate.HasValue)
  756. {
  757. // Make sure we don't request a bitrate higher than the source
  758. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  759. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  760. }
  761. return null;
  762. }
  763. /// <summary>
  764. /// Gets the user agent param.
  765. /// </summary>
  766. /// <param name="path">The path.</param>
  767. /// <returns>System.String.</returns>
  768. private string GetUserAgentParam(string path)
  769. {
  770. var useragent = GetUserAgent(path);
  771. if (!string.IsNullOrEmpty(useragent))
  772. {
  773. return "-user-agent \"" + useragent + "\"";
  774. }
  775. return string.Empty;
  776. }
  777. /// <summary>
  778. /// Gets the user agent.
  779. /// </summary>
  780. /// <param name="path">The path.</param>
  781. /// <returns>System.String.</returns>
  782. protected string GetUserAgent(string path)
  783. {
  784. if (string.IsNullOrEmpty(path))
  785. {
  786. throw new ArgumentNullException("path");
  787. }
  788. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  789. {
  790. return "QuickTime/7.7.4";
  791. }
  792. return string.Empty;
  793. }
  794. /// <summary>
  795. /// Processes the exited.
  796. /// </summary>
  797. /// <param name="process">The process.</param>
  798. /// <param name="state">The state.</param>
  799. protected async void OnFfMpegProcessExited(Process process, StreamState state)
  800. {
  801. if (state.IsoMount != null)
  802. {
  803. state.IsoMount.Dispose();
  804. state.IsoMount = null;
  805. }
  806. if (state.StandardInputCancellationTokenSource != null)
  807. {
  808. state.StandardInputCancellationTokenSource.Cancel();
  809. }
  810. var outputFilePath = GetOutputFilePath(state);
  811. state.LogFileStream.Dispose();
  812. try
  813. {
  814. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  815. }
  816. catch
  817. {
  818. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  819. }
  820. if (!string.IsNullOrEmpty(state.LiveTvStreamId))
  821. {
  822. try
  823. {
  824. await LiveTvManager.CloseLiveStream(state.LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  825. }
  826. catch (Exception ex)
  827. {
  828. Logger.ErrorException("Error closing live tv stream", ex);
  829. }
  830. }
  831. }
  832. protected double? GetFramerateParam(StreamState state)
  833. {
  834. if (state.VideoRequest != null && state.VideoRequest.Framerate.HasValue)
  835. {
  836. return state.VideoRequest.Framerate.Value;
  837. }
  838. if (state.VideoStream != null)
  839. {
  840. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  841. if (contentRate.HasValue && contentRate.Value > 23.976)
  842. {
  843. return 23.976;
  844. }
  845. }
  846. return null;
  847. }
  848. /// <summary>
  849. /// Gets the state.
  850. /// </summary>
  851. /// <param name="request">The request.</param>
  852. /// <param name="cancellationToken">The cancellation token.</param>
  853. /// <returns>StreamState.</returns>
  854. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  855. {
  856. if (request.ThrowDebugError)
  857. {
  858. throw new InvalidOperationException("You asked for a debug error, you got one.");
  859. }
  860. var user = AuthorizationRequestFilterAttribute.GetCurrentUser(Request, UserManager);
  861. if (user != null && !user.Configuration.EnableMediaPlayback)
  862. {
  863. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  864. }
  865. var url = Request.PathInfo;
  866. if (!request.AudioCodec.HasValue)
  867. {
  868. request.AudioCodec = InferAudioCodec(url);
  869. }
  870. var state = new StreamState
  871. {
  872. Request = request,
  873. RequestedUrl = url
  874. };
  875. var item = DtoService.GetItemByDtoId(request.Id);
  876. if (item is ILiveTvRecording)
  877. {
  878. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  879. state.VideoType = VideoType.VideoFile;
  880. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  881. state.PlayableStreamFileNames = new List<string>();
  882. if (!string.IsNullOrEmpty(recording.RecordingInfo.Path) && File.Exists(recording.RecordingInfo.Path))
  883. {
  884. state.MediaPath = recording.RecordingInfo.Path;
  885. state.IsRemote = false;
  886. }
  887. else if (!string.IsNullOrEmpty(recording.RecordingInfo.Url))
  888. {
  889. state.MediaPath = recording.RecordingInfo.Url;
  890. state.IsRemote = true;
  891. }
  892. else
  893. {
  894. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  895. state.LiveTvStreamId = streamInfo.Id;
  896. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  897. {
  898. state.MediaPath = streamInfo.Path;
  899. state.IsRemote = false;
  900. }
  901. else if (!string.IsNullOrEmpty(streamInfo.Url))
  902. {
  903. state.MediaPath = streamInfo.Url;
  904. state.IsRemote = true;
  905. }
  906. }
  907. //state.RunTimeTicks = recording.RunTimeTicks;
  908. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  909. state.SendInputOverStandardInput = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  910. state.AudioSync = "1000";
  911. state.DeInterlace = true;
  912. }
  913. else if (item is LiveTvChannel)
  914. {
  915. var channel = LiveTvManager.GetInternalChannel(request.Id);
  916. state.VideoType = VideoType.VideoFile;
  917. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  918. state.PlayableStreamFileNames = new List<string>();
  919. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  920. state.LiveTvStreamId = streamInfo.Id;
  921. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  922. {
  923. state.MediaPath = streamInfo.Path;
  924. state.IsRemote = false;
  925. }
  926. else if (!string.IsNullOrEmpty(streamInfo.Url))
  927. {
  928. state.MediaPath = streamInfo.Url;
  929. state.IsRemote = true;
  930. }
  931. state.SendInputOverStandardInput = true;
  932. state.ReadInputAtNativeFramerate = true;
  933. state.AudioSync = "1000";
  934. state.DeInterlace = true;
  935. }
  936. else
  937. {
  938. state.MediaPath = item.Path;
  939. state.IsRemote = item.LocationType == LocationType.Remote;
  940. var video = item as Video;
  941. if (video != null)
  942. {
  943. state.IsInputVideo = true;
  944. state.VideoType = video.VideoType;
  945. state.IsoType = video.IsoType;
  946. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  947. ? new List<string>()
  948. : video.PlayableStreamFileNames.ToList();
  949. }
  950. state.RunTimeTicks = item.RunTimeTicks;
  951. }
  952. var videoRequest = request as VideoStreamRequest;
  953. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  954. {
  955. ItemId = item.Id
  956. }).ToList();
  957. if (videoRequest != null)
  958. {
  959. if (!videoRequest.VideoCodec.HasValue)
  960. {
  961. videoRequest.VideoCodec = InferVideoCodec(url);
  962. }
  963. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  964. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  965. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  966. }
  967. else
  968. {
  969. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  970. }
  971. state.HasMediaStreams = mediaStreams.Count > 0;
  972. return state;
  973. }
  974. protected string GetInputModifier(StreamState state)
  975. {
  976. var inputModifier = string.Empty;
  977. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  978. inputModifier += " " + probeSize;
  979. inputModifier = inputModifier.Trim();
  980. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  981. inputModifier = inputModifier.Trim();
  982. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  983. inputModifier = inputModifier.Trim();
  984. if (state.VideoRequest != null)
  985. {
  986. inputModifier += " -fflags genpts";
  987. }
  988. if (!string.IsNullOrEmpty(state.InputFormat))
  989. {
  990. inputModifier += " -f " + state.InputFormat;
  991. }
  992. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  993. {
  994. inputModifier += " -vcodec " + state.InputVideoCodec;
  995. }
  996. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  997. {
  998. inputModifier += " -acodec " + state.InputAudioCodec;
  999. }
  1000. if (state.ReadInputAtNativeFramerate)
  1001. {
  1002. inputModifier += " -re";
  1003. }
  1004. return inputModifier;
  1005. }
  1006. /// <summary>
  1007. /// Infers the audio codec based on the url
  1008. /// </summary>
  1009. /// <param name="url">The URL.</param>
  1010. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1011. private AudioCodecs? InferAudioCodec(string url)
  1012. {
  1013. var ext = Path.GetExtension(url);
  1014. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1015. {
  1016. return AudioCodecs.Mp3;
  1017. }
  1018. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1019. {
  1020. return AudioCodecs.Aac;
  1021. }
  1022. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1023. {
  1024. return AudioCodecs.Wma;
  1025. }
  1026. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1027. {
  1028. return AudioCodecs.Vorbis;
  1029. }
  1030. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1031. {
  1032. return AudioCodecs.Vorbis;
  1033. }
  1034. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1035. {
  1036. return AudioCodecs.Vorbis;
  1037. }
  1038. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1039. {
  1040. return AudioCodecs.Vorbis;
  1041. }
  1042. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1043. {
  1044. return AudioCodecs.Vorbis;
  1045. }
  1046. return null;
  1047. }
  1048. /// <summary>
  1049. /// Infers the video codec.
  1050. /// </summary>
  1051. /// <param name="url">The URL.</param>
  1052. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1053. private VideoCodecs? InferVideoCodec(string url)
  1054. {
  1055. var ext = Path.GetExtension(url);
  1056. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1057. {
  1058. return VideoCodecs.Wmv;
  1059. }
  1060. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1061. {
  1062. return VideoCodecs.Vpx;
  1063. }
  1064. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1065. {
  1066. return VideoCodecs.Theora;
  1067. }
  1068. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1069. {
  1070. return VideoCodecs.H264;
  1071. }
  1072. return VideoCodecs.Copy;
  1073. }
  1074. }
  1075. }