BaseStreamingService.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Model.Drawing;
  7. using MediaBrowser.Model.Dto;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Server.Implementations.HttpServer;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.ComponentModel;
  13. using System.Diagnostics;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Api.Playback
  19. {
  20. /// <summary>
  21. /// Class BaseStreamingService
  22. /// </summary>
  23. public abstract class BaseStreamingService : BaseApiService
  24. {
  25. /// <summary>
  26. /// Gets or sets the application paths.
  27. /// </summary>
  28. /// <value>The application paths.</value>
  29. protected IServerApplicationPaths ApplicationPaths { get; set; }
  30. /// <summary>
  31. /// Gets or sets the user manager.
  32. /// </summary>
  33. /// <value>The user manager.</value>
  34. protected IUserManager UserManager { get; set; }
  35. /// <summary>
  36. /// Gets or sets the library manager.
  37. /// </summary>
  38. /// <value>The library manager.</value>
  39. protected ILibraryManager LibraryManager { get; set; }
  40. /// <summary>
  41. /// Gets or sets the iso manager.
  42. /// </summary>
  43. /// <value>The iso manager.</value>
  44. protected IIsoManager IsoManager { get; set; }
  45. /// <summary>
  46. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  47. /// </summary>
  48. /// <param name="appPaths">The app paths.</param>
  49. /// <param name="userManager">The user manager.</param>
  50. /// <param name="libraryManager">The library manager.</param>
  51. /// <param name="isoManager">The iso manager.</param>
  52. protected BaseStreamingService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager)
  53. {
  54. ApplicationPaths = appPaths;
  55. UserManager = userManager;
  56. LibraryManager = libraryManager;
  57. IsoManager = isoManager;
  58. }
  59. /// <summary>
  60. /// Gets the command line arguments.
  61. /// </summary>
  62. /// <param name="outputPath">The output path.</param>
  63. /// <param name="state">The state.</param>
  64. /// <returns>System.String.</returns>
  65. protected abstract string GetCommandLineArguments(string outputPath, StreamState state);
  66. /// <summary>
  67. /// Gets the type of the transcoding job.
  68. /// </summary>
  69. /// <value>The type of the transcoding job.</value>
  70. protected abstract TranscodingJobType TranscodingJobType { get; }
  71. /// <summary>
  72. /// Gets the output file extension.
  73. /// </summary>
  74. /// <param name="state">The state.</param>
  75. /// <returns>System.String.</returns>
  76. protected virtual string GetOutputFileExtension(StreamState state)
  77. {
  78. return Path.GetExtension(state.Url);
  79. }
  80. /// <summary>
  81. /// Gets the output file path.
  82. /// </summary>
  83. /// <param name="state">The state.</param>
  84. /// <returns>System.String.</returns>
  85. protected string GetOutputFilePath(StreamState state)
  86. {
  87. var folder = ApplicationPaths.EncodedMediaCachePath;
  88. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state).GetMD5() + GetOutputFileExtension(state).ToLower());
  89. }
  90. /// <summary>
  91. /// The fast seek offset seconds
  92. /// </summary>
  93. private const int FastSeekOffsetSeconds = 1;
  94. /// <summary>
  95. /// Gets the fast seek command line parameter.
  96. /// </summary>
  97. /// <param name="request">The request.</param>
  98. /// <returns>System.String.</returns>
  99. /// <value>The fast seek command line parameter.</value>
  100. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  101. {
  102. var time = request.StartTimeTicks;
  103. if (time.HasValue)
  104. {
  105. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds;
  106. if (seconds > 0)
  107. {
  108. return string.Format("-ss {0}", seconds);
  109. }
  110. }
  111. return string.Empty;
  112. }
  113. /// <summary>
  114. /// Gets the slow seek command line parameter.
  115. /// </summary>
  116. /// <param name="request">The request.</param>
  117. /// <returns>System.String.</returns>
  118. /// <value>The slow seek command line parameter.</value>
  119. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  120. {
  121. var time = request.StartTimeTicks;
  122. if (time.HasValue)
  123. {
  124. if (TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds > 0)
  125. {
  126. return string.Format(" -ss {0}", FastSeekOffsetSeconds);
  127. }
  128. }
  129. return string.Empty;
  130. }
  131. /// <summary>
  132. /// Gets the map args.
  133. /// </summary>
  134. /// <param name="state">The state.</param>
  135. /// <returns>System.String.</returns>
  136. protected virtual string GetMapArgs(StreamState state)
  137. {
  138. var args = string.Empty;
  139. if (state.VideoStream != null)
  140. {
  141. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  142. }
  143. else
  144. {
  145. args += "-map -0:v";
  146. }
  147. if (state.AudioStream != null)
  148. {
  149. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  150. }
  151. else
  152. {
  153. args += " -map -0:a";
  154. }
  155. if (state.SubtitleStream == null)
  156. {
  157. args += " -map -0:s";
  158. }
  159. return args;
  160. }
  161. /// <summary>
  162. /// Determines which stream will be used for playback
  163. /// </summary>
  164. /// <param name="allStream">All stream.</param>
  165. /// <param name="desiredIndex">Index of the desired.</param>
  166. /// <param name="type">The type.</param>
  167. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  168. /// <returns>MediaStream.</returns>
  169. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  170. {
  171. var streams = allStream.Where(s => s.Type == type).ToList();
  172. if (desiredIndex.HasValue)
  173. {
  174. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  175. if (stream != null)
  176. {
  177. return stream;
  178. }
  179. }
  180. // Just return the first one
  181. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  182. }
  183. /// <summary>
  184. /// If we're going to put a fixed size on the command line, this will calculate it
  185. /// </summary>
  186. /// <param name="state">The state.</param>
  187. /// <param name="outputVideoCodec">The output video codec.</param>
  188. /// <returns>System.String.</returns>
  189. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec)
  190. {
  191. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  192. var assSubtitleParam = string.Empty;
  193. var request = state.VideoRequest;
  194. if (state.SubtitleStream != null)
  195. {
  196. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 || state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1)
  197. {
  198. assSubtitleParam = GetTextSubtitleParam((Video)state.Item, state.SubtitleStream, request.StartTimeTicks);
  199. }
  200. }
  201. // If fixed dimensions were supplied
  202. if (request.Width.HasValue && request.Height.HasValue)
  203. {
  204. return string.Format(" -vf \"scale={0}:{1}{2}\"", request.Width.Value, request.Height.Value, assSubtitleParam);
  205. }
  206. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  207. // If a fixed width was requested
  208. if (request.Width.HasValue)
  209. {
  210. return isH264Output ?
  211. string.Format(" -vf \"scale={0}:trunc(ow/a/2)*2{1}\"", request.Width.Value, assSubtitleParam) :
  212. string.Format(" -vf \"scale={0}:-1{1}\"", request.Width.Value, assSubtitleParam);
  213. }
  214. // If a max width was requested
  215. if (request.MaxWidth.HasValue && !request.MaxHeight.HasValue)
  216. {
  217. return isH264Output ?
  218. string.Format(" -vf \"scale=min(iw\\,{0}):trunc(ow/a/2)*2{1}\"", request.MaxWidth.Value, assSubtitleParam) :
  219. string.Format(" -vf \"scale=min(iw\\,{0}):-1{1}\"", request.MaxWidth.Value, assSubtitleParam);
  220. }
  221. // Need to perform calculations manually
  222. // Try to account for bad media info
  223. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  224. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  225. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  226. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  227. if (isH264Output)
  228. {
  229. return string.Format(" -vf \"scale=trunc({0}/2)*2:trunc({1}/2)*2{2}\"", outputSize.Width, outputSize.Height, assSubtitleParam);
  230. }
  231. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  232. return string.Format(" -vf \"scale={0}:-1{1}\"", Convert.ToInt32(outputSize.Width), assSubtitleParam);
  233. }
  234. /// <summary>
  235. /// Gets the text subtitle param.
  236. /// </summary>
  237. /// <param name="video">The video.</param>
  238. /// <param name="subtitleStream">The subtitle stream.</param>
  239. /// <param name="startTimeTicks">The start time ticks.</param>
  240. /// <returns>System.String.</returns>
  241. protected string GetTextSubtitleParam(Video video, MediaStream subtitleStream, long? startTimeTicks)
  242. {
  243. var path = subtitleStream.IsExternal ? GetConvertedAssPath(video, subtitleStream) : GetExtractedAssPath(video, subtitleStream);
  244. if (string.IsNullOrEmpty(path))
  245. {
  246. return string.Empty;
  247. }
  248. var param = string.Format(",ass={0}", path);
  249. if (startTimeTicks.HasValue)
  250. {
  251. var seconds = Convert.ToInt32(TimeSpan.FromTicks(startTimeTicks.Value).TotalSeconds);
  252. param += string.Format(",setpts=PTS-{0}/TB", seconds);
  253. }
  254. return param;
  255. }
  256. /// <summary>
  257. /// Gets the extracted ass path.
  258. /// </summary>
  259. /// <param name="video">The video.</param>
  260. /// <param name="subtitleStream">The subtitle stream.</param>
  261. /// <returns>System.String.</returns>
  262. private string GetExtractedAssPath(Video video, MediaStream subtitleStream)
  263. {
  264. var path = Kernel.Instance.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");
  265. if (!File.Exists(path))
  266. {
  267. var success = Kernel.Instance.FFMpegManager.ExtractTextSubtitle(video, subtitleStream.Index, path, CancellationToken.None).Result;
  268. if (!success)
  269. {
  270. return null;
  271. }
  272. }
  273. return path;
  274. }
  275. /// <summary>
  276. /// Gets the converted ass path.
  277. /// </summary>
  278. /// <param name="video">The video.</param>
  279. /// <param name="subtitleStream">The subtitle stream.</param>
  280. /// <returns>System.String.</returns>
  281. private string GetConvertedAssPath(Video video, MediaStream subtitleStream)
  282. {
  283. var path = Kernel.Instance.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");
  284. if (!File.Exists(path))
  285. {
  286. var success = Kernel.Instance.FFMpegManager.ConvertTextSubtitle(subtitleStream, path, CancellationToken.None).Result;
  287. if (!success)
  288. {
  289. return null;
  290. }
  291. }
  292. return path;
  293. }
  294. /// <summary>
  295. /// Gets the internal graphical subtitle param.
  296. /// </summary>
  297. /// <param name="state">The state.</param>
  298. /// <param name="outputVideoCodec">The output video codec.</param>
  299. /// <returns>System.String.</returns>
  300. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  301. {
  302. var outputSizeParam = string.Empty;
  303. var request = state.VideoRequest;
  304. // Add resolution params, if specified
  305. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  306. {
  307. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec).TrimEnd('"');
  308. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  309. }
  310. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p,lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:0] [sub] overlay{1}\"", state.SubtitleStream.Index, outputSizeParam);
  311. }
  312. /// <summary>
  313. /// Gets the number of audio channels to specify on the command line
  314. /// </summary>
  315. /// <param name="request">The request.</param>
  316. /// <param name="audioStream">The audio stream.</param>
  317. /// <returns>System.Nullable{System.Int32}.</returns>
  318. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  319. {
  320. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  321. {
  322. if (request.AudioCodec.Value == AudioCodecs.Aac)
  323. {
  324. // libvo_aacenc currently only supports two channel output
  325. return 2;
  326. }
  327. if (request.AudioCodec.Value == AudioCodecs.Wma)
  328. {
  329. // wmav2 currently only supports two channel output
  330. return 2;
  331. }
  332. }
  333. return request.AudioChannels;
  334. }
  335. /// <summary>
  336. /// Determines whether the specified stream is H264.
  337. /// </summary>
  338. /// <param name="stream">The stream.</param>
  339. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  340. protected bool IsH264(MediaStream stream)
  341. {
  342. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  343. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  344. }
  345. /// <summary>
  346. /// Gets the name of the output audio codec
  347. /// </summary>
  348. /// <param name="request">The request.</param>
  349. /// <returns>System.String.</returns>
  350. protected string GetAudioCodec(StreamRequest request)
  351. {
  352. var codec = request.AudioCodec;
  353. if (codec.HasValue)
  354. {
  355. if (codec == AudioCodecs.Aac)
  356. {
  357. return "libvo_aacenc";
  358. }
  359. if (codec == AudioCodecs.Mp3)
  360. {
  361. return "libmp3lame";
  362. }
  363. if (codec == AudioCodecs.Vorbis)
  364. {
  365. return "libvorbis";
  366. }
  367. if (codec == AudioCodecs.Wma)
  368. {
  369. return "wmav2";
  370. }
  371. }
  372. return "copy";
  373. }
  374. /// <summary>
  375. /// Gets the name of the output video codec
  376. /// </summary>
  377. /// <param name="request">The request.</param>
  378. /// <returns>System.String.</returns>
  379. protected string GetVideoCodec(VideoStreamRequest request)
  380. {
  381. var codec = request.VideoCodec;
  382. if (codec.HasValue)
  383. {
  384. if (codec == VideoCodecs.H264)
  385. {
  386. return "libx264";
  387. }
  388. if (codec == VideoCodecs.Vpx)
  389. {
  390. return "libvpx";
  391. }
  392. if (codec == VideoCodecs.Wmv)
  393. {
  394. return "wmv2";
  395. }
  396. if (codec == VideoCodecs.Theora)
  397. {
  398. return "libtheora";
  399. }
  400. }
  401. return "copy";
  402. }
  403. /// <summary>
  404. /// Gets the input argument.
  405. /// </summary>
  406. /// <param name="item">The item.</param>
  407. /// <param name="isoMount">The iso mount.</param>
  408. /// <returns>System.String.</returns>
  409. protected string GetInputArgument(BaseItem item, IIsoMount isoMount)
  410. {
  411. return isoMount == null ?
  412. Kernel.Instance.FFMpegManager.GetInputArgument(item) :
  413. Kernel.Instance.FFMpegManager.GetInputArgument(item as Video, isoMount);
  414. }
  415. /// <summary>
  416. /// Starts the FFMPEG.
  417. /// </summary>
  418. /// <param name="state">The state.</param>
  419. /// <param name="outputPath">The output path.</param>
  420. /// <returns>Task.</returns>
  421. protected async Task StartFFMpeg(StreamState state, string outputPath)
  422. {
  423. var video = state.Item as Video;
  424. if (video != null && video.VideoType == VideoType.Iso && video.IsoType.HasValue && IsoManager.CanMount(video.Path))
  425. {
  426. state.IsoMount = await IsoManager.Mount(video.Path, CancellationToken.None).ConfigureAwait(false);
  427. }
  428. var process = new Process
  429. {
  430. StartInfo = new ProcessStartInfo
  431. {
  432. CreateNoWindow = true,
  433. UseShellExecute = false,
  434. // Must consume both stdout and stderr or deadlocks may occur
  435. RedirectStandardOutput = true,
  436. RedirectStandardError = true,
  437. FileName = Kernel.Instance.FFMpegManager.FFMpegPath,
  438. WorkingDirectory = Path.GetDirectoryName(Kernel.Instance.FFMpegManager.FFMpegPath),
  439. Arguments = GetCommandLineArguments(outputPath, state),
  440. WindowStyle = ProcessWindowStyle.Hidden,
  441. ErrorDialog = false
  442. },
  443. EnableRaisingEvents = true
  444. };
  445. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process);
  446. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  447. var logFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  448. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  449. state.LogFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  450. process.Exited += (sender, args) => OnFFMpegProcessExited(process, state);
  451. try
  452. {
  453. process.Start();
  454. }
  455. catch (Win32Exception ex)
  456. {
  457. Logger.ErrorException("Error starting ffmpeg", ex);
  458. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  459. state.LogFileStream.Dispose();
  460. throw;
  461. }
  462. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  463. process.BeginOutputReadLine();
  464. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  465. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  466. // Wait for the file to exist before proceeeding
  467. while (!File.Exists(outputPath))
  468. {
  469. await Task.Delay(100).ConfigureAwait(false);
  470. }
  471. }
  472. /// <summary>
  473. /// Processes the exited.
  474. /// </summary>
  475. /// <param name="process">The process.</param>
  476. /// <param name="state">The state.</param>
  477. protected void OnFFMpegProcessExited(Process process, StreamState state)
  478. {
  479. if (state.IsoMount != null)
  480. {
  481. state.IsoMount.Dispose();
  482. state.IsoMount = null;
  483. }
  484. var outputFilePath = GetOutputFilePath(state);
  485. state.LogFileStream.Dispose();
  486. int? exitCode = null;
  487. try
  488. {
  489. exitCode = process.ExitCode;
  490. Logger.Info("FFMpeg exited with code {0} for {1}", exitCode.Value, outputFilePath);
  491. }
  492. catch
  493. {
  494. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  495. }
  496. process.Dispose();
  497. ApiEntryPoint.Instance.OnTranscodingFinished(outputFilePath, TranscodingJobType);
  498. if (!exitCode.HasValue || exitCode.Value != 0)
  499. {
  500. Logger.Info("Deleting partial stream file(s) {0}", outputFilePath);
  501. try
  502. {
  503. DeletePartialStreamFiles(outputFilePath);
  504. }
  505. catch (IOException ex)
  506. {
  507. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, outputFilePath);
  508. }
  509. }
  510. else
  511. {
  512. Logger.Info("FFMpeg completed and exited normally for {0}", outputFilePath);
  513. }
  514. }
  515. /// <summary>
  516. /// Deletes the partial stream files.
  517. /// </summary>
  518. /// <param name="outputFilePath">The output file path.</param>
  519. protected abstract void DeletePartialStreamFiles(string outputFilePath);
  520. /// <summary>
  521. /// Gets the state.
  522. /// </summary>
  523. /// <param name="request">The request.</param>
  524. /// <returns>StreamState.</returns>
  525. protected StreamState GetState(StreamRequest request)
  526. {
  527. var item = DtoBuilder.GetItemByClientId(request.Id, UserManager, LibraryManager);
  528. var media = (IHasMediaStreams)item;
  529. var url = Request.PathInfo;
  530. if (!request.AudioCodec.HasValue)
  531. {
  532. request.AudioCodec = InferAudioCodec(url);
  533. }
  534. var state = new StreamState
  535. {
  536. Item = item,
  537. Request = request,
  538. Url = url
  539. };
  540. var videoRequest = request as VideoStreamRequest;
  541. if (videoRequest != null)
  542. {
  543. if (!videoRequest.VideoCodec.HasValue)
  544. {
  545. videoRequest.VideoCodec = InferVideoCodec(url);
  546. }
  547. state.VideoStream = GetMediaStream(media.MediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video, true);
  548. state.SubtitleStream = GetMediaStream(media.MediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  549. }
  550. state.AudioStream = GetMediaStream(media.MediaStreams, null, MediaStreamType.Audio, true);
  551. return state;
  552. }
  553. /// <summary>
  554. /// Infers the audio codec based on the url
  555. /// </summary>
  556. /// <param name="url">The URL.</param>
  557. /// <returns>System.Nullable{AudioCodecs}.</returns>
  558. private AudioCodecs? InferAudioCodec(string url)
  559. {
  560. var ext = Path.GetExtension(url);
  561. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  562. {
  563. return AudioCodecs.Mp3;
  564. }
  565. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  566. {
  567. return AudioCodecs.Aac;
  568. }
  569. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  570. {
  571. return AudioCodecs.Wma;
  572. }
  573. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  574. {
  575. return AudioCodecs.Vorbis;
  576. }
  577. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  578. {
  579. return AudioCodecs.Vorbis;
  580. }
  581. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  582. {
  583. return AudioCodecs.Vorbis;
  584. }
  585. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  586. {
  587. return AudioCodecs.Vorbis;
  588. }
  589. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  590. {
  591. return AudioCodecs.Vorbis;
  592. }
  593. return null;
  594. }
  595. /// <summary>
  596. /// Infers the video codec.
  597. /// </summary>
  598. /// <param name="url">The URL.</param>
  599. /// <returns>System.Nullable{VideoCodecs}.</returns>
  600. private VideoCodecs? InferVideoCodec(string url)
  601. {
  602. var ext = Path.GetExtension(url);
  603. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  604. {
  605. return VideoCodecs.Wmv;
  606. }
  607. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  608. {
  609. return VideoCodecs.Vpx;
  610. }
  611. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  612. {
  613. return VideoCodecs.Theora;
  614. }
  615. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  616. {
  617. return VideoCodecs.H264;
  618. }
  619. return null;
  620. }
  621. }
  622. }