BaseStreamingService.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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 MediaEncodingQuality value.</exception>
  225. protected int GetNumberOfThreads()
  226. {
  227. var quality = ServerConfigurationManager.Configuration.MediaEncodingQuality;
  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 MediaEncodingQuality 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. var videoSizeParam = string.Empty;
  444. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  445. {
  446. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  447. }
  448. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  449. state.SubtitleStream.Index,
  450. state.VideoStream.Index,
  451. outputSizeParam,
  452. videoSizeParam);
  453. }
  454. /// <summary>
  455. /// Gets the probe size argument.
  456. /// </summary>
  457. /// <param name="mediaPath">The media path.</param>
  458. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  459. /// <param name="videoType">Type of the video.</param>
  460. /// <param name="isoType">Type of the iso.</param>
  461. /// <returns>System.String.</returns>
  462. protected string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  463. {
  464. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  465. MediaEncoderHelpers.GetInputType(videoType, isoType);
  466. return MediaEncoder.GetProbeSizeArgument(type);
  467. }
  468. /// <summary>
  469. /// Gets the number of audio channels to specify on the command line
  470. /// </summary>
  471. /// <param name="request">The request.</param>
  472. /// <param name="audioStream">The audio stream.</param>
  473. /// <returns>System.Nullable{System.Int32}.</returns>
  474. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  475. {
  476. if (audioStream != null)
  477. {
  478. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  479. {
  480. if (request.AudioCodec.Value == AudioCodecs.Wma)
  481. {
  482. // wmav2 currently only supports two channel output
  483. return 2;
  484. }
  485. }
  486. }
  487. return request.AudioChannels;
  488. }
  489. /// <summary>
  490. /// Determines whether the specified stream is H264.
  491. /// </summary>
  492. /// <param name="stream">The stream.</param>
  493. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  494. protected bool IsH264(MediaStream stream)
  495. {
  496. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  497. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  498. }
  499. /// <summary>
  500. /// Gets the name of the output audio codec
  501. /// </summary>
  502. /// <param name="request">The request.</param>
  503. /// <returns>System.String.</returns>
  504. protected string GetAudioCodec(StreamRequest request)
  505. {
  506. var codec = request.AudioCodec;
  507. if (codec.HasValue)
  508. {
  509. if (codec == AudioCodecs.Aac)
  510. {
  511. return "aac -strict experimental";
  512. }
  513. if (codec == AudioCodecs.Mp3)
  514. {
  515. return "libmp3lame";
  516. }
  517. if (codec == AudioCodecs.Vorbis)
  518. {
  519. return "libvorbis";
  520. }
  521. if (codec == AudioCodecs.Wma)
  522. {
  523. return "wmav2";
  524. }
  525. return codec.ToString().ToLower();
  526. }
  527. return "copy";
  528. }
  529. /// <summary>
  530. /// Gets the name of the output video codec
  531. /// </summary>
  532. /// <param name="request">The request.</param>
  533. /// <returns>System.String.</returns>
  534. protected string GetVideoCodec(VideoStreamRequest request)
  535. {
  536. var codec = request.VideoCodec;
  537. if (codec.HasValue)
  538. {
  539. if (codec == VideoCodecs.H264)
  540. {
  541. return "libx264";
  542. }
  543. if (codec == VideoCodecs.Vpx)
  544. {
  545. return "libvpx";
  546. }
  547. if (codec == VideoCodecs.Wmv)
  548. {
  549. return "wmv2";
  550. }
  551. if (codec == VideoCodecs.Theora)
  552. {
  553. return "libtheora";
  554. }
  555. return codec.ToString().ToLower();
  556. }
  557. return "copy";
  558. }
  559. /// <summary>
  560. /// Gets the input argument.
  561. /// </summary>
  562. /// <param name="state">The state.</param>
  563. /// <returns>System.String.</returns>
  564. protected string GetInputArgument(StreamState state)
  565. {
  566. if (state.SendInputOverStandardInput)
  567. {
  568. return "-";
  569. }
  570. var type = InputType.AudioFile;
  571. var inputPath = new[] { state.MediaPath };
  572. if (state.IsInputVideo)
  573. {
  574. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  575. {
  576. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  577. }
  578. }
  579. return MediaEncoder.GetInputArgument(inputPath, type);
  580. }
  581. /// <summary>
  582. /// Starts the FFMPEG.
  583. /// </summary>
  584. /// <param name="state">The state.</param>
  585. /// <param name="outputPath">The output path.</param>
  586. /// <returns>Task.</returns>
  587. protected async Task StartFfMpeg(StreamState state, string outputPath)
  588. {
  589. if (!File.Exists(MediaEncoder.EncoderPath))
  590. {
  591. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  592. }
  593. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  594. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  595. {
  596. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  597. }
  598. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  599. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  600. {
  601. commandLineArgs = "-loglevel debug " + commandLineArgs;
  602. }
  603. var process = new Process
  604. {
  605. StartInfo = new ProcessStartInfo
  606. {
  607. CreateNoWindow = true,
  608. UseShellExecute = false,
  609. // Must consume both stdout and stderr or deadlocks may occur
  610. RedirectStandardOutput = true,
  611. RedirectStandardError = true,
  612. FileName = MediaEncoder.EncoderPath,
  613. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  614. Arguments = commandLineArgs,
  615. WindowStyle = ProcessWindowStyle.Hidden,
  616. ErrorDialog = false,
  617. RedirectStandardInput = state.SendInputOverStandardInput
  618. },
  619. EnableRaisingEvents = true
  620. };
  621. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  622. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  623. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  624. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  625. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  626. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  627. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  628. try
  629. {
  630. process.Start();
  631. }
  632. catch (Exception ex)
  633. {
  634. Logger.ErrorException("Error starting ffmpeg", ex);
  635. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  636. state.LogFileStream.Dispose();
  637. throw;
  638. }
  639. if (state.SendInputOverStandardInput)
  640. {
  641. StreamToStandardInput(process, state);
  642. }
  643. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  644. process.BeginOutputReadLine();
  645. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  646. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  647. // Wait for the file to exist before proceeeding
  648. while (!File.Exists(outputPath))
  649. {
  650. await Task.Delay(100).ConfigureAwait(false);
  651. }
  652. // Allow a small amount of time to buffer a little
  653. if (state.IsInputVideo)
  654. {
  655. await Task.Delay(500).ConfigureAwait(false);
  656. }
  657. // This is arbitrary, but add a little buffer time when internet streaming
  658. if (state.IsRemote)
  659. {
  660. await Task.Delay(3000).ConfigureAwait(false);
  661. }
  662. }
  663. private async void StreamToStandardInput(Process process, StreamState state)
  664. {
  665. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  666. try
  667. {
  668. await StreamToStandardInputInternal(process, state).ConfigureAwait(false);
  669. }
  670. catch (OperationCanceledException)
  671. {
  672. Logger.Debug("Stream to standard input closed normally.");
  673. }
  674. catch (Exception ex)
  675. {
  676. Logger.ErrorException("Error writing to standard input", ex);
  677. }
  678. }
  679. private async Task StreamToStandardInputInternal(Process process, StreamState state)
  680. {
  681. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  682. using (var fileStream = FileSystem.GetFileStream(state.MediaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  683. {
  684. await new EndlessStreamCopy().CopyStream(fileStream, process.StandardInput.BaseStream, state.StandardInputCancellationTokenSource.Token).ConfigureAwait(false);
  685. }
  686. }
  687. protected int? GetVideoBitrateParam(StreamState state)
  688. {
  689. return state.VideoRequest.VideoBitRate;
  690. }
  691. protected int? GetAudioBitrateParam(StreamState state)
  692. {
  693. if (state.Request.AudioBitRate.HasValue)
  694. {
  695. // Make sure we don't request a bitrate higher than the source
  696. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  697. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  698. }
  699. return null;
  700. }
  701. /// <summary>
  702. /// Gets the user agent param.
  703. /// </summary>
  704. /// <param name="path">The path.</param>
  705. /// <returns>System.String.</returns>
  706. protected string GetUserAgentParam(string path)
  707. {
  708. var useragent = GetUserAgent(path);
  709. if (!string.IsNullOrEmpty(useragent))
  710. {
  711. return "-user-agent \"" + useragent + "\"";
  712. }
  713. return string.Empty;
  714. }
  715. /// <summary>
  716. /// Gets the user agent.
  717. /// </summary>
  718. /// <param name="path">The path.</param>
  719. /// <returns>System.String.</returns>
  720. protected string GetUserAgent(string path)
  721. {
  722. if (string.IsNullOrEmpty(path))
  723. {
  724. throw new ArgumentNullException("path");
  725. }
  726. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  727. {
  728. return "QuickTime/7.7.4";
  729. }
  730. return string.Empty;
  731. }
  732. /// <summary>
  733. /// Processes the exited.
  734. /// </summary>
  735. /// <param name="process">The process.</param>
  736. /// <param name="state">The state.</param>
  737. protected async void OnFfMpegProcessExited(Process process, StreamState state)
  738. {
  739. if (state.IsoMount != null)
  740. {
  741. state.IsoMount.Dispose();
  742. state.IsoMount = null;
  743. }
  744. if (state.StandardInputCancellationTokenSource != null)
  745. {
  746. state.StandardInputCancellationTokenSource.Cancel();
  747. }
  748. var outputFilePath = GetOutputFilePath(state);
  749. state.LogFileStream.Dispose();
  750. try
  751. {
  752. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  753. }
  754. catch
  755. {
  756. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  757. }
  758. if (!string.IsNullOrEmpty(state.LiveTvStreamId))
  759. {
  760. try
  761. {
  762. await LiveTvManager.CloseLiveStream(state.LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  763. }
  764. catch (Exception ex)
  765. {
  766. Logger.ErrorException("Error closing live tv stream", ex);
  767. }
  768. }
  769. }
  770. /// <summary>
  771. /// Gets the state.
  772. /// </summary>
  773. /// <param name="request">The request.</param>
  774. /// <param name="cancellationToken">The cancellation token.</param>
  775. /// <returns>StreamState.</returns>
  776. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  777. {
  778. var url = Request.PathInfo;
  779. if (!request.AudioCodec.HasValue)
  780. {
  781. request.AudioCodec = InferAudioCodec(url);
  782. }
  783. var state = new StreamState
  784. {
  785. Request = request,
  786. RequestedUrl = url
  787. };
  788. Guid itemId;
  789. if (string.Equals(request.Type, "Recording", StringComparison.OrdinalIgnoreCase))
  790. {
  791. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  792. state.VideoType = VideoType.VideoFile;
  793. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  794. state.PlayableStreamFileNames = new List<string>();
  795. if (!string.IsNullOrEmpty(recording.RecordingInfo.Path) && File.Exists(recording.RecordingInfo.Path))
  796. {
  797. state.MediaPath = recording.RecordingInfo.Path;
  798. state.IsRemote = false;
  799. }
  800. else if (!string.IsNullOrEmpty(recording.RecordingInfo.Url))
  801. {
  802. state.MediaPath = recording.RecordingInfo.Url;
  803. state.IsRemote = true;
  804. }
  805. else
  806. {
  807. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  808. state.LiveTvStreamId = streamInfo.Id;
  809. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  810. {
  811. state.MediaPath = streamInfo.Path;
  812. state.IsRemote = false;
  813. }
  814. else if (!string.IsNullOrEmpty(streamInfo.Url))
  815. {
  816. state.MediaPath = streamInfo.Url;
  817. state.IsRemote = true;
  818. }
  819. }
  820. itemId = recording.Id;
  821. state.SendInputOverStandardInput = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  822. }
  823. else if (string.Equals(request.Type, "Channel", StringComparison.OrdinalIgnoreCase))
  824. {
  825. var channel = LiveTvManager.GetInternalChannel(request.Id);
  826. state.VideoType = VideoType.VideoFile;
  827. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  828. state.PlayableStreamFileNames = new List<string>();
  829. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  830. state.LiveTvStreamId = streamInfo.Id;
  831. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  832. {
  833. state.MediaPath = streamInfo.Path;
  834. state.IsRemote = false;
  835. }
  836. else if (!string.IsNullOrEmpty(streamInfo.Url))
  837. {
  838. state.MediaPath = streamInfo.Url;
  839. state.IsRemote = true;
  840. }
  841. itemId = channel.Id;
  842. state.SendInputOverStandardInput = true;
  843. }
  844. else
  845. {
  846. var item = DtoService.GetItemByDtoId(request.Id);
  847. state.MediaPath = item.Path;
  848. state.IsRemote = item.LocationType == LocationType.Remote;
  849. var video = item as Video;
  850. if (video != null)
  851. {
  852. state.IsInputVideo = true;
  853. state.VideoType = video.VideoType;
  854. state.IsoType = video.IsoType;
  855. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  856. ? new List<string>()
  857. : video.PlayableStreamFileNames.ToList();
  858. }
  859. itemId = item.Id;
  860. }
  861. var videoRequest = request as VideoStreamRequest;
  862. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  863. {
  864. ItemId = itemId
  865. }).ToList();
  866. if (videoRequest != null)
  867. {
  868. if (!videoRequest.VideoCodec.HasValue)
  869. {
  870. videoRequest.VideoCodec = InferVideoCodec(url);
  871. }
  872. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  873. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  874. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  875. }
  876. else
  877. {
  878. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  879. }
  880. state.HasMediaStreams = mediaStreams.Count > 0;
  881. return state;
  882. }
  883. /// <summary>
  884. /// Infers the audio codec based on the url
  885. /// </summary>
  886. /// <param name="url">The URL.</param>
  887. /// <returns>System.Nullable{AudioCodecs}.</returns>
  888. private AudioCodecs? InferAudioCodec(string url)
  889. {
  890. var ext = Path.GetExtension(url);
  891. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  892. {
  893. return AudioCodecs.Mp3;
  894. }
  895. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  896. {
  897. return AudioCodecs.Aac;
  898. }
  899. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  900. {
  901. return AudioCodecs.Wma;
  902. }
  903. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  904. {
  905. return AudioCodecs.Vorbis;
  906. }
  907. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  908. {
  909. return AudioCodecs.Vorbis;
  910. }
  911. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  912. {
  913. return AudioCodecs.Vorbis;
  914. }
  915. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  916. {
  917. return AudioCodecs.Vorbis;
  918. }
  919. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  920. {
  921. return AudioCodecs.Vorbis;
  922. }
  923. return null;
  924. }
  925. /// <summary>
  926. /// Infers the video codec.
  927. /// </summary>
  928. /// <param name="url">The URL.</param>
  929. /// <returns>System.Nullable{VideoCodecs}.</returns>
  930. private VideoCodecs? InferVideoCodec(string url)
  931. {
  932. var ext = Path.GetExtension(url);
  933. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  934. {
  935. return VideoCodecs.Wmv;
  936. }
  937. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  938. {
  939. return VideoCodecs.Vpx;
  940. }
  941. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  942. {
  943. return VideoCodecs.Theora;
  944. }
  945. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  946. {
  947. return VideoCodecs.H264;
  948. }
  949. return VideoCodecs.Copy;
  950. }
  951. }
  952. }