BaseStreamingService.cs 28 KB

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