BaseStreamingService.cs 33 KB

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