BaseStreamingService.cs 45 KB

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