BaseStreamingService.cs 32 KB

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