BaseStreamingService.cs 25 KB

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