BaseStreamingService.cs 30 KB

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