BaseStreamingService.cs 30 KB

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