BaseStreamingService.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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 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.EncodedMediaCachePath;
  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. /// <summary>
  220. /// Gets the number of threads.
  221. /// </summary>
  222. /// <returns>System.Int32.</returns>
  223. /// <exception cref="System.Exception">Unrecognized EncodingQuality value.</exception>
  224. protected int GetNumberOfThreads()
  225. {
  226. var quality = ServerConfigurationManager.Configuration.EncodingQuality;
  227. switch (quality)
  228. {
  229. case EncodingQuality.Auto:
  230. return 0;
  231. case EncodingQuality.HighSpeed:
  232. return 2;
  233. case EncodingQuality.HighQuality:
  234. return 2;
  235. case EncodingQuality.MaxQuality:
  236. return 0;
  237. default:
  238. throw new Exception("Unrecognized EncodingQuality value.");
  239. }
  240. }
  241. /// <summary>
  242. /// Gets the video bitrate to specify on the command line
  243. /// </summary>
  244. /// <param name="state">The state.</param>
  245. /// <param name="videoCodec">The video codec.</param>
  246. /// <returns>System.String.</returns>
  247. protected string GetVideoQualityParam(StreamState state, string videoCodec)
  248. {
  249. var args = string.Empty;
  250. // webm
  251. if (videoCodec.Equals("libvpx", StringComparison.OrdinalIgnoreCase))
  252. {
  253. args = "-speed 16 -quality good -profile:v 0 -slices 8";
  254. }
  255. // asf/wmv
  256. else if (videoCodec.Equals("wmv2", StringComparison.OrdinalIgnoreCase))
  257. {
  258. args = "-g 100 -qmax 15";
  259. }
  260. else if (videoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase))
  261. {
  262. args = "-preset superfast";
  263. }
  264. else if (videoCodec.Equals("mpeg4", StringComparison.OrdinalIgnoreCase))
  265. {
  266. args = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  267. }
  268. return args.Trim();
  269. }
  270. /// <summary>
  271. /// If we're going to put a fixed size on the command line, this will calculate it
  272. /// </summary>
  273. /// <param name="state">The state.</param>
  274. /// <param name="outputVideoCodec">The output video codec.</param>
  275. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  276. /// <returns>System.String.</returns>
  277. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  278. {
  279. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  280. var assSubtitleParam = string.Empty;
  281. var request = state.VideoRequest;
  282. if (state.SubtitleStream != null)
  283. {
  284. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  285. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  286. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  287. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  288. {
  289. assSubtitleParam = GetTextSubtitleParam(state, request.StartTimeTicks, performTextSubtitleConversion);
  290. }
  291. }
  292. // If fixed dimensions were supplied
  293. if (request.Width.HasValue && request.Height.HasValue)
  294. {
  295. var widthParam = request.Width.Value.ToString(UsCulture);
  296. var heightParam = request.Height.Value.ToString(UsCulture);
  297. return string.Format(" -vf \"scale=trunc({0}/2)*2:trunc({1}/2)*2{2}\"", widthParam, heightParam, assSubtitleParam);
  298. }
  299. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  300. // If a fixed width was requested
  301. if (request.Width.HasValue)
  302. {
  303. var widthParam = request.Width.Value.ToString(UsCulture);
  304. return isH264Output ?
  305. string.Format(" -vf \"scale={0}:trunc(ow/a/2)*2{1}\"", widthParam, assSubtitleParam) :
  306. string.Format(" -vf \"scale={0}:-1{1}\"", widthParam, assSubtitleParam);
  307. }
  308. // If a fixed height was requested
  309. if (request.Height.HasValue)
  310. {
  311. var heightParam = request.Height.Value.ToString(UsCulture);
  312. return isH264Output ?
  313. string.Format(" -vf \"scale=trunc(oh*a*2)/2:{0}{1}\"", heightParam, assSubtitleParam) :
  314. string.Format(" -vf \"scale=-1:{0}{1}\"", heightParam, assSubtitleParam);
  315. }
  316. // If a max width was requested
  317. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  318. {
  319. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  320. return isH264Output ?
  321. string.Format(" -vf \"scale=min(iw\\,{0}):trunc(ow/a/2)*2{1}\"", maxWidthParam, assSubtitleParam) :
  322. string.Format(" -vf \"scale=min(iw\\,{0}):-1{1}\"", maxWidthParam, assSubtitleParam);
  323. }
  324. // If a max height was requested
  325. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  326. {
  327. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  328. return isH264Output ?
  329. string.Format(" -vf \"scale=trunc(oh*a*2)/2:min(ih\\,{0}){1}\"", maxHeightParam, assSubtitleParam) :
  330. string.Format(" -vf \"scale=-1:min(ih\\,{0}){1}\"", maxHeightParam, assSubtitleParam);
  331. }
  332. if (state.VideoStream == null)
  333. {
  334. // No way to figure this out
  335. return string.Empty;
  336. }
  337. // Need to perform calculations manually
  338. // Try to account for bad media info
  339. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  340. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  341. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  342. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  343. if (isH264Output)
  344. {
  345. var widthParam = outputSize.Width.ToString(UsCulture);
  346. var heightParam = outputSize.Height.ToString(UsCulture);
  347. return string.Format(" -vf \"scale=trunc({0}/2)*2:trunc({1}/2)*2{2}\"", widthParam, heightParam, assSubtitleParam);
  348. }
  349. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  350. return string.Format(" -vf \"scale={0}:-1{1}\"", Convert.ToInt32(outputSize.Width), assSubtitleParam);
  351. }
  352. /// <summary>
  353. /// Gets the text subtitle param.
  354. /// </summary>
  355. /// <param name="state">The state.</param>
  356. /// <param name="startTimeTicks">The start time ticks.</param>
  357. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  358. /// <returns>System.String.</returns>
  359. protected string GetTextSubtitleParam(StreamState state, long? startTimeTicks, bool performConversion)
  360. {
  361. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, startTimeTicks, performConversion) :
  362. GetExtractedAssPath(state, startTimeTicks, performConversion);
  363. if (string.IsNullOrEmpty(path))
  364. {
  365. return string.Empty;
  366. }
  367. return string.Format(",ass='{0}'", path.Replace('\\', '/').Replace(":/", "\\:/"));
  368. }
  369. /// <summary>
  370. /// Gets the extracted ass path.
  371. /// </summary>
  372. /// <param name="state">The state.</param>
  373. /// <param name="startTimeTicks">The start time ticks.</param>
  374. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  375. /// <returns>System.String.</returns>
  376. private string GetExtractedAssPath(StreamState state, long? startTimeTicks, bool performConversion)
  377. {
  378. var offset = TimeSpan.FromTicks(startTimeTicks ?? 0);
  379. var path = FFMpegManager.Instance.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream, offset, ".ass");
  380. if (performConversion)
  381. {
  382. InputType type;
  383. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  384. try
  385. {
  386. var parentPath = Path.GetDirectoryName(path);
  387. Directory.CreateDirectory(parentPath);
  388. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, offset, path, CancellationToken.None);
  389. Task.WaitAll(task);
  390. }
  391. catch
  392. {
  393. return null;
  394. }
  395. }
  396. return path;
  397. }
  398. /// <summary>
  399. /// Gets the converted ass path.
  400. /// </summary>
  401. /// <param name="mediaPath">The media path.</param>
  402. /// <param name="subtitleStream">The subtitle stream.</param>
  403. /// <param name="startTimeTicks">The start time ticks.</param>
  404. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  405. /// <returns>System.String.</returns>
  406. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, long? startTimeTicks, bool performConversion)
  407. {
  408. var offset = TimeSpan.FromTicks(startTimeTicks ?? 0);
  409. var path = FFMpegManager.Instance.GetSubtitleCachePath(mediaPath, subtitleStream, offset, ".ass");
  410. if (performConversion)
  411. {
  412. try
  413. {
  414. var parentPath = Path.GetDirectoryName(path);
  415. Directory.CreateDirectory(parentPath);
  416. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, offset, CancellationToken.None);
  417. Task.WaitAll(task);
  418. }
  419. catch
  420. {
  421. return null;
  422. }
  423. }
  424. return path;
  425. }
  426. /// <summary>
  427. /// Gets the internal graphical subtitle param.
  428. /// </summary>
  429. /// <param name="state">The state.</param>
  430. /// <param name="outputVideoCodec">The output video codec.</param>
  431. /// <returns>System.String.</returns>
  432. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  433. {
  434. var outputSizeParam = string.Empty;
  435. var request = state.VideoRequest;
  436. // Add resolution params, if specified
  437. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  438. {
  439. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  440. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  441. }
  442. 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);
  443. }
  444. /// <summary>
  445. /// Gets the probe size argument.
  446. /// </summary>
  447. /// <param name="mediaPath">The media path.</param>
  448. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  449. /// <param name="videoType">Type of the video.</param>
  450. /// <param name="isoType">Type of the iso.</param>
  451. /// <returns>System.String.</returns>
  452. protected string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  453. {
  454. var type = !isVideo ? MediaEncoderHelpers.GetInputType(mediaPath, null, null) :
  455. MediaEncoderHelpers.GetInputType(mediaPath, videoType, isoType);
  456. return MediaEncoder.GetProbeSizeArgument(type);
  457. }
  458. /// <summary>
  459. /// Gets the number of audio channels to specify on the command line
  460. /// </summary>
  461. /// <param name="request">The request.</param>
  462. /// <param name="audioStream">The audio stream.</param>
  463. /// <returns>System.Nullable{System.Int32}.</returns>
  464. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  465. {
  466. if (audioStream != null)
  467. {
  468. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  469. {
  470. if (request.AudioCodec.Value == AudioCodecs.Wma)
  471. {
  472. // wmav2 currently only supports two channel output
  473. return 2;
  474. }
  475. }
  476. }
  477. return request.AudioChannels;
  478. }
  479. /// <summary>
  480. /// Determines whether the specified stream is H264.
  481. /// </summary>
  482. /// <param name="stream">The stream.</param>
  483. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  484. protected bool IsH264(MediaStream stream)
  485. {
  486. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  487. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  488. }
  489. /// <summary>
  490. /// Gets the name of the output audio codec
  491. /// </summary>
  492. /// <param name="request">The request.</param>
  493. /// <returns>System.String.</returns>
  494. protected string GetAudioCodec(StreamRequest request)
  495. {
  496. var codec = request.AudioCodec;
  497. if (codec.HasValue)
  498. {
  499. if (codec == AudioCodecs.Aac)
  500. {
  501. return "aac -strict experimental";
  502. }
  503. if (codec == AudioCodecs.Mp3)
  504. {
  505. return "libmp3lame";
  506. }
  507. if (codec == AudioCodecs.Vorbis)
  508. {
  509. return "libvorbis";
  510. }
  511. if (codec == AudioCodecs.Wma)
  512. {
  513. return "wmav2";
  514. }
  515. return codec.ToString().ToLower();
  516. }
  517. return "copy";
  518. }
  519. /// <summary>
  520. /// Gets the name of the output video codec
  521. /// </summary>
  522. /// <param name="request">The request.</param>
  523. /// <returns>System.String.</returns>
  524. protected string GetVideoCodec(VideoStreamRequest request)
  525. {
  526. var codec = request.VideoCodec;
  527. if (codec.HasValue)
  528. {
  529. if (codec == VideoCodecs.H264)
  530. {
  531. return "libx264";
  532. }
  533. if (codec == VideoCodecs.Vpx)
  534. {
  535. return "libvpx";
  536. }
  537. if (codec == VideoCodecs.Wmv)
  538. {
  539. return "wmv2";
  540. }
  541. if (codec == VideoCodecs.Theora)
  542. {
  543. return "libtheora";
  544. }
  545. return codec.ToString().ToLower();
  546. }
  547. return "copy";
  548. }
  549. /// <summary>
  550. /// Gets the input argument.
  551. /// </summary>
  552. /// <param name="state">The state.</param>
  553. /// <returns>System.String.</returns>
  554. protected string GetInputArgument(StreamState state)
  555. {
  556. var type = InputType.AudioFile;
  557. var inputPath = new[] { state.MediaPath };
  558. if (state.IsInputVideo)
  559. {
  560. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  561. {
  562. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  563. }
  564. }
  565. return MediaEncoder.GetInputArgument(inputPath, type);
  566. }
  567. /// <summary>
  568. /// Starts the FFMPEG.
  569. /// </summary>
  570. /// <param name="state">The state.</param>
  571. /// <param name="outputPath">The output path.</param>
  572. /// <returns>Task.</returns>
  573. protected async Task StartFfMpeg(StreamState state, string outputPath)
  574. {
  575. if (!File.Exists(MediaEncoder.EncoderPath))
  576. {
  577. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  578. }
  579. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  580. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  581. {
  582. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  583. }
  584. var process = new Process
  585. {
  586. StartInfo = new ProcessStartInfo
  587. {
  588. CreateNoWindow = true,
  589. UseShellExecute = false,
  590. // Must consume both stdout and stderr or deadlocks may occur
  591. RedirectStandardOutput = true,
  592. RedirectStandardError = true,
  593. FileName = MediaEncoder.EncoderPath,
  594. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  595. Arguments = GetCommandLineArguments(outputPath, state, true),
  596. WindowStyle = ProcessWindowStyle.Hidden,
  597. ErrorDialog = false
  598. },
  599. EnableRaisingEvents = true
  600. };
  601. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  602. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  603. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  604. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  605. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  606. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  607. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  608. try
  609. {
  610. process.Start();
  611. }
  612. catch (Exception ex)
  613. {
  614. Logger.ErrorException("Error starting ffmpeg", ex);
  615. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  616. state.LogFileStream.Dispose();
  617. throw;
  618. }
  619. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  620. process.BeginOutputReadLine();
  621. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  622. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  623. // Wait for the file to exist before proceeeding
  624. while (!File.Exists(outputPath))
  625. {
  626. await Task.Delay(100).ConfigureAwait(false);
  627. }
  628. // Allow a small amount of time to buffer a little
  629. if (state.IsInputVideo)
  630. {
  631. await Task.Delay(500).ConfigureAwait(false);
  632. }
  633. // This is arbitrary, but add a little buffer time when internet streaming
  634. if (state.IsRemote)
  635. {
  636. await Task.Delay(3000).ConfigureAwait(false);
  637. }
  638. }
  639. protected int? GetVideoBitrateParam(StreamState state)
  640. {
  641. return state.VideoRequest.VideoBitRate;
  642. }
  643. protected int? GetAudioBitrateParam(StreamState state)
  644. {
  645. if (state.Request.AudioBitRate.HasValue)
  646. {
  647. // Make sure we don't request a bitrate higher than the source
  648. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  649. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  650. }
  651. return null;
  652. }
  653. /// <summary>
  654. /// Gets the user agent param.
  655. /// </summary>
  656. /// <param name="path">The path.</param>
  657. /// <returns>System.String.</returns>
  658. protected string GetUserAgentParam(string path)
  659. {
  660. var useragent = GetUserAgent(path);
  661. if (!string.IsNullOrEmpty(useragent))
  662. {
  663. return "-user-agent \"" + useragent + "\"";
  664. }
  665. return string.Empty;
  666. }
  667. /// <summary>
  668. /// Gets the user agent.
  669. /// </summary>
  670. /// <param name="path">The path.</param>
  671. /// <returns>System.String.</returns>
  672. protected string GetUserAgent(string path)
  673. {
  674. if (string.IsNullOrEmpty(path))
  675. {
  676. throw new ArgumentNullException("path");
  677. }
  678. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  679. {
  680. return "QuickTime/7.7.4";
  681. }
  682. return string.Empty;
  683. }
  684. /// <summary>
  685. /// Processes the exited.
  686. /// </summary>
  687. /// <param name="process">The process.</param>
  688. /// <param name="state">The state.</param>
  689. protected void OnFfMpegProcessExited(Process process, StreamState state)
  690. {
  691. if (state.IsoMount != null)
  692. {
  693. state.IsoMount.Dispose();
  694. state.IsoMount = null;
  695. }
  696. var outputFilePath = GetOutputFilePath(state);
  697. state.LogFileStream.Dispose();
  698. try
  699. {
  700. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  701. }
  702. catch
  703. {
  704. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  705. }
  706. }
  707. /// <summary>
  708. /// Gets the state.
  709. /// </summary>
  710. /// <param name="request">The request.</param>
  711. /// <param name="cancellationToken">The cancellation token.</param>
  712. /// <returns>StreamState.</returns>
  713. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  714. {
  715. var url = Request.PathInfo;
  716. if (!request.AudioCodec.HasValue)
  717. {
  718. request.AudioCodec = InferAudioCodec(url);
  719. }
  720. var state = new StreamState
  721. {
  722. Request = request,
  723. RequestedUrl = url
  724. };
  725. Guid itemId;
  726. if (string.Equals(request.Type, "Recording", StringComparison.OrdinalIgnoreCase))
  727. {
  728. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  729. state.VideoType = VideoType.VideoFile;
  730. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  731. state.PlayableStreamFileNames = new List<string>();
  732. if (!string.IsNullOrEmpty(recording.RecordingInfo.Path) && File.Exists(recording.RecordingInfo.Path))
  733. {
  734. state.MediaPath = recording.RecordingInfo.Path;
  735. state.IsRemote = false;
  736. }
  737. else if (!string.IsNullOrEmpty(recording.RecordingInfo.Url))
  738. {
  739. state.MediaPath = recording.RecordingInfo.Url;
  740. state.IsRemote = true;
  741. }
  742. else
  743. {
  744. state.MediaPath = string.Format("http://localhost:{0}/mediabrowser/LiveTv/Recordings/{1}/Stream",
  745. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  746. request.Id);
  747. state.IsRemote = true;
  748. }
  749. itemId = recording.Id;
  750. }
  751. else if (string.Equals(request.Type, "Channel", StringComparison.OrdinalIgnoreCase))
  752. {
  753. var channel = LiveTvManager.GetInternalChannel(request.Id);
  754. state.VideoType = VideoType.VideoFile;
  755. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  756. state.PlayableStreamFileNames = new List<string>();
  757. state.MediaPath = string.Format("http://localhost:{0}/mediabrowser/LiveTv/Channels/{1}/Stream",
  758. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  759. request.Id);
  760. state.IsRemote = true;
  761. itemId = channel.Id;
  762. }
  763. else
  764. {
  765. var item = DtoService.GetItemByDtoId(request.Id);
  766. state.MediaPath = item.Path;
  767. state.IsRemote = item.LocationType == LocationType.Remote;
  768. var video = item as Video;
  769. if (video != null)
  770. {
  771. state.IsInputVideo = true;
  772. state.VideoType = video.VideoType;
  773. state.IsoType = video.IsoType;
  774. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  775. ? new List<string>()
  776. : video.PlayableStreamFileNames.ToList();
  777. }
  778. itemId = item.Id;
  779. }
  780. var videoRequest = request as VideoStreamRequest;
  781. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  782. {
  783. ItemId = itemId
  784. }).ToList();
  785. if (videoRequest != null)
  786. {
  787. if (!videoRequest.VideoCodec.HasValue)
  788. {
  789. videoRequest.VideoCodec = InferVideoCodec(url);
  790. }
  791. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  792. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  793. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  794. }
  795. else
  796. {
  797. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  798. }
  799. state.HasMediaStreams = mediaStreams.Count > 0;
  800. return state;
  801. }
  802. /// <summary>
  803. /// Infers the audio codec based on the url
  804. /// </summary>
  805. /// <param name="url">The URL.</param>
  806. /// <returns>System.Nullable{AudioCodecs}.</returns>
  807. private AudioCodecs? InferAudioCodec(string url)
  808. {
  809. var ext = Path.GetExtension(url);
  810. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  811. {
  812. return AudioCodecs.Mp3;
  813. }
  814. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  815. {
  816. return AudioCodecs.Aac;
  817. }
  818. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  819. {
  820. return AudioCodecs.Wma;
  821. }
  822. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  823. {
  824. return AudioCodecs.Vorbis;
  825. }
  826. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  827. {
  828. return AudioCodecs.Vorbis;
  829. }
  830. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  831. {
  832. return AudioCodecs.Vorbis;
  833. }
  834. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  835. {
  836. return AudioCodecs.Vorbis;
  837. }
  838. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  839. {
  840. return AudioCodecs.Vorbis;
  841. }
  842. return null;
  843. }
  844. /// <summary>
  845. /// Infers the video codec.
  846. /// </summary>
  847. /// <param name="url">The URL.</param>
  848. /// <returns>System.Nullable{VideoCodecs}.</returns>
  849. private VideoCodecs? InferVideoCodec(string url)
  850. {
  851. var ext = Path.GetExtension(url);
  852. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  853. {
  854. return VideoCodecs.Wmv;
  855. }
  856. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  857. {
  858. return VideoCodecs.Vpx;
  859. }
  860. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  861. {
  862. return VideoCodecs.Theora;
  863. }
  864. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  865. {
  866. return VideoCodecs.H264;
  867. }
  868. return VideoCodecs.Copy;
  869. }
  870. }
  871. }