BaseStreamingService.cs 28 KB

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