BaseStreamingService.cs 32 KB

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