BaseStreamingService.cs 32 KB

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