BaseStreamingService.cs 30 KB

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