BaseStreamingService.cs 26 KB

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