BaseStreamingService.cs 33 KB

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