BaseStreamingService.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  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.MediaEncoding;
  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.Library;
  16. using MediaBrowser.Model.LiveTv;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Diagnostics;
  20. using System.Globalization;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. namespace MediaBrowser.Api.Playback
  26. {
  27. /// <summary>
  28. /// Class BaseStreamingService
  29. /// </summary>
  30. public abstract class BaseStreamingService : BaseApiService
  31. {
  32. /// <summary>
  33. /// Gets or sets the application paths.
  34. /// </summary>
  35. /// <value>The application paths.</value>
  36. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  37. /// <summary>
  38. /// Gets or sets the user manager.
  39. /// </summary>
  40. /// <value>The user manager.</value>
  41. protected IUserManager UserManager { get; private set; }
  42. /// <summary>
  43. /// Gets or sets the library manager.
  44. /// </summary>
  45. /// <value>The library manager.</value>
  46. protected ILibraryManager LibraryManager { get; private set; }
  47. /// <summary>
  48. /// Gets or sets the iso manager.
  49. /// </summary>
  50. /// <value>The iso manager.</value>
  51. protected IIsoManager IsoManager { get; private set; }
  52. /// <summary>
  53. /// Gets or sets the media encoder.
  54. /// </summary>
  55. /// <value>The media encoder.</value>
  56. protected IMediaEncoder MediaEncoder { get; private set; }
  57. protected IEncodingManager EncodingManager { get; private set; }
  58. protected IDtoService DtoService { get; private set; }
  59. protected IFileSystem FileSystem { get; private set; }
  60. protected IItemRepository ItemRepository { get; private set; }
  61. protected ILiveTvManager LiveTvManager { get; private set; }
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  64. /// </summary>
  65. /// <param name="serverConfig">The server configuration.</param>
  66. /// <param name="userManager">The user manager.</param>
  67. /// <param name="libraryManager">The library manager.</param>
  68. /// <param name="isoManager">The iso manager.</param>
  69. /// <param name="mediaEncoder">The media encoder.</param>
  70. /// <param name="dtoService">The dto service.</param>
  71. /// <param name="fileSystem">The file system.</param>
  72. /// <param name="itemRepository">The item repository.</param>
  73. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager, IEncodingManager encodingManager)
  74. {
  75. EncodingManager = encodingManager;
  76. LiveTvManager = liveTvManager;
  77. ItemRepository = itemRepository;
  78. FileSystem = fileSystem;
  79. DtoService = dtoService;
  80. ServerConfigurationManager = serverConfig;
  81. UserManager = userManager;
  82. LibraryManager = libraryManager;
  83. IsoManager = isoManager;
  84. MediaEncoder = mediaEncoder;
  85. }
  86. /// <summary>
  87. /// Gets the command line arguments.
  88. /// </summary>
  89. /// <param name="outputPath">The output path.</param>
  90. /// <param name="state">The state.</param>
  91. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  92. /// <returns>System.String.</returns>
  93. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions);
  94. /// <summary>
  95. /// Gets the type of the transcoding job.
  96. /// </summary>
  97. /// <value>The type of the transcoding job.</value>
  98. protected abstract TranscodingJobType TranscodingJobType { get; }
  99. /// <summary>
  100. /// Gets the output file extension.
  101. /// </summary>
  102. /// <param name="state">The state.</param>
  103. /// <returns>System.String.</returns>
  104. protected virtual string GetOutputFileExtension(StreamState state)
  105. {
  106. return Path.GetExtension(state.RequestedUrl);
  107. }
  108. /// <summary>
  109. /// Gets the output file path.
  110. /// </summary>
  111. /// <param name="state">The state.</param>
  112. /// <returns>System.String.</returns>
  113. protected virtual string GetOutputFilePath(StreamState state)
  114. {
  115. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  116. var outputFileExtension = GetOutputFileExtension(state);
  117. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  118. }
  119. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  120. /// <summary>
  121. /// The fast seek offset seconds
  122. /// </summary>
  123. private const int FastSeekOffsetSeconds = 1;
  124. /// <summary>
  125. /// Gets the fast seek command line parameter.
  126. /// </summary>
  127. /// <param name="request">The request.</param>
  128. /// <returns>System.String.</returns>
  129. /// <value>The fast seek command line parameter.</value>
  130. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  131. {
  132. var time = request.StartTimeTicks;
  133. if (time.HasValue)
  134. {
  135. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds;
  136. if (seconds > 0)
  137. {
  138. return string.Format("-ss {0}", seconds.ToString(UsCulture));
  139. }
  140. }
  141. return string.Empty;
  142. }
  143. /// <summary>
  144. /// Gets the slow seek command line parameter.
  145. /// </summary>
  146. /// <param name="request">The request.</param>
  147. /// <returns>System.String.</returns>
  148. /// <value>The slow seek command line parameter.</value>
  149. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  150. {
  151. var time = request.StartTimeTicks;
  152. if (time.HasValue)
  153. {
  154. if (TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds > 0)
  155. {
  156. return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture));
  157. }
  158. }
  159. return string.Empty;
  160. }
  161. /// <summary>
  162. /// Gets the map args.
  163. /// </summary>
  164. /// <param name="state">The state.</param>
  165. /// <returns>System.String.</returns>
  166. protected virtual string GetMapArgs(StreamState state)
  167. {
  168. var args = string.Empty;
  169. if (state.IsRemote || !state.HasMediaStreams)
  170. {
  171. return string.Empty;
  172. }
  173. if (state.VideoStream != null)
  174. {
  175. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  176. }
  177. else
  178. {
  179. args += "-map -0:v";
  180. }
  181. if (state.AudioStream != null)
  182. {
  183. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  184. }
  185. else
  186. {
  187. args += " -map -0:a";
  188. }
  189. if (state.SubtitleStream == null)
  190. {
  191. args += " -map -0:s";
  192. }
  193. return args;
  194. }
  195. /// <summary>
  196. /// Determines which stream will be used for playback
  197. /// </summary>
  198. /// <param name="allStream">All stream.</param>
  199. /// <param name="desiredIndex">Index of the desired.</param>
  200. /// <param name="type">The type.</param>
  201. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  202. /// <returns>MediaStream.</returns>
  203. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  204. {
  205. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  206. if (desiredIndex.HasValue)
  207. {
  208. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  209. if (stream != null)
  210. {
  211. return stream;
  212. }
  213. }
  214. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  215. {
  216. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  217. streams.FirstOrDefault();
  218. }
  219. // Just return the first one
  220. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  221. }
  222. protected EncodingQuality GetQualitySetting()
  223. {
  224. var quality = ServerConfigurationManager.Configuration.MediaEncodingQuality;
  225. if (quality == EncodingQuality.Auto)
  226. {
  227. var cpuCount = Environment.ProcessorCount;
  228. if (cpuCount >= 4)
  229. {
  230. //return EncodingQuality.HighQuality;
  231. }
  232. return EncodingQuality.HighSpeed;
  233. }
  234. return quality;
  235. }
  236. /// <summary>
  237. /// Gets the number of threads.
  238. /// </summary>
  239. /// <returns>System.Int32.</returns>
  240. /// <exception cref="System.Exception">Unrecognized MediaEncodingQuality value.</exception>
  241. protected int GetNumberOfThreads(bool isWebm)
  242. {
  243. // Webm: http://www.webmproject.org/docs/encoder-parameters/
  244. // 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
  245. // for the coefficient data if the encoder selected --token-parts > 0 at encode time.
  246. switch (GetQualitySetting())
  247. {
  248. case EncodingQuality.HighSpeed:
  249. return 2;
  250. case EncodingQuality.HighQuality:
  251. return 2;
  252. case EncodingQuality.MaxQuality:
  253. return isWebm ? 2 : 0;
  254. default:
  255. throw new Exception("Unrecognized MediaEncodingQuality value.");
  256. }
  257. }
  258. /// <summary>
  259. /// Gets the video bitrate to specify on the command line
  260. /// </summary>
  261. /// <param name="state">The state.</param>
  262. /// <param name="videoCodec">The video codec.</param>
  263. /// <returns>System.String.</returns>
  264. protected string GetVideoQualityParam(StreamState state, string videoCodec, bool isHls)
  265. {
  266. var param = string.Empty;
  267. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  268. var qualitySetting = GetQualitySetting();
  269. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  270. {
  271. switch (qualitySetting)
  272. {
  273. case EncodingQuality.HighSpeed:
  274. param = "-preset ultrafast";
  275. break;
  276. case EncodingQuality.HighQuality:
  277. param = "-preset superfast";
  278. break;
  279. case EncodingQuality.MaxQuality:
  280. param = "-preset superfast";
  281. break;
  282. }
  283. if (!isHls)
  284. {
  285. switch (qualitySetting)
  286. {
  287. case EncodingQuality.HighSpeed:
  288. param += " -crf 23";
  289. break;
  290. case EncodingQuality.HighQuality:
  291. param += " -crf 20";
  292. break;
  293. case EncodingQuality.MaxQuality:
  294. param += " -crf 18";
  295. break;
  296. }
  297. }
  298. }
  299. // webm
  300. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  301. {
  302. // http://www.webmproject.org/docs/encoder-parameters/
  303. param = "-speed 16 -quality good -profile:v 0 -slices 8";
  304. if (!hasFixedResolution)
  305. {
  306. switch (qualitySetting)
  307. {
  308. case EncodingQuality.HighSpeed:
  309. param += " -crf 18";
  310. break;
  311. case EncodingQuality.HighQuality:
  312. param += " -crf 10";
  313. break;
  314. case EncodingQuality.MaxQuality:
  315. param += " -crf 4";
  316. break;
  317. }
  318. }
  319. }
  320. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  321. {
  322. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  323. }
  324. // asf/wmv
  325. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  326. {
  327. param = "-qmin 2";
  328. }
  329. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  330. {
  331. param = "-mbd 2";
  332. }
  333. param += GetVideoBitrateParam(state, videoCodec, isHls);
  334. var framerate = GetFramerateParam(state);
  335. if (framerate.HasValue)
  336. {
  337. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  338. }
  339. if (!string.IsNullOrEmpty(state.VideoSync))
  340. {
  341. param += " -vsync " + state.VideoSync;
  342. }
  343. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  344. {
  345. param += " -profile:v " + state.VideoRequest.Profile;
  346. }
  347. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  348. {
  349. param += " -level " + state.VideoRequest.Level;
  350. }
  351. return param;
  352. }
  353. protected string GetAudioFilterParam(StreamState state, bool isHls)
  354. {
  355. var volParam = string.Empty;
  356. var audioSampleRate = string.Empty;
  357. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  358. // Boost volume to 200% when downsampling from 6ch to 2ch
  359. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  360. {
  361. volParam = ",volume=2.000000";
  362. }
  363. if (state.Request.AudioSampleRate.HasValue)
  364. {
  365. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  366. }
  367. var adelay = isHls ? "adelay=1," : string.Empty;
  368. var pts = string.Empty;
  369. if (state.SubtitleStream != null)
  370. {
  371. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  372. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  373. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  374. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  375. {
  376. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  377. pts = string.Format(",asetpts=PTS-{0}/TB",
  378. Math.Round(seconds).ToString(UsCulture));
  379. }
  380. }
  381. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  382. adelay,
  383. audioSampleRate,
  384. volParam,
  385. pts,
  386. state.AudioSync);
  387. }
  388. /// <summary>
  389. /// If we're going to put a fixed size on the command line, this will calculate it
  390. /// </summary>
  391. /// <param name="state">The state.</param>
  392. /// <param name="outputVideoCodec">The output video codec.</param>
  393. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  394. /// <returns>System.String.</returns>
  395. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  396. {
  397. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  398. var assSubtitleParam = string.Empty;
  399. var copyTsParam = string.Empty;
  400. var yadifParam = state.DeInterlace ? "yadif=0:-1:0," : string.Empty;
  401. var request = state.VideoRequest;
  402. if (state.SubtitleStream != null)
  403. {
  404. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  405. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  406. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  407. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  408. {
  409. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  410. copyTsParam = " -copyts";
  411. }
  412. }
  413. // If fixed dimensions were supplied
  414. if (request.Width.HasValue && request.Height.HasValue)
  415. {
  416. var widthParam = request.Width.Value.ToString(UsCulture);
  417. var heightParam = request.Height.Value.ToString(UsCulture);
  418. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  419. }
  420. // If Max dimensions were supplied
  421. //this makes my brain hurt. For width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size
  422. if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  423. {
  424. var MaxwidthParam = request.MaxWidth.Value.ToString(UsCulture);
  425. var MaxheightParam = request.MaxHeight.Value.ToString(UsCulture);
  426. return string.Format("{4} -vf \"{0}scale=trunc(min(iw\\,{1})/2)*2:trunc(min((iw/dar)\\,{2})/2)*2{3}\"", yadifParam, MaxwidthParam, MaxheightParam, assSubtitleParam, copyTsParam);
  427. }
  428. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  429. // If a fixed width was requested
  430. if (request.Width.HasValue)
  431. {
  432. var widthParam = request.Width.Value.ToString(UsCulture);
  433. return isH264Output ?
  434. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  435. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam);
  436. }
  437. // If a fixed height was requested
  438. if (request.Height.HasValue)
  439. {
  440. var heightParam = request.Height.Value.ToString(UsCulture);
  441. return isH264Output ?
  442. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  443. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam);
  444. }
  445. // If a max width was requested
  446. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  447. {
  448. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  449. return isH264Output ?
  450. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  451. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  452. }
  453. // If a max height was requested
  454. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  455. {
  456. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  457. return isH264Output ?
  458. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  459. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  460. }
  461. if (state.VideoStream == null)
  462. {
  463. // No way to figure this out
  464. return string.Empty;
  465. }
  466. // Need to perform calculations manually
  467. // Try to account for bad media info
  468. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  469. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  470. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  471. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  472. if (isH264Output)
  473. {
  474. var widthParam = outputSize.Width.ToString(UsCulture);
  475. var heightParam = outputSize.Height.ToString(UsCulture);
  476. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  477. }
  478. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  479. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  480. }
  481. /// <summary>
  482. /// Gets the text subtitle param.
  483. /// </summary>
  484. /// <param name="state">The state.</param>
  485. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  486. /// <returns>System.String.</returns>
  487. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  488. {
  489. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  490. GetExtractedAssPath(state, performConversion);
  491. if (string.IsNullOrEmpty(path))
  492. {
  493. return string.Empty;
  494. }
  495. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  496. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  497. path.Replace('\\', '/').Replace(":/", "\\:/"),
  498. Math.Round(seconds).ToString(UsCulture));
  499. }
  500. /// <summary>
  501. /// Gets the extracted ass path.
  502. /// </summary>
  503. /// <param name="state">The state.</param>
  504. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  505. /// <returns>System.String.</returns>
  506. private string GetExtractedAssPath(StreamState state, bool performConversion)
  507. {
  508. var path = EncodingManager.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream.Index, ".ass");
  509. if (performConversion)
  510. {
  511. InputType type;
  512. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  513. try
  514. {
  515. var parentPath = Path.GetDirectoryName(path);
  516. Directory.CreateDirectory(parentPath);
  517. // Don't re-encode ass/ssa to ass because ffmpeg ass encoder fails if there's more than one ass rectangle. Affect Anime mostly.
  518. // See https://lists.ffmpeg.org/pipermail/ffmpeg-cvslog/2013-April/063616.html
  519. var isAssSubtitle = string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase);
  520. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, isAssSubtitle, path, CancellationToken.None);
  521. Task.WaitAll(task);
  522. }
  523. catch
  524. {
  525. return null;
  526. }
  527. }
  528. return path;
  529. }
  530. /// <summary>
  531. /// Gets the converted ass path.
  532. /// </summary>
  533. /// <param name="mediaPath">The media path.</param>
  534. /// <param name="subtitleStream">The subtitle stream.</param>
  535. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  536. /// <returns>System.String.</returns>
  537. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  538. {
  539. var path = EncodingManager.GetSubtitleCachePath(subtitleStream.Path, ".ass");
  540. if (performConversion)
  541. {
  542. try
  543. {
  544. var parentPath = Path.GetDirectoryName(path);
  545. Directory.CreateDirectory(parentPath);
  546. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  547. Task.WaitAll(task);
  548. }
  549. catch
  550. {
  551. return null;
  552. }
  553. }
  554. return path;
  555. }
  556. /// <summary>
  557. /// Gets the internal graphical subtitle param.
  558. /// </summary>
  559. /// <param name="state">The state.</param>
  560. /// <param name="outputVideoCodec">The output video codec.</param>
  561. /// <returns>System.String.</returns>
  562. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  563. {
  564. var outputSizeParam = string.Empty;
  565. var request = state.VideoRequest;
  566. // Add resolution params, if specified
  567. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  568. {
  569. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  570. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  571. }
  572. var videoSizeParam = string.Empty;
  573. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  574. {
  575. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  576. }
  577. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  578. state.SubtitleStream.Index,
  579. state.VideoStream.Index,
  580. outputSizeParam,
  581. videoSizeParam);
  582. }
  583. /// <summary>
  584. /// Gets the probe size argument.
  585. /// </summary>
  586. /// <param name="mediaPath">The media path.</param>
  587. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  588. /// <param name="videoType">Type of the video.</param>
  589. /// <param name="isoType">Type of the iso.</param>
  590. /// <returns>System.String.</returns>
  591. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  592. {
  593. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  594. MediaEncoderHelpers.GetInputType(videoType, isoType);
  595. return MediaEncoder.GetProbeSizeArgument(type);
  596. }
  597. /// <summary>
  598. /// Gets the number of audio channels to specify on the command line
  599. /// </summary>
  600. /// <param name="request">The request.</param>
  601. /// <param name="audioStream">The audio stream.</param>
  602. /// <returns>System.Nullable{System.Int32}.</returns>
  603. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  604. {
  605. if (audioStream != null)
  606. {
  607. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  608. {
  609. if (request.AudioCodec.Value == AudioCodecs.Wma)
  610. {
  611. // wmav2 currently only supports two channel output
  612. return 2;
  613. }
  614. }
  615. }
  616. return request.AudioChannels;
  617. }
  618. /// <summary>
  619. /// Determines whether the specified stream is H264.
  620. /// </summary>
  621. /// <param name="stream">The stream.</param>
  622. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  623. protected bool IsH264(MediaStream stream)
  624. {
  625. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  626. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  627. }
  628. /// <summary>
  629. /// Gets the name of the output audio codec
  630. /// </summary>
  631. /// <param name="request">The request.</param>
  632. /// <returns>System.String.</returns>
  633. protected string GetAudioCodec(StreamRequest request)
  634. {
  635. var codec = request.AudioCodec;
  636. if (codec.HasValue)
  637. {
  638. if (codec == AudioCodecs.Aac)
  639. {
  640. return "aac -strict experimental";
  641. }
  642. if (codec == AudioCodecs.Mp3)
  643. {
  644. return "libmp3lame";
  645. }
  646. if (codec == AudioCodecs.Vorbis)
  647. {
  648. return "libvorbis";
  649. }
  650. if (codec == AudioCodecs.Wma)
  651. {
  652. return "wmav2";
  653. }
  654. return codec.ToString().ToLower();
  655. }
  656. return "copy";
  657. }
  658. /// <summary>
  659. /// Gets the name of the output video codec
  660. /// </summary>
  661. /// <param name="request">The request.</param>
  662. /// <returns>System.String.</returns>
  663. protected string GetVideoCodec(VideoStreamRequest request)
  664. {
  665. var codec = request.VideoCodec;
  666. if (codec.HasValue)
  667. {
  668. if (codec == VideoCodecs.H264)
  669. {
  670. return "libx264";
  671. }
  672. if (codec == VideoCodecs.Vpx)
  673. {
  674. return "libvpx";
  675. }
  676. if (codec == VideoCodecs.Wmv)
  677. {
  678. return "msmpeg4";
  679. }
  680. if (codec == VideoCodecs.Theora)
  681. {
  682. return "libtheora";
  683. }
  684. return codec.ToString().ToLower();
  685. }
  686. return "copy";
  687. }
  688. /// <summary>
  689. /// Gets the input argument.
  690. /// </summary>
  691. /// <param name="state">The state.</param>
  692. /// <returns>System.String.</returns>
  693. protected string GetInputArgument(StreamState state)
  694. {
  695. if (state.SendInputOverStandardInput)
  696. {
  697. return "-";
  698. }
  699. var type = InputType.File;
  700. var inputPath = new[] { state.MediaPath };
  701. if (state.IsInputVideo)
  702. {
  703. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  704. {
  705. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  706. }
  707. }
  708. return MediaEncoder.GetInputArgument(inputPath, type);
  709. }
  710. /// <summary>
  711. /// Starts the FFMPEG.
  712. /// </summary>
  713. /// <param name="state">The state.</param>
  714. /// <param name="outputPath">The output path.</param>
  715. /// <returns>Task.</returns>
  716. protected async Task StartFfMpeg(StreamState state, string outputPath)
  717. {
  718. if (!File.Exists(MediaEncoder.EncoderPath))
  719. {
  720. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  721. }
  722. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  723. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  724. {
  725. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  726. }
  727. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  728. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  729. {
  730. commandLineArgs = "-loglevel debug " + commandLineArgs;
  731. }
  732. var process = new Process
  733. {
  734. StartInfo = new ProcessStartInfo
  735. {
  736. CreateNoWindow = true,
  737. UseShellExecute = false,
  738. // Must consume both stdout and stderr or deadlocks may occur
  739. RedirectStandardOutput = true,
  740. RedirectStandardError = true,
  741. FileName = MediaEncoder.EncoderPath,
  742. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  743. Arguments = commandLineArgs,
  744. WindowStyle = ProcessWindowStyle.Hidden,
  745. ErrorDialog = false,
  746. RedirectStandardInput = state.SendInputOverStandardInput
  747. },
  748. EnableRaisingEvents = true
  749. };
  750. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  751. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  752. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  753. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  754. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  755. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  756. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  757. try
  758. {
  759. process.Start();
  760. }
  761. catch (Exception ex)
  762. {
  763. Logger.ErrorException("Error starting ffmpeg", ex);
  764. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  765. state.LogFileStream.Dispose();
  766. throw;
  767. }
  768. if (state.SendInputOverStandardInput)
  769. {
  770. StreamToStandardInput(process, state);
  771. }
  772. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  773. process.BeginOutputReadLine();
  774. #pragma warning disable 4014
  775. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  776. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  777. #pragma warning restore 4014
  778. // Wait for the file to exist before proceeeding
  779. while (!File.Exists(outputPath))
  780. {
  781. await Task.Delay(100).ConfigureAwait(false);
  782. }
  783. // Allow a small amount of time to buffer a little
  784. if (state.IsInputVideo)
  785. {
  786. await Task.Delay(500).ConfigureAwait(false);
  787. }
  788. // This is arbitrary, but add a little buffer time when internet streaming
  789. if (state.IsRemote)
  790. {
  791. await Task.Delay(3000).ConfigureAwait(false);
  792. }
  793. }
  794. private async void StreamToStandardInput(Process process, StreamState state)
  795. {
  796. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  797. try
  798. {
  799. await StreamToStandardInputInternal(process, state).ConfigureAwait(false);
  800. }
  801. catch (OperationCanceledException)
  802. {
  803. Logger.Debug("Stream to standard input closed normally.");
  804. }
  805. catch (Exception ex)
  806. {
  807. Logger.ErrorException("Error writing to standard input", ex);
  808. }
  809. }
  810. private async Task StreamToStandardInputInternal(Process process, StreamState state)
  811. {
  812. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  813. using (var fileStream = FileSystem.GetFileStream(state.MediaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  814. {
  815. await new EndlessStreamCopy().CopyStream(fileStream, process.StandardInput.BaseStream, state.StandardInputCancellationTokenSource.Token).ConfigureAwait(false);
  816. }
  817. }
  818. protected int? GetVideoBitrateParamValue(StreamState state)
  819. {
  820. var bitrate = state.VideoRequest.VideoBitRate;
  821. if (state.VideoStream != null)
  822. {
  823. var isUpscaling = false;
  824. if (state.VideoRequest.Height.HasValue && state.VideoStream.Height.HasValue &&
  825. state.VideoRequest.Height.Value > state.VideoStream.Height.Value)
  826. {
  827. isUpscaling = true;
  828. }
  829. if (state.VideoRequest.Width.HasValue && state.VideoStream.Width.HasValue &&
  830. state.VideoRequest.Width.Value > state.VideoStream.Width.Value)
  831. {
  832. isUpscaling = true;
  833. }
  834. // Don't allow bitrate increases unless upscaling
  835. if (!isUpscaling)
  836. {
  837. if (bitrate.HasValue && state.VideoStream.BitRate.HasValue)
  838. {
  839. bitrate = Math.Min(bitrate.Value, state.VideoStream.BitRate.Value);
  840. }
  841. }
  842. }
  843. return bitrate;
  844. }
  845. protected string GetVideoBitrateParam(StreamState state, string videoCodec, bool isHls)
  846. {
  847. var bitrate = GetVideoBitrateParamValue(state);
  848. if (bitrate.HasValue)
  849. {
  850. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  851. if (isHls)
  852. {
  853. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  854. }
  855. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  856. {
  857. if (hasFixedResolution)
  858. {
  859. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  860. }
  861. // With vpx when crf is used, b:v becomes a max rate
  862. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide
  863. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  864. //return string.Format(" -minrate:v ({0}*.95) -maxrate:v ({0}*1.05) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  865. }
  866. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  867. {
  868. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  869. }
  870. // H264
  871. if (hasFixedResolution)
  872. {
  873. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  874. }
  875. return string.Format(" -maxrate {0} -bufsize {1}",
  876. bitrate.Value.ToString(UsCulture),
  877. (bitrate.Value * 2).ToString(UsCulture));
  878. }
  879. return string.Empty;
  880. }
  881. protected int? GetAudioBitrateParam(StreamState state)
  882. {
  883. if (state.Request.AudioBitRate.HasValue)
  884. {
  885. // Make sure we don't request a bitrate higher than the source
  886. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  887. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  888. }
  889. return null;
  890. }
  891. /// <summary>
  892. /// Gets the user agent param.
  893. /// </summary>
  894. /// <param name="path">The path.</param>
  895. /// <returns>System.String.</returns>
  896. private string GetUserAgentParam(string path)
  897. {
  898. var useragent = GetUserAgent(path);
  899. if (!string.IsNullOrEmpty(useragent))
  900. {
  901. return "-user-agent \"" + useragent + "\"";
  902. }
  903. return string.Empty;
  904. }
  905. /// <summary>
  906. /// Gets the user agent.
  907. /// </summary>
  908. /// <param name="path">The path.</param>
  909. /// <returns>System.String.</returns>
  910. protected string GetUserAgent(string path)
  911. {
  912. if (string.IsNullOrEmpty(path))
  913. {
  914. throw new ArgumentNullException("path");
  915. }
  916. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  917. {
  918. return "QuickTime/7.7.4";
  919. }
  920. return string.Empty;
  921. }
  922. /// <summary>
  923. /// Processes the exited.
  924. /// </summary>
  925. /// <param name="process">The process.</param>
  926. /// <param name="state">The state.</param>
  927. protected async void OnFfMpegProcessExited(Process process, StreamState state)
  928. {
  929. if (state.IsoMount != null)
  930. {
  931. state.IsoMount.Dispose();
  932. state.IsoMount = null;
  933. }
  934. if (state.StandardInputCancellationTokenSource != null)
  935. {
  936. state.StandardInputCancellationTokenSource.Cancel();
  937. }
  938. var outputFilePath = GetOutputFilePath(state);
  939. state.LogFileStream.Dispose();
  940. try
  941. {
  942. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  943. }
  944. catch
  945. {
  946. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  947. }
  948. if (!string.IsNullOrEmpty(state.LiveTvStreamId))
  949. {
  950. try
  951. {
  952. await LiveTvManager.CloseLiveStream(state.LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  953. }
  954. catch (Exception ex)
  955. {
  956. Logger.ErrorException("Error closing live tv stream", ex);
  957. }
  958. }
  959. }
  960. protected double? GetFramerateParam(StreamState state)
  961. {
  962. if (state.VideoRequest != null && state.VideoRequest.Framerate.HasValue)
  963. {
  964. return state.VideoRequest.Framerate.Value;
  965. }
  966. if (state.VideoStream != null)
  967. {
  968. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  969. if (contentRate.HasValue && contentRate.Value > 23.976)
  970. {
  971. return 23.976;
  972. }
  973. }
  974. return null;
  975. }
  976. /// <summary>
  977. /// Parses the parameters.
  978. /// </summary>
  979. /// <param name="request">The request.</param>
  980. private void ParseParams(StreamRequest request)
  981. {
  982. var vals = request.Params.Split(';');
  983. var videoRequest = request as VideoStreamRequest;
  984. for (var i = 0; i < vals.Length; i++)
  985. {
  986. var val = vals[i];
  987. if (string.IsNullOrWhiteSpace(val))
  988. {
  989. continue;
  990. }
  991. if (i == 0)
  992. {
  993. request.DeviceId = val;
  994. }
  995. else if (i == 1)
  996. {
  997. if (videoRequest != null)
  998. {
  999. videoRequest.VideoCodec = (VideoCodecs)Enum.Parse(typeof(VideoCodecs), val, true);
  1000. }
  1001. }
  1002. else if (i == 2)
  1003. {
  1004. request.AudioCodec = (AudioCodecs)Enum.Parse(typeof(AudioCodecs), val, true);
  1005. }
  1006. else if (i == 3)
  1007. {
  1008. if (videoRequest != null)
  1009. {
  1010. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  1011. }
  1012. }
  1013. else if (i == 4)
  1014. {
  1015. if (videoRequest != null)
  1016. {
  1017. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  1018. }
  1019. }
  1020. else if (i == 5)
  1021. {
  1022. if (videoRequest != null)
  1023. {
  1024. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  1025. }
  1026. }
  1027. else if (i == 6)
  1028. {
  1029. request.AudioBitRate = int.Parse(val, UsCulture);
  1030. }
  1031. else if (i == 7)
  1032. {
  1033. request.AudioChannels = int.Parse(val, UsCulture);
  1034. }
  1035. else if (i == 8)
  1036. {
  1037. if (videoRequest != null)
  1038. {
  1039. request.StartTimeTicks = long.Parse(val, UsCulture);
  1040. }
  1041. }
  1042. else if (i == 9)
  1043. {
  1044. if (videoRequest != null)
  1045. {
  1046. videoRequest.Profile = val;
  1047. }
  1048. }
  1049. else if (i == 10)
  1050. {
  1051. if (videoRequest != null)
  1052. {
  1053. videoRequest.Level = val;
  1054. }
  1055. }
  1056. }
  1057. }
  1058. /// <summary>
  1059. /// Gets the state.
  1060. /// </summary>
  1061. /// <param name="request">The request.</param>
  1062. /// <param name="cancellationToken">The cancellation token.</param>
  1063. /// <returns>StreamState.</returns>
  1064. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  1065. {
  1066. if (!string.IsNullOrWhiteSpace(request.Params))
  1067. {
  1068. ParseParams(request);
  1069. }
  1070. if (request.ThrowDebugError)
  1071. {
  1072. throw new InvalidOperationException("You asked for a debug error, you got one.");
  1073. }
  1074. var user = AuthorizationRequestFilterAttribute.GetCurrentUser(Request, UserManager);
  1075. var url = Request.PathInfo;
  1076. if (!request.AudioCodec.HasValue)
  1077. {
  1078. request.AudioCodec = InferAudioCodec(url);
  1079. }
  1080. var state = new StreamState
  1081. {
  1082. Request = request,
  1083. RequestedUrl = url
  1084. };
  1085. var item = DtoService.GetItemByDtoId(request.Id);
  1086. if (user != null && item.GetPlayAccess(user) != PlayAccess.Full)
  1087. {
  1088. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  1089. }
  1090. if (item is ILiveTvRecording)
  1091. {
  1092. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  1093. state.VideoType = VideoType.VideoFile;
  1094. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1095. state.PlayableStreamFileNames = new List<string>();
  1096. if (!string.IsNullOrEmpty(recording.RecordingInfo.Path) && File.Exists(recording.RecordingInfo.Path))
  1097. {
  1098. state.MediaPath = recording.RecordingInfo.Path;
  1099. state.IsRemote = false;
  1100. }
  1101. else if (!string.IsNullOrEmpty(recording.RecordingInfo.Url))
  1102. {
  1103. state.MediaPath = recording.RecordingInfo.Url;
  1104. state.IsRemote = true;
  1105. }
  1106. else
  1107. {
  1108. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  1109. state.LiveTvStreamId = streamInfo.Id;
  1110. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  1111. {
  1112. state.MediaPath = streamInfo.Path;
  1113. state.IsRemote = false;
  1114. }
  1115. else if (!string.IsNullOrEmpty(streamInfo.Url))
  1116. {
  1117. state.MediaPath = streamInfo.Url;
  1118. state.IsRemote = true;
  1119. }
  1120. }
  1121. //state.RunTimeTicks = recording.RunTimeTicks;
  1122. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  1123. state.SendInputOverStandardInput = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  1124. state.AudioSync = "1000";
  1125. state.DeInterlace = true;
  1126. }
  1127. else if (item is LiveTvChannel)
  1128. {
  1129. var channel = LiveTvManager.GetInternalChannel(request.Id);
  1130. state.VideoType = VideoType.VideoFile;
  1131. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1132. state.PlayableStreamFileNames = new List<string>();
  1133. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  1134. state.LiveTvStreamId = streamInfo.Id;
  1135. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  1136. {
  1137. state.MediaPath = streamInfo.Path;
  1138. state.IsRemote = false;
  1139. }
  1140. else if (!string.IsNullOrEmpty(streamInfo.Url))
  1141. {
  1142. state.MediaPath = streamInfo.Url;
  1143. state.IsRemote = true;
  1144. }
  1145. state.SendInputOverStandardInput = true;
  1146. state.ReadInputAtNativeFramerate = true;
  1147. state.AudioSync = "1000";
  1148. state.DeInterlace = true;
  1149. }
  1150. else
  1151. {
  1152. state.MediaPath = item.Path;
  1153. state.IsRemote = item.LocationType == LocationType.Remote;
  1154. var video = item as Video;
  1155. if (video != null)
  1156. {
  1157. state.IsInputVideo = true;
  1158. state.VideoType = video.VideoType;
  1159. state.IsoType = video.IsoType;
  1160. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  1161. ? new List<string>()
  1162. : video.PlayableStreamFileNames.ToList();
  1163. }
  1164. state.RunTimeTicks = item.RunTimeTicks;
  1165. }
  1166. var videoRequest = request as VideoStreamRequest;
  1167. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  1168. {
  1169. ItemId = item.Id
  1170. }).ToList();
  1171. if (videoRequest != null)
  1172. {
  1173. if (!videoRequest.VideoCodec.HasValue)
  1174. {
  1175. videoRequest.VideoCodec = InferVideoCodec(url);
  1176. }
  1177. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1178. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1179. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1180. EnforceResolutionLimit(state, videoRequest);
  1181. }
  1182. else
  1183. {
  1184. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1185. }
  1186. state.HasMediaStreams = mediaStreams.Count > 0;
  1187. state.SegmentLength = state.ReadInputAtNativeFramerate ? 3 : 10;
  1188. state.HlsListSize = state.ReadInputAtNativeFramerate ? 20 : 1440;
  1189. return state;
  1190. }
  1191. /// <summary>
  1192. /// Enforces the resolution limit.
  1193. /// </summary>
  1194. /// <param name="state">The state.</param>
  1195. /// <param name="videoRequest">The video request.</param>
  1196. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1197. {
  1198. // If enabled, allow whatever the client asks for
  1199. if (ServerConfigurationManager.Configuration.AllowVideoUpscaling)
  1200. {
  1201. return;
  1202. }
  1203. // Switch the incoming params to be ceilings rather than fixed values
  1204. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1205. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1206. videoRequest.Width = null;
  1207. videoRequest.Height = null;
  1208. }
  1209. protected string GetInputModifier(StreamState state)
  1210. {
  1211. var inputModifier = string.Empty;
  1212. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  1213. inputModifier += " " + probeSize;
  1214. inputModifier = inputModifier.Trim();
  1215. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  1216. inputModifier = inputModifier.Trim();
  1217. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1218. inputModifier = inputModifier.Trim();
  1219. if (state.VideoRequest != null)
  1220. {
  1221. inputModifier += " -fflags genpts";
  1222. }
  1223. if (!string.IsNullOrEmpty(state.InputFormat))
  1224. {
  1225. inputModifier += " -f " + state.InputFormat;
  1226. }
  1227. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  1228. {
  1229. inputModifier += " -vcodec " + state.InputVideoCodec;
  1230. }
  1231. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  1232. {
  1233. inputModifier += " -acodec " + state.InputAudioCodec;
  1234. }
  1235. if (state.ReadInputAtNativeFramerate)
  1236. {
  1237. inputModifier += " -re";
  1238. }
  1239. return inputModifier;
  1240. }
  1241. /// <summary>
  1242. /// Infers the audio codec based on the url
  1243. /// </summary>
  1244. /// <param name="url">The URL.</param>
  1245. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1246. private AudioCodecs? InferAudioCodec(string url)
  1247. {
  1248. var ext = Path.GetExtension(url);
  1249. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1250. {
  1251. return AudioCodecs.Mp3;
  1252. }
  1253. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1254. {
  1255. return AudioCodecs.Aac;
  1256. }
  1257. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1258. {
  1259. return AudioCodecs.Wma;
  1260. }
  1261. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1262. {
  1263. return AudioCodecs.Vorbis;
  1264. }
  1265. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1266. {
  1267. return AudioCodecs.Vorbis;
  1268. }
  1269. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1270. {
  1271. return AudioCodecs.Vorbis;
  1272. }
  1273. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1274. {
  1275. return AudioCodecs.Vorbis;
  1276. }
  1277. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1278. {
  1279. return AudioCodecs.Vorbis;
  1280. }
  1281. return null;
  1282. }
  1283. /// <summary>
  1284. /// Infers the video codec.
  1285. /// </summary>
  1286. /// <param name="url">The URL.</param>
  1287. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1288. private VideoCodecs? InferVideoCodec(string url)
  1289. {
  1290. var ext = Path.GetExtension(url);
  1291. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1292. {
  1293. return VideoCodecs.Wmv;
  1294. }
  1295. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1296. {
  1297. return VideoCodecs.Vpx;
  1298. }
  1299. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1300. {
  1301. return VideoCodecs.Theora;
  1302. }
  1303. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1304. {
  1305. return VideoCodecs.H264;
  1306. }
  1307. return VideoCodecs.Copy;
  1308. }
  1309. }
  1310. }