BaseStreamingService.cs 33 KB

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