2
0

BaseStreamingService.cs 57 KB

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