BaseStreamingService.cs 30 KB

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