BaseStreamingService.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.MediaInfo;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Dto;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Controller.MediaInfo;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.Drawing;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.LiveTv;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Diagnostics;
  20. using System.Globalization;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. namespace MediaBrowser.Api.Playback
  26. {
  27. /// <summary>
  28. /// Class BaseStreamingService
  29. /// </summary>
  30. public abstract class BaseStreamingService : BaseApiService
  31. {
  32. /// <summary>
  33. /// Gets or sets the application paths.
  34. /// </summary>
  35. /// <value>The application paths.</value>
  36. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  37. /// <summary>
  38. /// Gets or sets the user manager.
  39. /// </summary>
  40. /// <value>The user manager.</value>
  41. protected IUserManager UserManager { get; private set; }
  42. /// <summary>
  43. /// Gets or sets the library manager.
  44. /// </summary>
  45. /// <value>The library manager.</value>
  46. protected ILibraryManager LibraryManager { get; private set; }
  47. /// <summary>
  48. /// Gets or sets the iso manager.
  49. /// </summary>
  50. /// <value>The iso manager.</value>
  51. protected IIsoManager IsoManager { get; private set; }
  52. /// <summary>
  53. /// Gets or sets the media encoder.
  54. /// </summary>
  55. /// <value>The media encoder.</value>
  56. protected IMediaEncoder MediaEncoder { get; private set; }
  57. protected IDtoService DtoService { get; private set; }
  58. protected IFileSystem FileSystem { get; private set; }
  59. protected IItemRepository ItemRepository { get; private set; }
  60. protected ILiveTvManager LiveTvManager { get; private set; }
  61. /// <summary>
  62. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  63. /// </summary>
  64. /// <param name="serverConfig">The server configuration.</param>
  65. /// <param name="userManager">The user manager.</param>
  66. /// <param name="libraryManager">The library manager.</param>
  67. /// <param name="isoManager">The iso manager.</param>
  68. /// <param name="mediaEncoder">The media encoder.</param>
  69. /// <param name="dtoService">The dto service.</param>
  70. /// <param name="fileSystem">The file system.</param>
  71. /// <param name="itemRepository">The item repository.</param>
  72. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager)
  73. {
  74. LiveTvManager = liveTvManager;
  75. ItemRepository = itemRepository;
  76. FileSystem = fileSystem;
  77. DtoService = dtoService;
  78. ServerConfigurationManager = serverConfig;
  79. UserManager = userManager;
  80. LibraryManager = libraryManager;
  81. IsoManager = isoManager;
  82. MediaEncoder = mediaEncoder;
  83. }
  84. /// <summary>
  85. /// Gets the command line arguments.
  86. /// </summary>
  87. /// <param name="outputPath">The output path.</param>
  88. /// <param name="state">The state.</param>
  89. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  90. /// <returns>System.String.</returns>
  91. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions);
  92. /// <summary>
  93. /// Gets the type of the transcoding job.
  94. /// </summary>
  95. /// <value>The type of the transcoding job.</value>
  96. protected abstract TranscodingJobType TranscodingJobType { get; }
  97. /// <summary>
  98. /// Gets the output file extension.
  99. /// </summary>
  100. /// <param name="state">The state.</param>
  101. /// <returns>System.String.</returns>
  102. protected virtual string GetOutputFileExtension(StreamState state)
  103. {
  104. return Path.GetExtension(state.RequestedUrl);
  105. }
  106. /// <summary>
  107. /// Gets the output file path.
  108. /// </summary>
  109. /// <param name="state">The state.</param>
  110. /// <returns>System.String.</returns>
  111. protected virtual string GetOutputFilePath(StreamState state)
  112. {
  113. var folder = ServerConfigurationManager.ApplicationPaths.EncodedMediaCachePath;
  114. var outputFileExtension = GetOutputFileExtension(state);
  115. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  116. }
  117. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  118. /// <summary>
  119. /// The fast seek offset seconds
  120. /// </summary>
  121. private const int FastSeekOffsetSeconds = 1;
  122. /// <summary>
  123. /// Gets the fast seek command line parameter.
  124. /// </summary>
  125. /// <param name="request">The request.</param>
  126. /// <returns>System.String.</returns>
  127. /// <value>The fast seek command line parameter.</value>
  128. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  129. {
  130. var time = request.StartTimeTicks;
  131. if (time.HasValue)
  132. {
  133. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds;
  134. if (seconds > 0)
  135. {
  136. return string.Format("-ss {0}", seconds.ToString(UsCulture));
  137. }
  138. }
  139. return string.Empty;
  140. }
  141. /// <summary>
  142. /// Gets the slow seek command line parameter.
  143. /// </summary>
  144. /// <param name="request">The request.</param>
  145. /// <returns>System.String.</returns>
  146. /// <value>The slow seek command line parameter.</value>
  147. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  148. {
  149. var time = request.StartTimeTicks;
  150. if (time.HasValue)
  151. {
  152. if (TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds > 0)
  153. {
  154. return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture));
  155. }
  156. }
  157. return string.Empty;
  158. }
  159. /// <summary>
  160. /// Gets the map args.
  161. /// </summary>
  162. /// <param name="state">The state.</param>
  163. /// <returns>System.String.</returns>
  164. protected virtual string GetMapArgs(StreamState state)
  165. {
  166. var args = string.Empty;
  167. if (state.IsRemote || !state.HasMediaStreams)
  168. {
  169. return string.Empty;
  170. }
  171. if (state.VideoStream != null)
  172. {
  173. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  174. }
  175. else
  176. {
  177. args += "-map -0:v";
  178. }
  179. if (state.AudioStream != null)
  180. {
  181. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  182. }
  183. else
  184. {
  185. args += " -map -0:a";
  186. }
  187. if (state.SubtitleStream == null)
  188. {
  189. args += " -map -0:s";
  190. }
  191. return args;
  192. }
  193. /// <summary>
  194. /// Determines which stream will be used for playback
  195. /// </summary>
  196. /// <param name="allStream">All stream.</param>
  197. /// <param name="desiredIndex">Index of the desired.</param>
  198. /// <param name="type">The type.</param>
  199. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  200. /// <returns>MediaStream.</returns>
  201. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  202. {
  203. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  204. if (desiredIndex.HasValue)
  205. {
  206. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  207. if (stream != null)
  208. {
  209. return stream;
  210. }
  211. }
  212. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  213. {
  214. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  215. streams.FirstOrDefault();
  216. }
  217. // Just return the first one
  218. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  219. }
  220. /// <summary>
  221. /// Gets the number of threads.
  222. /// </summary>
  223. /// <returns>System.Int32.</returns>
  224. /// <exception cref="System.Exception">Unrecognized EncodingQuality value.</exception>
  225. protected int GetNumberOfThreads()
  226. {
  227. var quality = ServerConfigurationManager.Configuration.EncodingQuality;
  228. switch (quality)
  229. {
  230. case EncodingQuality.Auto:
  231. return 0;
  232. case EncodingQuality.HighSpeed:
  233. return 2;
  234. case EncodingQuality.HighQuality:
  235. return 2;
  236. case EncodingQuality.MaxQuality:
  237. return 0;
  238. default:
  239. throw new Exception("Unrecognized EncodingQuality value.");
  240. }
  241. }
  242. /// <summary>
  243. /// Gets the video bitrate to specify on the command line
  244. /// </summary>
  245. /// <param name="state">The state.</param>
  246. /// <param name="videoCodec">The video codec.</param>
  247. /// <returns>System.String.</returns>
  248. protected string GetVideoQualityParam(StreamState state, string videoCodec)
  249. {
  250. var args = string.Empty;
  251. // webm
  252. if (videoCodec.Equals("libvpx", StringComparison.OrdinalIgnoreCase))
  253. {
  254. args = "-speed 16 -quality good -profile:v 0 -slices 8";
  255. }
  256. // asf/wmv
  257. else if (videoCodec.Equals("wmv2", StringComparison.OrdinalIgnoreCase))
  258. {
  259. args = "-g 100 -qmax 15";
  260. }
  261. else if (videoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase))
  262. {
  263. args = "-preset superfast";
  264. }
  265. else if (videoCodec.Equals("mpeg4", StringComparison.OrdinalIgnoreCase))
  266. {
  267. args = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  268. }
  269. return args.Trim();
  270. }
  271. /// <summary>
  272. /// If we're going to put a fixed size on the command line, this will calculate it
  273. /// </summary>
  274. /// <param name="state">The state.</param>
  275. /// <param name="outputVideoCodec">The output video codec.</param>
  276. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  277. /// <returns>System.String.</returns>
  278. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  279. {
  280. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  281. var assSubtitleParam = string.Empty;
  282. var request = state.VideoRequest;
  283. if (state.SubtitleStream != null)
  284. {
  285. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  286. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  287. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  288. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  289. {
  290. assSubtitleParam = GetTextSubtitleParam(state, request.StartTimeTicks, performTextSubtitleConversion);
  291. }
  292. }
  293. // If fixed dimensions were supplied
  294. if (request.Width.HasValue && request.Height.HasValue)
  295. {
  296. var widthParam = request.Width.Value.ToString(UsCulture);
  297. var heightParam = request.Height.Value.ToString(UsCulture);
  298. return string.Format(" -vf \"scale=trunc({0}/2)*2:trunc({1}/2)*2{2}\"", widthParam, heightParam, assSubtitleParam);
  299. }
  300. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  301. // If a fixed width was requested
  302. if (request.Width.HasValue)
  303. {
  304. var widthParam = request.Width.Value.ToString(UsCulture);
  305. return isH264Output ?
  306. string.Format(" -vf \"scale={0}:trunc(ow/a/2)*2{1}\"", widthParam, assSubtitleParam) :
  307. string.Format(" -vf \"scale={0}:-1{1}\"", widthParam, assSubtitleParam);
  308. }
  309. // If a fixed height was requested
  310. if (request.Height.HasValue)
  311. {
  312. var heightParam = request.Height.Value.ToString(UsCulture);
  313. return isH264Output ?
  314. string.Format(" -vf \"scale=trunc(oh*a*2)/2:{0}{1}\"", heightParam, assSubtitleParam) :
  315. string.Format(" -vf \"scale=-1:{0}{1}\"", heightParam, assSubtitleParam);
  316. }
  317. // If a max width was requested
  318. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  319. {
  320. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  321. return isH264Output ?
  322. string.Format(" -vf \"scale=min(iw\\,{0}):trunc(ow/a/2)*2{1}\"", maxWidthParam, assSubtitleParam) :
  323. string.Format(" -vf \"scale=min(iw\\,{0}):-1{1}\"", maxWidthParam, assSubtitleParam);
  324. }
  325. // If a max height was requested
  326. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  327. {
  328. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  329. return isH264Output ?
  330. string.Format(" -vf \"scale=trunc(oh*a*2)/2:min(ih\\,{0}){1}\"", maxHeightParam, assSubtitleParam) :
  331. string.Format(" -vf \"scale=-1:min(ih\\,{0}){1}\"", maxHeightParam, assSubtitleParam);
  332. }
  333. if (state.VideoStream == null)
  334. {
  335. // No way to figure this out
  336. return string.Empty;
  337. }
  338. // Need to perform calculations manually
  339. // Try to account for bad media info
  340. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  341. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  342. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  343. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  344. if (isH264Output)
  345. {
  346. var widthParam = outputSize.Width.ToString(UsCulture);
  347. var heightParam = outputSize.Height.ToString(UsCulture);
  348. return string.Format(" -vf \"scale=trunc({0}/2)*2:trunc({1}/2)*2{2}\"", widthParam, heightParam, assSubtitleParam);
  349. }
  350. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  351. return string.Format(" -vf \"scale={0}:-1{1}\"", Convert.ToInt32(outputSize.Width), assSubtitleParam);
  352. }
  353. /// <summary>
  354. /// Gets the text subtitle param.
  355. /// </summary>
  356. /// <param name="state">The state.</param>
  357. /// <param name="startTimeTicks">The start time ticks.</param>
  358. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  359. /// <returns>System.String.</returns>
  360. protected string GetTextSubtitleParam(StreamState state, long? startTimeTicks, bool performConversion)
  361. {
  362. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, startTimeTicks, performConversion) :
  363. GetExtractedAssPath(state, startTimeTicks, performConversion);
  364. if (string.IsNullOrEmpty(path))
  365. {
  366. return string.Empty;
  367. }
  368. return string.Format(",ass='{0}'", path.Replace('\\', '/').Replace(":/", "\\:/"));
  369. }
  370. /// <summary>
  371. /// Gets the extracted ass path.
  372. /// </summary>
  373. /// <param name="state">The state.</param>
  374. /// <param name="startTimeTicks">The start time ticks.</param>
  375. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  376. /// <returns>System.String.</returns>
  377. private string GetExtractedAssPath(StreamState state, long? startTimeTicks, bool performConversion)
  378. {
  379. var offset = TimeSpan.FromTicks(startTimeTicks ?? 0);
  380. var path = FFMpegManager.Instance.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream, offset, ".ass");
  381. if (performConversion)
  382. {
  383. InputType type;
  384. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  385. try
  386. {
  387. var parentPath = Path.GetDirectoryName(path);
  388. Directory.CreateDirectory(parentPath);
  389. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, offset, path, CancellationToken.None);
  390. Task.WaitAll(task);
  391. }
  392. catch
  393. {
  394. return null;
  395. }
  396. }
  397. return path;
  398. }
  399. /// <summary>
  400. /// Gets the converted ass path.
  401. /// </summary>
  402. /// <param name="mediaPath">The media path.</param>
  403. /// <param name="subtitleStream">The subtitle stream.</param>
  404. /// <param name="startTimeTicks">The start time ticks.</param>
  405. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  406. /// <returns>System.String.</returns>
  407. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, long? startTimeTicks, bool performConversion)
  408. {
  409. var offset = TimeSpan.FromTicks(startTimeTicks ?? 0);
  410. var path = FFMpegManager.Instance.GetSubtitleCachePath(mediaPath, subtitleStream, offset, ".ass");
  411. if (performConversion)
  412. {
  413. try
  414. {
  415. var parentPath = Path.GetDirectoryName(path);
  416. Directory.CreateDirectory(parentPath);
  417. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, offset, CancellationToken.None);
  418. Task.WaitAll(task);
  419. }
  420. catch
  421. {
  422. return null;
  423. }
  424. }
  425. return path;
  426. }
  427. /// <summary>
  428. /// Gets the internal graphical subtitle param.
  429. /// </summary>
  430. /// <param name="state">The state.</param>
  431. /// <param name="outputVideoCodec">The output video codec.</param>
  432. /// <returns>System.String.</returns>
  433. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  434. {
  435. var outputSizeParam = string.Empty;
  436. var request = state.VideoRequest;
  437. // Add resolution params, if specified
  438. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  439. {
  440. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  441. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  442. }
  443. 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);
  444. }
  445. /// <summary>
  446. /// Gets the probe size argument.
  447. /// </summary>
  448. /// <param name="mediaPath">The media path.</param>
  449. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  450. /// <param name="videoType">Type of the video.</param>
  451. /// <param name="isoType">Type of the iso.</param>
  452. /// <returns>System.String.</returns>
  453. protected string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  454. {
  455. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  456. MediaEncoderHelpers.GetInputType(videoType, isoType);
  457. return MediaEncoder.GetProbeSizeArgument(type);
  458. }
  459. /// <summary>
  460. /// Gets the number of audio channels to specify on the command line
  461. /// </summary>
  462. /// <param name="request">The request.</param>
  463. /// <param name="audioStream">The audio stream.</param>
  464. /// <returns>System.Nullable{System.Int32}.</returns>
  465. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  466. {
  467. if (audioStream != null)
  468. {
  469. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  470. {
  471. if (request.AudioCodec.Value == AudioCodecs.Wma)
  472. {
  473. // wmav2 currently only supports two channel output
  474. return 2;
  475. }
  476. }
  477. }
  478. return request.AudioChannels;
  479. }
  480. /// <summary>
  481. /// Determines whether the specified stream is H264.
  482. /// </summary>
  483. /// <param name="stream">The stream.</param>
  484. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  485. protected bool IsH264(MediaStream stream)
  486. {
  487. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  488. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  489. }
  490. /// <summary>
  491. /// Gets the name of the output audio codec
  492. /// </summary>
  493. /// <param name="request">The request.</param>
  494. /// <returns>System.String.</returns>
  495. protected string GetAudioCodec(StreamRequest request)
  496. {
  497. var codec = request.AudioCodec;
  498. if (codec.HasValue)
  499. {
  500. if (codec == AudioCodecs.Aac)
  501. {
  502. return "aac -strict experimental";
  503. }
  504. if (codec == AudioCodecs.Mp3)
  505. {
  506. return "libmp3lame";
  507. }
  508. if (codec == AudioCodecs.Vorbis)
  509. {
  510. return "libvorbis";
  511. }
  512. if (codec == AudioCodecs.Wma)
  513. {
  514. return "wmav2";
  515. }
  516. return codec.ToString().ToLower();
  517. }
  518. return "copy";
  519. }
  520. /// <summary>
  521. /// Gets the name of the output video codec
  522. /// </summary>
  523. /// <param name="request">The request.</param>
  524. /// <returns>System.String.</returns>
  525. protected string GetVideoCodec(VideoStreamRequest request)
  526. {
  527. var codec = request.VideoCodec;
  528. if (codec.HasValue)
  529. {
  530. if (codec == VideoCodecs.H264)
  531. {
  532. return "libx264";
  533. }
  534. if (codec == VideoCodecs.Vpx)
  535. {
  536. return "libvpx";
  537. }
  538. if (codec == VideoCodecs.Wmv)
  539. {
  540. return "wmv2";
  541. }
  542. if (codec == VideoCodecs.Theora)
  543. {
  544. return "libtheora";
  545. }
  546. return codec.ToString().ToLower();
  547. }
  548. return "copy";
  549. }
  550. /// <summary>
  551. /// Gets the input argument.
  552. /// </summary>
  553. /// <param name="state">The state.</param>
  554. /// <returns>System.String.</returns>
  555. protected string GetInputArgument(StreamState state)
  556. {
  557. if (state.SendInputOverStandardInput)
  558. {
  559. return "-";
  560. }
  561. var type = InputType.AudioFile;
  562. var inputPath = new[] { state.MediaPath };
  563. if (state.IsInputVideo)
  564. {
  565. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  566. {
  567. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  568. }
  569. }
  570. return MediaEncoder.GetInputArgument(inputPath, type);
  571. }
  572. /// <summary>
  573. /// Starts the FFMPEG.
  574. /// </summary>
  575. /// <param name="state">The state.</param>
  576. /// <param name="outputPath">The output path.</param>
  577. /// <returns>Task.</returns>
  578. protected async Task StartFfMpeg(StreamState state, string outputPath)
  579. {
  580. if (!File.Exists(MediaEncoder.EncoderPath))
  581. {
  582. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  583. }
  584. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  585. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  586. {
  587. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  588. }
  589. var process = new Process
  590. {
  591. StartInfo = new ProcessStartInfo
  592. {
  593. CreateNoWindow = true,
  594. UseShellExecute = false,
  595. // Must consume both stdout and stderr or deadlocks may occur
  596. RedirectStandardOutput = true,
  597. RedirectStandardError = true,
  598. FileName = MediaEncoder.EncoderPath,
  599. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  600. Arguments = GetCommandLineArguments(outputPath, state, true),
  601. WindowStyle = ProcessWindowStyle.Hidden,
  602. ErrorDialog = false,
  603. RedirectStandardInput = state.SendInputOverStandardInput
  604. },
  605. EnableRaisingEvents = true
  606. };
  607. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  608. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  609. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  610. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  611. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  612. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  613. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  614. try
  615. {
  616. process.Start();
  617. }
  618. catch (Exception ex)
  619. {
  620. Logger.ErrorException("Error starting ffmpeg", ex);
  621. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  622. state.LogFileStream.Dispose();
  623. throw;
  624. }
  625. if (state.SendInputOverStandardInput)
  626. {
  627. StreamToStandardInput(process, state);
  628. }
  629. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  630. process.BeginOutputReadLine();
  631. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  632. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  633. // Wait for the file to exist before proceeeding
  634. while (!File.Exists(outputPath))
  635. {
  636. await Task.Delay(100).ConfigureAwait(false);
  637. }
  638. // Allow a small amount of time to buffer a little
  639. if (state.IsInputVideo)
  640. {
  641. await Task.Delay(500).ConfigureAwait(false);
  642. }
  643. // This is arbitrary, but add a little buffer time when internet streaming
  644. if (state.IsRemote)
  645. {
  646. await Task.Delay(3000).ConfigureAwait(false);
  647. }
  648. }
  649. private async void StreamToStandardInput(Process process, StreamState state)
  650. {
  651. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  652. try
  653. {
  654. await StreamToStandardInputInternal(process, state).ConfigureAwait(false);
  655. }
  656. catch (OperationCanceledException)
  657. {
  658. Logger.Debug("Stream to standard input closed normally.");
  659. }
  660. catch (Exception ex)
  661. {
  662. Logger.ErrorException("Error writing to standard input", ex);
  663. }
  664. }
  665. private async Task StreamToStandardInputInternal(Process process, StreamState state)
  666. {
  667. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  668. using (var fileStream = FileSystem.GetFileStream(state.MediaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  669. {
  670. await new EndlessStreamCopy().CopyStream(fileStream, process.StandardInput.BaseStream, state.StandardInputCancellationTokenSource.Token).ConfigureAwait(false);
  671. }
  672. }
  673. protected int? GetVideoBitrateParam(StreamState state)
  674. {
  675. return state.VideoRequest.VideoBitRate;
  676. }
  677. protected int? GetAudioBitrateParam(StreamState state)
  678. {
  679. if (state.Request.AudioBitRate.HasValue)
  680. {
  681. // Make sure we don't request a bitrate higher than the source
  682. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  683. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  684. }
  685. return null;
  686. }
  687. /// <summary>
  688. /// Gets the user agent param.
  689. /// </summary>
  690. /// <param name="path">The path.</param>
  691. /// <returns>System.String.</returns>
  692. protected string GetUserAgentParam(string path)
  693. {
  694. var useragent = GetUserAgent(path);
  695. if (!string.IsNullOrEmpty(useragent))
  696. {
  697. return "-user-agent \"" + useragent + "\"";
  698. }
  699. return string.Empty;
  700. }
  701. /// <summary>
  702. /// Gets the user agent.
  703. /// </summary>
  704. /// <param name="path">The path.</param>
  705. /// <returns>System.String.</returns>
  706. protected string GetUserAgent(string path)
  707. {
  708. if (string.IsNullOrEmpty(path))
  709. {
  710. throw new ArgumentNullException("path");
  711. }
  712. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  713. {
  714. return "QuickTime/7.7.4";
  715. }
  716. return string.Empty;
  717. }
  718. /// <summary>
  719. /// Processes the exited.
  720. /// </summary>
  721. /// <param name="process">The process.</param>
  722. /// <param name="state">The state.</param>
  723. protected void OnFfMpegProcessExited(Process process, StreamState state)
  724. {
  725. if (state.IsoMount != null)
  726. {
  727. state.IsoMount.Dispose();
  728. state.IsoMount = null;
  729. }
  730. if (state.StandardInputCancellationTokenSource != null)
  731. {
  732. state.StandardInputCancellationTokenSource.Cancel();
  733. }
  734. var outputFilePath = GetOutputFilePath(state);
  735. state.LogFileStream.Dispose();
  736. try
  737. {
  738. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  739. }
  740. catch
  741. {
  742. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  743. }
  744. }
  745. /// <summary>
  746. /// Gets the state.
  747. /// </summary>
  748. /// <param name="request">The request.</param>
  749. /// <param name="cancellationToken">The cancellation token.</param>
  750. /// <returns>StreamState.</returns>
  751. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  752. {
  753. var url = Request.PathInfo;
  754. if (!request.AudioCodec.HasValue)
  755. {
  756. request.AudioCodec = InferAudioCodec(url);
  757. }
  758. var state = new StreamState
  759. {
  760. Request = request,
  761. RequestedUrl = url
  762. };
  763. Guid itemId;
  764. if (string.Equals(request.Type, "Recording", StringComparison.OrdinalIgnoreCase))
  765. {
  766. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  767. state.VideoType = VideoType.VideoFile;
  768. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  769. state.PlayableStreamFileNames = new List<string>();
  770. if (!string.IsNullOrEmpty(recording.RecordingInfo.Path) && File.Exists(recording.RecordingInfo.Path))
  771. {
  772. state.MediaPath = recording.RecordingInfo.Path;
  773. state.IsRemote = false;
  774. }
  775. else if (!string.IsNullOrEmpty(recording.RecordingInfo.Url))
  776. {
  777. state.MediaPath = recording.RecordingInfo.Url;
  778. state.IsRemote = true;
  779. }
  780. else
  781. {
  782. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  783. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  784. {
  785. state.MediaPath = streamInfo.Path;
  786. state.IsRemote = false;
  787. }
  788. else if (!string.IsNullOrEmpty(streamInfo.Url))
  789. {
  790. state.MediaPath = streamInfo.Url;
  791. state.IsRemote = true;
  792. }
  793. }
  794. itemId = recording.Id;
  795. state.SendInputOverStandardInput = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  796. }
  797. else if (string.Equals(request.Type, "Channel", StringComparison.OrdinalIgnoreCase))
  798. {
  799. var channel = LiveTvManager.GetInternalChannel(request.Id);
  800. state.VideoType = VideoType.VideoFile;
  801. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  802. state.PlayableStreamFileNames = new List<string>();
  803. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  804. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  805. {
  806. state.MediaPath = streamInfo.Path;
  807. state.IsRemote = false;
  808. }
  809. else if (!string.IsNullOrEmpty(streamInfo.Url))
  810. {
  811. state.MediaPath = streamInfo.Url;
  812. state.IsRemote = true;
  813. }
  814. itemId = channel.Id;
  815. state.SendInputOverStandardInput = true;
  816. }
  817. else
  818. {
  819. var item = DtoService.GetItemByDtoId(request.Id);
  820. state.MediaPath = item.Path;
  821. state.IsRemote = item.LocationType == LocationType.Remote;
  822. var video = item as Video;
  823. if (video != null)
  824. {
  825. state.IsInputVideo = true;
  826. state.VideoType = video.VideoType;
  827. state.IsoType = video.IsoType;
  828. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  829. ? new List<string>()
  830. : video.PlayableStreamFileNames.ToList();
  831. }
  832. itemId = item.Id;
  833. }
  834. var videoRequest = request as VideoStreamRequest;
  835. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  836. {
  837. ItemId = itemId
  838. }).ToList();
  839. if (videoRequest != null)
  840. {
  841. if (!videoRequest.VideoCodec.HasValue)
  842. {
  843. videoRequest.VideoCodec = InferVideoCodec(url);
  844. }
  845. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  846. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  847. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  848. }
  849. else
  850. {
  851. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  852. }
  853. state.HasMediaStreams = mediaStreams.Count > 0;
  854. return state;
  855. }
  856. /// <summary>
  857. /// Infers the audio codec based on the url
  858. /// </summary>
  859. /// <param name="url">The URL.</param>
  860. /// <returns>System.Nullable{AudioCodecs}.</returns>
  861. private AudioCodecs? InferAudioCodec(string url)
  862. {
  863. var ext = Path.GetExtension(url);
  864. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  865. {
  866. return AudioCodecs.Mp3;
  867. }
  868. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  869. {
  870. return AudioCodecs.Aac;
  871. }
  872. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  873. {
  874. return AudioCodecs.Wma;
  875. }
  876. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  877. {
  878. return AudioCodecs.Vorbis;
  879. }
  880. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  881. {
  882. return AudioCodecs.Vorbis;
  883. }
  884. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  885. {
  886. return AudioCodecs.Vorbis;
  887. }
  888. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  889. {
  890. return AudioCodecs.Vorbis;
  891. }
  892. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  893. {
  894. return AudioCodecs.Vorbis;
  895. }
  896. return null;
  897. }
  898. /// <summary>
  899. /// Infers the video codec.
  900. /// </summary>
  901. /// <param name="url">The URL.</param>
  902. /// <returns>System.Nullable{VideoCodecs}.</returns>
  903. private VideoCodecs? InferVideoCodec(string url)
  904. {
  905. var ext = Path.GetExtension(url);
  906. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  907. {
  908. return VideoCodecs.Wmv;
  909. }
  910. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  911. {
  912. return VideoCodecs.Vpx;
  913. }
  914. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  915. {
  916. return VideoCodecs.Theora;
  917. }
  918. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  919. {
  920. return VideoCodecs.H264;
  921. }
  922. return VideoCodecs.Copy;
  923. }
  924. }
  925. }