BaseStreamingService.cs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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 2;
  249. case EncodingQuality.MaxQuality:
  250. return isWebm ? 2 : 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, bool isHls)
  262. {
  263. var param = string.Empty;
  264. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  265. {
  266. switch (GetQualitySetting())
  267. {
  268. case EncodingQuality.HighSpeed:
  269. param = "-preset ultrafast -crf 18";
  270. break;
  271. case EncodingQuality.HighQuality:
  272. param = "-preset superfast -crf 18";
  273. break;
  274. case EncodingQuality.MaxQuality:
  275. param = "-preset superfast -crf 18";
  276. break;
  277. }
  278. }
  279. // webm
  280. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  281. {
  282. // http://www.webmproject.org/docs/encoder-parameters/
  283. param = "-speed 16 -quality good -profile:v 0 -slices 8 -crf 18";
  284. }
  285. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  286. {
  287. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  288. }
  289. // asf/wmv
  290. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  291. {
  292. param = "-qmin 2";
  293. }
  294. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  295. {
  296. param = "-mbd 2";
  297. }
  298. param += GetVideoBitrateParam(state, videoCodec, isHls);
  299. var framerate = GetFramerateParam(state);
  300. if (framerate.HasValue)
  301. {
  302. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  303. }
  304. if (!string.IsNullOrEmpty(state.VideoSync))
  305. {
  306. param += " -vsync " + state.VideoSync;
  307. }
  308. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  309. {
  310. param += " -profile:v " + state.VideoRequest.Profile;
  311. }
  312. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  313. {
  314. param += " -level " + state.VideoRequest.Level;
  315. }
  316. return param;
  317. }
  318. protected string GetAudioFilterParam(StreamState state, bool isHls)
  319. {
  320. var volParam = string.Empty;
  321. var audioSampleRate = string.Empty;
  322. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  323. // Boost volume to 200% when downsampling from 6ch to 2ch
  324. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  325. {
  326. volParam = ",volume=2.000000";
  327. }
  328. if (state.Request.AudioSampleRate.HasValue)
  329. {
  330. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  331. }
  332. var adelay = isHls ? "adelay=1," : string.Empty;
  333. var pts = string.Empty;
  334. if (state.SubtitleStream != null)
  335. {
  336. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  337. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  338. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  339. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  340. {
  341. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  342. pts = string.Format(",asetpts=PTS-{0}/TB",
  343. Math.Round(seconds).ToString(UsCulture));
  344. }
  345. }
  346. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  347. adelay,
  348. audioSampleRate,
  349. volParam,
  350. pts,
  351. state.AudioSync);
  352. }
  353. /// <summary>
  354. /// If we're going to put a fixed size on the command line, this will calculate it
  355. /// </summary>
  356. /// <param name="state">The state.</param>
  357. /// <param name="outputVideoCodec">The output video codec.</param>
  358. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  359. /// <returns>System.String.</returns>
  360. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  361. {
  362. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  363. var assSubtitleParam = string.Empty;
  364. var copyTsParam = string.Empty;
  365. var yadifParam = state.DeInterlace ? "yadif=0:-1:0," : string.Empty;
  366. var request = state.VideoRequest;
  367. if (state.SubtitleStream != null)
  368. {
  369. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  370. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  371. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  372. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  373. {
  374. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  375. copyTsParam = " -copyts";
  376. }
  377. }
  378. // If fixed dimensions were supplied
  379. if (request.Width.HasValue && request.Height.HasValue)
  380. {
  381. var widthParam = request.Width.Value.ToString(UsCulture);
  382. var heightParam = request.Height.Value.ToString(UsCulture);
  383. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  384. }
  385. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  386. // If a fixed width was requested
  387. if (request.Width.HasValue)
  388. {
  389. var widthParam = request.Width.Value.ToString(UsCulture);
  390. return isH264Output ?
  391. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  392. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam);
  393. }
  394. // If a fixed height was requested
  395. if (request.Height.HasValue)
  396. {
  397. var heightParam = request.Height.Value.ToString(UsCulture);
  398. return isH264Output ?
  399. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  400. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam);
  401. }
  402. // If a max width was requested
  403. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  404. {
  405. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  406. return isH264Output ?
  407. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  408. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  409. }
  410. // If a max height was requested
  411. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  412. {
  413. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  414. return isH264Output ?
  415. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  416. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  417. }
  418. if (state.VideoStream == null)
  419. {
  420. // No way to figure this out
  421. return string.Empty;
  422. }
  423. // Need to perform calculations manually
  424. // Try to account for bad media info
  425. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  426. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  427. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  428. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  429. if (isH264Output)
  430. {
  431. var widthParam = outputSize.Width.ToString(UsCulture);
  432. var heightParam = outputSize.Height.ToString(UsCulture);
  433. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  434. }
  435. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  436. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  437. }
  438. /// <summary>
  439. /// Gets the text subtitle param.
  440. /// </summary>
  441. /// <param name="state">The state.</param>
  442. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  443. /// <returns>System.String.</returns>
  444. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  445. {
  446. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  447. GetExtractedAssPath(state, performConversion);
  448. if (string.IsNullOrEmpty(path))
  449. {
  450. return string.Empty;
  451. }
  452. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  453. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  454. path.Replace('\\', '/').Replace(":/", "\\:/"),
  455. Math.Round(seconds).ToString(UsCulture));
  456. }
  457. /// <summary>
  458. /// Gets the extracted ass path.
  459. /// </summary>
  460. /// <param name="state">The state.</param>
  461. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  462. /// <returns>System.String.</returns>
  463. private string GetExtractedAssPath(StreamState state, bool performConversion)
  464. {
  465. var path = FFMpegManager.Instance.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream, ".ass");
  466. if (performConversion)
  467. {
  468. InputType type;
  469. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  470. try
  471. {
  472. var parentPath = Path.GetDirectoryName(path);
  473. Directory.CreateDirectory(parentPath);
  474. // Don't re-encode ass/ssa to ass because ffmpeg ass encoder fails if there's more than one ass rectangle. Affect Anime mostly.
  475. // See https://lists.ffmpeg.org/pipermail/ffmpeg-cvslog/2013-April/063616.html
  476. bool isAssSubtitle = string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase);
  477. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, isAssSubtitle, path, CancellationToken.None);
  478. Task.WaitAll(task);
  479. }
  480. catch
  481. {
  482. return null;
  483. }
  484. }
  485. return path;
  486. }
  487. /// <summary>
  488. /// Gets the converted ass path.
  489. /// </summary>
  490. /// <param name="mediaPath">The media path.</param>
  491. /// <param name="subtitleStream">The subtitle stream.</param>
  492. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  493. /// <returns>System.String.</returns>
  494. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  495. {
  496. var path = FFMpegManager.Instance.GetSubtitleCachePath(mediaPath, subtitleStream, ".ass");
  497. if (performConversion)
  498. {
  499. try
  500. {
  501. var parentPath = Path.GetDirectoryName(path);
  502. Directory.CreateDirectory(parentPath);
  503. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  504. Task.WaitAll(task);
  505. }
  506. catch
  507. {
  508. return null;
  509. }
  510. }
  511. return path;
  512. }
  513. /// <summary>
  514. /// Gets the internal graphical subtitle param.
  515. /// </summary>
  516. /// <param name="state">The state.</param>
  517. /// <param name="outputVideoCodec">The output video codec.</param>
  518. /// <returns>System.String.</returns>
  519. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  520. {
  521. var outputSizeParam = string.Empty;
  522. var request = state.VideoRequest;
  523. // Add resolution params, if specified
  524. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  525. {
  526. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  527. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  528. }
  529. var videoSizeParam = string.Empty;
  530. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  531. {
  532. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  533. }
  534. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  535. state.SubtitleStream.Index,
  536. state.VideoStream.Index,
  537. outputSizeParam,
  538. videoSizeParam);
  539. }
  540. /// <summary>
  541. /// Gets the probe size argument.
  542. /// </summary>
  543. /// <param name="mediaPath">The media path.</param>
  544. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  545. /// <param name="videoType">Type of the video.</param>
  546. /// <param name="isoType">Type of the iso.</param>
  547. /// <returns>System.String.</returns>
  548. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  549. {
  550. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  551. MediaEncoderHelpers.GetInputType(videoType, isoType);
  552. return MediaEncoder.GetProbeSizeArgument(type);
  553. }
  554. /// <summary>
  555. /// Gets the number of audio channels to specify on the command line
  556. /// </summary>
  557. /// <param name="request">The request.</param>
  558. /// <param name="audioStream">The audio stream.</param>
  559. /// <returns>System.Nullable{System.Int32}.</returns>
  560. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  561. {
  562. if (audioStream != null)
  563. {
  564. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  565. {
  566. if (request.AudioCodec.Value == AudioCodecs.Wma)
  567. {
  568. // wmav2 currently only supports two channel output
  569. return 2;
  570. }
  571. }
  572. }
  573. return request.AudioChannels;
  574. }
  575. /// <summary>
  576. /// Determines whether the specified stream is H264.
  577. /// </summary>
  578. /// <param name="stream">The stream.</param>
  579. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  580. protected bool IsH264(MediaStream stream)
  581. {
  582. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  583. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  584. }
  585. /// <summary>
  586. /// Gets the name of the output audio codec
  587. /// </summary>
  588. /// <param name="request">The request.</param>
  589. /// <returns>System.String.</returns>
  590. protected string GetAudioCodec(StreamRequest request)
  591. {
  592. var codec = request.AudioCodec;
  593. if (codec.HasValue)
  594. {
  595. if (codec == AudioCodecs.Aac)
  596. {
  597. return "aac -strict experimental";
  598. }
  599. if (codec == AudioCodecs.Mp3)
  600. {
  601. return "libmp3lame";
  602. }
  603. if (codec == AudioCodecs.Vorbis)
  604. {
  605. return "libvorbis";
  606. }
  607. if (codec == AudioCodecs.Wma)
  608. {
  609. return "wmav2";
  610. }
  611. return codec.ToString().ToLower();
  612. }
  613. return "copy";
  614. }
  615. /// <summary>
  616. /// Gets the name of the output video codec
  617. /// </summary>
  618. /// <param name="request">The request.</param>
  619. /// <returns>System.String.</returns>
  620. protected string GetVideoCodec(VideoStreamRequest request)
  621. {
  622. var codec = request.VideoCodec;
  623. if (codec.HasValue)
  624. {
  625. if (codec == VideoCodecs.H264)
  626. {
  627. return "libx264";
  628. }
  629. if (codec == VideoCodecs.Vpx)
  630. {
  631. return "libvpx";
  632. }
  633. if (codec == VideoCodecs.Wmv)
  634. {
  635. return "msmpeg4";
  636. }
  637. if (codec == VideoCodecs.Theora)
  638. {
  639. return "libtheora";
  640. }
  641. return codec.ToString().ToLower();
  642. }
  643. return "copy";
  644. }
  645. /// <summary>
  646. /// Gets the input argument.
  647. /// </summary>
  648. /// <param name="state">The state.</param>
  649. /// <returns>System.String.</returns>
  650. protected string GetInputArgument(StreamState state)
  651. {
  652. if (state.SendInputOverStandardInput)
  653. {
  654. return "-";
  655. }
  656. var type = InputType.File;
  657. var inputPath = new[] { state.MediaPath };
  658. if (state.IsInputVideo)
  659. {
  660. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  661. {
  662. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  663. }
  664. }
  665. return MediaEncoder.GetInputArgument(inputPath, type);
  666. }
  667. /// <summary>
  668. /// Starts the FFMPEG.
  669. /// </summary>
  670. /// <param name="state">The state.</param>
  671. /// <param name="outputPath">The output path.</param>
  672. /// <returns>Task.</returns>
  673. protected async Task StartFfMpeg(StreamState state, string outputPath)
  674. {
  675. if (!File.Exists(MediaEncoder.EncoderPath))
  676. {
  677. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  678. }
  679. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  680. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  681. {
  682. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  683. }
  684. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  685. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  686. {
  687. commandLineArgs = "-loglevel debug " + commandLineArgs;
  688. }
  689. var process = new Process
  690. {
  691. StartInfo = new ProcessStartInfo
  692. {
  693. CreateNoWindow = true,
  694. UseShellExecute = false,
  695. // Must consume both stdout and stderr or deadlocks may occur
  696. RedirectStandardOutput = true,
  697. RedirectStandardError = true,
  698. FileName = MediaEncoder.EncoderPath,
  699. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  700. Arguments = commandLineArgs,
  701. WindowStyle = ProcessWindowStyle.Hidden,
  702. ErrorDialog = false,
  703. RedirectStandardInput = state.SendInputOverStandardInput
  704. },
  705. EnableRaisingEvents = true
  706. };
  707. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  708. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  709. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  710. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  711. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  712. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  713. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  714. try
  715. {
  716. process.Start();
  717. }
  718. catch (Exception ex)
  719. {
  720. Logger.ErrorException("Error starting ffmpeg", ex);
  721. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  722. state.LogFileStream.Dispose();
  723. throw;
  724. }
  725. if (state.SendInputOverStandardInput)
  726. {
  727. StreamToStandardInput(process, state);
  728. }
  729. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  730. process.BeginOutputReadLine();
  731. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  732. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  733. // Wait for the file to exist before proceeeding
  734. while (!File.Exists(outputPath))
  735. {
  736. await Task.Delay(100).ConfigureAwait(false);
  737. }
  738. // Allow a small amount of time to buffer a little
  739. if (state.IsInputVideo)
  740. {
  741. await Task.Delay(500).ConfigureAwait(false);
  742. }
  743. // This is arbitrary, but add a little buffer time when internet streaming
  744. if (state.IsRemote)
  745. {
  746. await Task.Delay(3000).ConfigureAwait(false);
  747. }
  748. }
  749. private async void StreamToStandardInput(Process process, StreamState state)
  750. {
  751. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  752. try
  753. {
  754. await StreamToStandardInputInternal(process, state).ConfigureAwait(false);
  755. }
  756. catch (OperationCanceledException)
  757. {
  758. Logger.Debug("Stream to standard input closed normally.");
  759. }
  760. catch (Exception ex)
  761. {
  762. Logger.ErrorException("Error writing to standard input", ex);
  763. }
  764. }
  765. private async Task StreamToStandardInputInternal(Process process, StreamState state)
  766. {
  767. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  768. using (var fileStream = FileSystem.GetFileStream(state.MediaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  769. {
  770. await new EndlessStreamCopy().CopyStream(fileStream, process.StandardInput.BaseStream, state.StandardInputCancellationTokenSource.Token).ConfigureAwait(false);
  771. }
  772. }
  773. protected int? GetVideoBitrateParamValue(StreamState state)
  774. {
  775. return state.VideoRequest.VideoBitRate;
  776. }
  777. protected string GetVideoBitrateParam(StreamState state, string videoCodec, bool isHls)
  778. {
  779. var bitrate = GetVideoBitrateParamValue(state);
  780. if (bitrate.HasValue)
  781. {
  782. if (isHls)
  783. {
  784. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  785. }
  786. // With vpx when crf is used, b:v becomes a max rate
  787. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide
  788. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  789. {
  790. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  791. }
  792. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  793. {
  794. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  795. }
  796. return string.Format(" -maxrate {0} -bufsize {1}",
  797. bitrate.Value.ToString(UsCulture),
  798. (bitrate.Value * 2).ToString(UsCulture));
  799. }
  800. return string.Empty;
  801. }
  802. protected int? GetAudioBitrateParam(StreamState state)
  803. {
  804. if (state.Request.AudioBitRate.HasValue)
  805. {
  806. // Make sure we don't request a bitrate higher than the source
  807. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  808. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  809. }
  810. return null;
  811. }
  812. /// <summary>
  813. /// Gets the user agent param.
  814. /// </summary>
  815. /// <param name="path">The path.</param>
  816. /// <returns>System.String.</returns>
  817. private string GetUserAgentParam(string path)
  818. {
  819. var useragent = GetUserAgent(path);
  820. if (!string.IsNullOrEmpty(useragent))
  821. {
  822. return "-user-agent \"" + useragent + "\"";
  823. }
  824. return string.Empty;
  825. }
  826. /// <summary>
  827. /// Gets the user agent.
  828. /// </summary>
  829. /// <param name="path">The path.</param>
  830. /// <returns>System.String.</returns>
  831. protected string GetUserAgent(string path)
  832. {
  833. if (string.IsNullOrEmpty(path))
  834. {
  835. throw new ArgumentNullException("path");
  836. }
  837. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  838. {
  839. return "QuickTime/7.7.4";
  840. }
  841. return string.Empty;
  842. }
  843. /// <summary>
  844. /// Processes the exited.
  845. /// </summary>
  846. /// <param name="process">The process.</param>
  847. /// <param name="state">The state.</param>
  848. protected async void OnFfMpegProcessExited(Process process, StreamState state)
  849. {
  850. if (state.IsoMount != null)
  851. {
  852. state.IsoMount.Dispose();
  853. state.IsoMount = null;
  854. }
  855. if (state.StandardInputCancellationTokenSource != null)
  856. {
  857. state.StandardInputCancellationTokenSource.Cancel();
  858. }
  859. var outputFilePath = GetOutputFilePath(state);
  860. state.LogFileStream.Dispose();
  861. try
  862. {
  863. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  864. }
  865. catch
  866. {
  867. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  868. }
  869. if (!string.IsNullOrEmpty(state.LiveTvStreamId))
  870. {
  871. try
  872. {
  873. await LiveTvManager.CloseLiveStream(state.LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  874. }
  875. catch (Exception ex)
  876. {
  877. Logger.ErrorException("Error closing live tv stream", ex);
  878. }
  879. }
  880. }
  881. protected double? GetFramerateParam(StreamState state)
  882. {
  883. if (state.VideoRequest != null && state.VideoRequest.Framerate.HasValue)
  884. {
  885. return state.VideoRequest.Framerate.Value;
  886. }
  887. if (state.VideoStream != null)
  888. {
  889. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  890. if (contentRate.HasValue && contentRate.Value > 23.976)
  891. {
  892. return 23.976;
  893. }
  894. }
  895. return null;
  896. }
  897. /// <summary>
  898. /// Gets the state.
  899. /// </summary>
  900. /// <param name="request">The request.</param>
  901. /// <param name="cancellationToken">The cancellation token.</param>
  902. /// <returns>StreamState.</returns>
  903. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  904. {
  905. if (request.ThrowDebugError)
  906. {
  907. throw new InvalidOperationException("You asked for a debug error, you got one.");
  908. }
  909. var user = AuthorizationRequestFilterAttribute.GetCurrentUser(Request, UserManager);
  910. if (user != null && !user.Configuration.EnableMediaPlayback)
  911. {
  912. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  913. }
  914. var url = Request.PathInfo;
  915. if (!request.AudioCodec.HasValue)
  916. {
  917. request.AudioCodec = InferAudioCodec(url);
  918. }
  919. var state = new StreamState
  920. {
  921. Request = request,
  922. RequestedUrl = url
  923. };
  924. var item = DtoService.GetItemByDtoId(request.Id);
  925. if (item is ILiveTvRecording)
  926. {
  927. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  928. state.VideoType = VideoType.VideoFile;
  929. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  930. state.PlayableStreamFileNames = new List<string>();
  931. if (!string.IsNullOrEmpty(recording.RecordingInfo.Path) && File.Exists(recording.RecordingInfo.Path))
  932. {
  933. state.MediaPath = recording.RecordingInfo.Path;
  934. state.IsRemote = false;
  935. }
  936. else if (!string.IsNullOrEmpty(recording.RecordingInfo.Url))
  937. {
  938. state.MediaPath = recording.RecordingInfo.Url;
  939. state.IsRemote = true;
  940. }
  941. else
  942. {
  943. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  944. state.LiveTvStreamId = streamInfo.Id;
  945. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  946. {
  947. state.MediaPath = streamInfo.Path;
  948. state.IsRemote = false;
  949. }
  950. else if (!string.IsNullOrEmpty(streamInfo.Url))
  951. {
  952. state.MediaPath = streamInfo.Url;
  953. state.IsRemote = true;
  954. }
  955. }
  956. //state.RunTimeTicks = recording.RunTimeTicks;
  957. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  958. state.SendInputOverStandardInput = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  959. state.AudioSync = "1000";
  960. state.DeInterlace = true;
  961. }
  962. else if (item is LiveTvChannel)
  963. {
  964. var channel = LiveTvManager.GetInternalChannel(request.Id);
  965. state.VideoType = VideoType.VideoFile;
  966. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  967. state.PlayableStreamFileNames = new List<string>();
  968. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  969. state.LiveTvStreamId = streamInfo.Id;
  970. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  971. {
  972. state.MediaPath = streamInfo.Path;
  973. state.IsRemote = false;
  974. }
  975. else if (!string.IsNullOrEmpty(streamInfo.Url))
  976. {
  977. state.MediaPath = streamInfo.Url;
  978. state.IsRemote = true;
  979. }
  980. state.SendInputOverStandardInput = true;
  981. state.ReadInputAtNativeFramerate = true;
  982. state.AudioSync = "1000";
  983. state.DeInterlace = true;
  984. }
  985. else
  986. {
  987. state.MediaPath = item.Path;
  988. state.IsRemote = item.LocationType == LocationType.Remote;
  989. var video = item as Video;
  990. if (video != null)
  991. {
  992. state.IsInputVideo = true;
  993. state.VideoType = video.VideoType;
  994. state.IsoType = video.IsoType;
  995. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  996. ? new List<string>()
  997. : video.PlayableStreamFileNames.ToList();
  998. }
  999. state.RunTimeTicks = item.RunTimeTicks;
  1000. }
  1001. var videoRequest = request as VideoStreamRequest;
  1002. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  1003. {
  1004. ItemId = item.Id
  1005. }).ToList();
  1006. if (videoRequest != null)
  1007. {
  1008. if (!videoRequest.VideoCodec.HasValue)
  1009. {
  1010. videoRequest.VideoCodec = InferVideoCodec(url);
  1011. }
  1012. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1013. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1014. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1015. EnforceResolutionLimit(state, videoRequest);
  1016. }
  1017. else
  1018. {
  1019. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1020. }
  1021. state.HasMediaStreams = mediaStreams.Count > 0;
  1022. return state;
  1023. }
  1024. /// <summary>
  1025. /// Enforces the resolution limit.
  1026. /// </summary>
  1027. /// <param name="state">The state.</param>
  1028. /// <param name="videoRequest">The video request.</param>
  1029. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1030. {
  1031. // If enabled, allow whatever the client asks for
  1032. if (ServerConfigurationManager.Configuration.AllowVideoUpscaling)
  1033. {
  1034. return;
  1035. }
  1036. int? videoWidth = null;
  1037. int? videoHeight = null;
  1038. // Grab the values from the source video, if we have them
  1039. if (state.VideoStream != null)
  1040. {
  1041. videoWidth = state.VideoStream.Width;
  1042. videoHeight = state.VideoStream.Height;
  1043. }
  1044. if (videoRequest.Width.HasValue && videoWidth.HasValue)
  1045. {
  1046. if (videoRequest.Width.Value > videoWidth.Value)
  1047. {
  1048. throw new ArgumentException("Video upscaling has not been enabled by the user");
  1049. }
  1050. }
  1051. if (videoRequest.Height.HasValue && videoHeight.HasValue)
  1052. {
  1053. if (videoRequest.Height.Value > videoHeight.Value)
  1054. {
  1055. throw new ArgumentException("Video upscaling has not been enabled by the user");
  1056. }
  1057. }
  1058. // We don't know the source resolution. Don't allow an exact resolution unless upscaling is allowed
  1059. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1060. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1061. videoRequest.Width = null;
  1062. videoRequest.Height = null;
  1063. }
  1064. protected string GetInputModifier(StreamState state)
  1065. {
  1066. var inputModifier = string.Empty;
  1067. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  1068. inputModifier += " " + probeSize;
  1069. inputModifier = inputModifier.Trim();
  1070. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  1071. inputModifier = inputModifier.Trim();
  1072. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1073. inputModifier = inputModifier.Trim();
  1074. if (state.VideoRequest != null)
  1075. {
  1076. inputModifier += " -fflags genpts";
  1077. }
  1078. if (!string.IsNullOrEmpty(state.InputFormat))
  1079. {
  1080. inputModifier += " -f " + state.InputFormat;
  1081. }
  1082. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  1083. {
  1084. inputModifier += " -vcodec " + state.InputVideoCodec;
  1085. }
  1086. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  1087. {
  1088. inputModifier += " -acodec " + state.InputAudioCodec;
  1089. }
  1090. if (state.ReadInputAtNativeFramerate)
  1091. {
  1092. inputModifier += " -re";
  1093. }
  1094. return inputModifier;
  1095. }
  1096. /// <summary>
  1097. /// Infers the audio codec based on the url
  1098. /// </summary>
  1099. /// <param name="url">The URL.</param>
  1100. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1101. private AudioCodecs? InferAudioCodec(string url)
  1102. {
  1103. var ext = Path.GetExtension(url);
  1104. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1105. {
  1106. return AudioCodecs.Mp3;
  1107. }
  1108. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1109. {
  1110. return AudioCodecs.Aac;
  1111. }
  1112. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1113. {
  1114. return AudioCodecs.Wma;
  1115. }
  1116. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1117. {
  1118. return AudioCodecs.Vorbis;
  1119. }
  1120. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1121. {
  1122. return AudioCodecs.Vorbis;
  1123. }
  1124. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1125. {
  1126. return AudioCodecs.Vorbis;
  1127. }
  1128. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1129. {
  1130. return AudioCodecs.Vorbis;
  1131. }
  1132. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1133. {
  1134. return AudioCodecs.Vorbis;
  1135. }
  1136. return null;
  1137. }
  1138. /// <summary>
  1139. /// Infers the video codec.
  1140. /// </summary>
  1141. /// <param name="url">The URL.</param>
  1142. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1143. private VideoCodecs? InferVideoCodec(string url)
  1144. {
  1145. var ext = Path.GetExtension(url);
  1146. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1147. {
  1148. return VideoCodecs.Wmv;
  1149. }
  1150. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1151. {
  1152. return VideoCodecs.Vpx;
  1153. }
  1154. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1155. {
  1156. return VideoCodecs.Theora;
  1157. }
  1158. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1159. {
  1160. return VideoCodecs.H264;
  1161. }
  1162. return VideoCodecs.Copy;
  1163. }
  1164. }
  1165. }