BaseStreamingService.cs 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Dlna;
  5. using MediaBrowser.Controller.Dto;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Controller.MediaEncoding;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.Dlna;
  13. using MediaBrowser.Model.Drawing;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Library;
  17. using MediaBrowser.Model.LiveTv;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Diagnostics;
  21. using System.Globalization;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Text;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. namespace MediaBrowser.Api.Playback
  28. {
  29. /// <summary>
  30. /// Class BaseStreamingService
  31. /// </summary>
  32. public abstract class BaseStreamingService : BaseApiService
  33. {
  34. /// <summary>
  35. /// Gets or sets the application paths.
  36. /// </summary>
  37. /// <value>The application paths.</value>
  38. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  39. /// <summary>
  40. /// Gets or sets the user manager.
  41. /// </summary>
  42. /// <value>The user manager.</value>
  43. protected IUserManager UserManager { get; private set; }
  44. /// <summary>
  45. /// Gets or sets the library manager.
  46. /// </summary>
  47. /// <value>The library manager.</value>
  48. protected ILibraryManager LibraryManager { get; private set; }
  49. /// <summary>
  50. /// Gets or sets the iso manager.
  51. /// </summary>
  52. /// <value>The iso manager.</value>
  53. protected IIsoManager IsoManager { get; private set; }
  54. /// <summary>
  55. /// Gets or sets the media encoder.
  56. /// </summary>
  57. /// <value>The media encoder.</value>
  58. protected IMediaEncoder MediaEncoder { get; private set; }
  59. protected IEncodingManager EncodingManager { get; private set; }
  60. protected IDtoService DtoService { get; private set; }
  61. protected IFileSystem FileSystem { get; private set; }
  62. protected IItemRepository ItemRepository { get; private set; }
  63. protected ILiveTvManager LiveTvManager { get; private set; }
  64. protected IDlnaManager DlnaManager { get; private set; }
  65. /// <summary>
  66. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  67. /// </summary>
  68. /// <param name="serverConfig">The server configuration.</param>
  69. /// <param name="userManager">The user manager.</param>
  70. /// <param name="libraryManager">The library manager.</param>
  71. /// <param name="isoManager">The iso manager.</param>
  72. /// <param name="mediaEncoder">The media encoder.</param>
  73. /// <param name="dtoService">The dto service.</param>
  74. /// <param name="fileSystem">The file system.</param>
  75. /// <param name="itemRepository">The item repository.</param>
  76. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager, IEncodingManager encodingManager, IDlnaManager dlnaManager)
  77. {
  78. DlnaManager = dlnaManager;
  79. EncodingManager = encodingManager;
  80. LiveTvManager = liveTvManager;
  81. ItemRepository = itemRepository;
  82. FileSystem = fileSystem;
  83. DtoService = dtoService;
  84. ServerConfigurationManager = serverConfig;
  85. UserManager = userManager;
  86. LibraryManager = libraryManager;
  87. IsoManager = isoManager;
  88. MediaEncoder = mediaEncoder;
  89. }
  90. /// <summary>
  91. /// Gets the command line arguments.
  92. /// </summary>
  93. /// <param name="outputPath">The output path.</param>
  94. /// <param name="state">The state.</param>
  95. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  96. /// <returns>System.String.</returns>
  97. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions);
  98. /// <summary>
  99. /// Gets the type of the transcoding job.
  100. /// </summary>
  101. /// <value>The type of the transcoding job.</value>
  102. protected abstract TranscodingJobType TranscodingJobType { get; }
  103. /// <summary>
  104. /// Gets the output file extension.
  105. /// </summary>
  106. /// <param name="state">The state.</param>
  107. /// <returns>System.String.</returns>
  108. protected virtual string GetOutputFileExtension(StreamState state)
  109. {
  110. return Path.GetExtension(state.RequestedUrl);
  111. }
  112. /// <summary>
  113. /// Gets the output file path.
  114. /// </summary>
  115. /// <param name="state">The state.</param>
  116. /// <returns>System.String.</returns>
  117. protected virtual string GetOutputFilePath(StreamState state)
  118. {
  119. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  120. var outputFileExtension = GetOutputFileExtension(state);
  121. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  122. }
  123. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  124. /// <summary>
  125. /// The fast seek offset seconds
  126. /// </summary>
  127. private const int FastSeekOffsetSeconds = 1;
  128. /// <summary>
  129. /// Gets the fast seek command line parameter.
  130. /// </summary>
  131. /// <param name="request">The request.</param>
  132. /// <returns>System.String.</returns>
  133. /// <value>The fast seek command line parameter.</value>
  134. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  135. {
  136. var time = request.StartTimeTicks;
  137. if (time.HasValue)
  138. {
  139. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds;
  140. if (seconds > 0)
  141. {
  142. return string.Format("-ss {0}", seconds.ToString(UsCulture));
  143. }
  144. }
  145. return string.Empty;
  146. }
  147. /// <summary>
  148. /// Gets the slow seek command line parameter.
  149. /// </summary>
  150. /// <param name="request">The request.</param>
  151. /// <returns>System.String.</returns>
  152. /// <value>The slow seek command line parameter.</value>
  153. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  154. {
  155. return string.Empty;
  156. }
  157. /// <summary>
  158. /// Gets the map args.
  159. /// </summary>
  160. /// <param name="state">The state.</param>
  161. /// <returns>System.String.</returns>
  162. protected virtual string GetMapArgs(StreamState state)
  163. {
  164. var args = string.Empty;
  165. if (!state.HasMediaStreams)
  166. {
  167. return state.IsInputVideo ? "-sn" : string.Empty;
  168. }
  169. if (state.VideoStream != null)
  170. {
  171. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  172. }
  173. else
  174. {
  175. args += "-map -0:v";
  176. }
  177. if (state.AudioStream != null)
  178. {
  179. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  180. }
  181. else
  182. {
  183. args += " -map -0:a";
  184. }
  185. if (state.SubtitleStream == null)
  186. {
  187. args += " -map -0:s";
  188. }
  189. return args;
  190. }
  191. /// <summary>
  192. /// Determines which stream will be used for playback
  193. /// </summary>
  194. /// <param name="allStream">All stream.</param>
  195. /// <param name="desiredIndex">Index of the desired.</param>
  196. /// <param name="type">The type.</param>
  197. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  198. /// <returns>MediaStream.</returns>
  199. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  200. {
  201. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  202. if (desiredIndex.HasValue)
  203. {
  204. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  205. if (stream != null)
  206. {
  207. return stream;
  208. }
  209. }
  210. if (type == MediaStreamType.Video)
  211. {
  212. streams = streams.Where(i => !string.Equals(i.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)).ToList();
  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(StreamState state, bool isWebm)
  242. {
  243. // Use more when this is true. -re will keep cpu usage under control
  244. if (state.ReadInputAtNativeFramerate)
  245. {
  246. if (isWebm)
  247. {
  248. return Math.Max(Environment.ProcessorCount - 1, 2);
  249. }
  250. return 0;
  251. }
  252. // Webm: http://www.webmproject.org/docs/encoder-parameters/
  253. // 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
  254. // for the coefficient data if the encoder selected --token-parts > 0 at encode time.
  255. switch (GetQualitySetting())
  256. {
  257. case EncodingQuality.HighSpeed:
  258. return 2;
  259. case EncodingQuality.HighQuality:
  260. return 2;
  261. case EncodingQuality.MaxQuality:
  262. return isWebm ? Math.Max(Environment.ProcessorCount - 1, 2) : 0;
  263. default:
  264. throw new Exception("Unrecognized MediaEncodingQuality value.");
  265. }
  266. }
  267. /// <summary>
  268. /// Gets the video bitrate to specify on the command line
  269. /// </summary>
  270. /// <param name="state">The state.</param>
  271. /// <param name="videoCodec">The video codec.</param>
  272. /// <param name="isHls">if set to <c>true</c> [is HLS].</param>
  273. /// <returns>System.String.</returns>
  274. protected string GetVideoQualityParam(StreamState state, string videoCodec, bool isHls)
  275. {
  276. var param = string.Empty;
  277. var isVc1 = state.VideoStream != null &&
  278. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  279. var qualitySetting = GetQualitySetting();
  280. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  281. {
  282. switch (qualitySetting)
  283. {
  284. case EncodingQuality.HighSpeed:
  285. param = "-preset ultrafast";
  286. break;
  287. case EncodingQuality.HighQuality:
  288. param = "-preset superfast";
  289. break;
  290. case EncodingQuality.MaxQuality:
  291. param = "-preset superfast";
  292. break;
  293. }
  294. switch (qualitySetting)
  295. {
  296. case EncodingQuality.HighSpeed:
  297. param += " -crf 23";
  298. break;
  299. case EncodingQuality.HighQuality:
  300. param += " -crf 20";
  301. break;
  302. case EncodingQuality.MaxQuality:
  303. param += " -crf 18";
  304. break;
  305. }
  306. }
  307. // webm
  308. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  309. {
  310. // Values 0-3, 0 being highest quality but slower
  311. var profileScore = 0;
  312. string crf;
  313. switch (qualitySetting)
  314. {
  315. case EncodingQuality.HighSpeed:
  316. crf = "12";
  317. profileScore = 2;
  318. break;
  319. case EncodingQuality.HighQuality:
  320. crf = "8";
  321. profileScore = 1;
  322. break;
  323. case EncodingQuality.MaxQuality:
  324. crf = "4";
  325. break;
  326. default:
  327. throw new ArgumentException("Unrecognized quality setting");
  328. }
  329. if (isVc1)
  330. {
  331. profileScore ++;
  332. // Max of 2
  333. profileScore = Math.Min(profileScore, 2);
  334. }
  335. // http://www.webmproject.org/docs/encoder-parameters/
  336. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1}",
  337. profileScore.ToString(UsCulture),
  338. crf);
  339. }
  340. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  341. {
  342. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  343. }
  344. // asf/wmv
  345. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  346. {
  347. param = "-qmin 2";
  348. }
  349. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  350. {
  351. param = "-mbd 2";
  352. }
  353. param += GetVideoBitrateParam(state, videoCodec, isHls);
  354. var framerate = GetFramerateParam(state);
  355. if (framerate.HasValue)
  356. {
  357. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  358. }
  359. if (!string.IsNullOrEmpty(state.VideoSync))
  360. {
  361. param += " -vsync " + state.VideoSync;
  362. }
  363. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  364. {
  365. param += " -profile:v " + state.VideoRequest.Profile;
  366. }
  367. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  368. {
  369. param += " -level " + state.VideoRequest.Level;
  370. }
  371. return param;
  372. }
  373. protected string GetAudioFilterParam(StreamState state, bool isHls)
  374. {
  375. var volParam = string.Empty;
  376. var audioSampleRate = string.Empty;
  377. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  378. // Boost volume to 200% when downsampling from 6ch to 2ch
  379. if (channels.HasValue && channels.Value <= 2)
  380. {
  381. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  382. {
  383. volParam = ",volume=2.000000";
  384. }
  385. }
  386. if (state.Request.AudioSampleRate.HasValue)
  387. {
  388. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  389. }
  390. var adelay = isHls ? "adelay=1," : string.Empty;
  391. var pts = string.Empty;
  392. if (state.SubtitleStream != null)
  393. {
  394. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  395. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  396. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  397. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  398. {
  399. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  400. pts = string.Format(",asetpts=PTS-{0}/TB",
  401. Math.Round(seconds).ToString(UsCulture));
  402. }
  403. }
  404. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  405. adelay,
  406. audioSampleRate,
  407. volParam,
  408. pts,
  409. state.AudioSync);
  410. }
  411. /// <summary>
  412. /// If we're going to put a fixed size on the command line, this will calculate it
  413. /// </summary>
  414. /// <param name="state">The state.</param>
  415. /// <param name="outputVideoCodec">The output video codec.</param>
  416. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  417. /// <returns>System.String.</returns>
  418. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  419. {
  420. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  421. var assSubtitleParam = string.Empty;
  422. var copyTsParam = string.Empty;
  423. var yadifParam = state.DeInterlace ? "yadif=0:-1:0," : string.Empty;
  424. var request = state.VideoRequest;
  425. if (state.SubtitleStream != null)
  426. {
  427. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  428. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  429. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  430. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  431. {
  432. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  433. copyTsParam = " -copyts";
  434. }
  435. }
  436. // If fixed dimensions were supplied
  437. if (request.Width.HasValue && request.Height.HasValue)
  438. {
  439. var widthParam = request.Width.Value.ToString(UsCulture);
  440. var heightParam = request.Height.Value.ToString(UsCulture);
  441. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  442. }
  443. // If Max dimensions were supplied, 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
  444. if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  445. {
  446. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  447. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  448. 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);
  449. }
  450. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  451. // If a fixed width was requested
  452. if (request.Width.HasValue)
  453. {
  454. var widthParam = request.Width.Value.ToString(UsCulture);
  455. return isH264Output ?
  456. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  457. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam);
  458. }
  459. // If a fixed height was requested
  460. if (request.Height.HasValue)
  461. {
  462. var heightParam = request.Height.Value.ToString(UsCulture);
  463. return isH264Output ?
  464. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  465. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam);
  466. }
  467. // If a max width was requested
  468. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  469. {
  470. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  471. return isH264Output ?
  472. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  473. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  474. }
  475. // If a max height was requested
  476. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  477. {
  478. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  479. return isH264Output ?
  480. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  481. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  482. }
  483. if (state.VideoStream == null)
  484. {
  485. // No way to figure this out
  486. return string.Empty;
  487. }
  488. // Need to perform calculations manually
  489. // Try to account for bad media info
  490. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  491. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  492. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  493. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  494. if (isH264Output)
  495. {
  496. var widthParam = outputSize.Width.ToString(UsCulture);
  497. var heightParam = outputSize.Height.ToString(UsCulture);
  498. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  499. }
  500. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  501. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  502. }
  503. /// <summary>
  504. /// Gets the text subtitle param.
  505. /// </summary>
  506. /// <param name="state">The state.</param>
  507. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  508. /// <returns>System.String.</returns>
  509. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  510. {
  511. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  512. GetExtractedAssPath(state, performConversion);
  513. if (string.IsNullOrEmpty(path))
  514. {
  515. return string.Empty;
  516. }
  517. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  518. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  519. path.Replace('\\', '/').Replace(":/", "\\:/"),
  520. Math.Round(seconds).ToString(UsCulture));
  521. }
  522. /// <summary>
  523. /// Gets the extracted ass path.
  524. /// </summary>
  525. /// <param name="state">The state.</param>
  526. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  527. /// <returns>System.String.</returns>
  528. private string GetExtractedAssPath(StreamState state, bool performConversion)
  529. {
  530. var path = EncodingManager.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream.Index, ".ass");
  531. if (performConversion)
  532. {
  533. InputType type;
  534. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  535. try
  536. {
  537. var parentPath = Path.GetDirectoryName(path);
  538. Directory.CreateDirectory(parentPath);
  539. // Don't re-encode ass/ssa to ass because ffmpeg ass encoder fails if there's more than one ass rectangle. Affect Anime mostly.
  540. // See https://lists.ffmpeg.org/pipermail/ffmpeg-cvslog/2013-April/063616.html
  541. var isAssSubtitle = string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase);
  542. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, isAssSubtitle, path, CancellationToken.None);
  543. Task.WaitAll(task);
  544. }
  545. catch
  546. {
  547. return null;
  548. }
  549. }
  550. return path;
  551. }
  552. /// <summary>
  553. /// Gets the converted ass path.
  554. /// </summary>
  555. /// <param name="mediaPath">The media path.</param>
  556. /// <param name="subtitleStream">The subtitle stream.</param>
  557. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  558. /// <returns>System.String.</returns>
  559. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  560. {
  561. var path = EncodingManager.GetSubtitleCachePath(subtitleStream.Path, ".ass");
  562. if (performConversion)
  563. {
  564. try
  565. {
  566. var parentPath = Path.GetDirectoryName(path);
  567. Directory.CreateDirectory(parentPath);
  568. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  569. Task.WaitAll(task);
  570. }
  571. catch
  572. {
  573. return null;
  574. }
  575. }
  576. return path;
  577. }
  578. /// <summary>
  579. /// Gets the internal graphical subtitle param.
  580. /// </summary>
  581. /// <param name="state">The state.</param>
  582. /// <param name="outputVideoCodec">The output video codec.</param>
  583. /// <returns>System.String.</returns>
  584. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  585. {
  586. var outputSizeParam = string.Empty;
  587. var request = state.VideoRequest;
  588. // Add resolution params, if specified
  589. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  590. {
  591. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  592. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  593. }
  594. var videoSizeParam = string.Empty;
  595. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  596. {
  597. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  598. }
  599. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  600. state.SubtitleStream.Index,
  601. state.VideoStream.Index,
  602. outputSizeParam,
  603. videoSizeParam);
  604. }
  605. /// <summary>
  606. /// Gets the probe size argument.
  607. /// </summary>
  608. /// <param name="mediaPath">The media path.</param>
  609. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  610. /// <param name="videoType">Type of the video.</param>
  611. /// <param name="isoType">Type of the iso.</param>
  612. /// <returns>System.String.</returns>
  613. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  614. {
  615. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  616. MediaEncoderHelpers.GetInputType(videoType, isoType);
  617. return MediaEncoder.GetProbeSizeArgument(type);
  618. }
  619. /// <summary>
  620. /// Gets the number of audio channels to specify on the command line
  621. /// </summary>
  622. /// <param name="request">The request.</param>
  623. /// <param name="audioStream">The audio stream.</param>
  624. /// <returns>System.Nullable{System.Int32}.</returns>
  625. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  626. {
  627. if (audioStream != null)
  628. {
  629. var codec = request.AudioCodec ?? string.Empty;
  630. if (audioStream.Channels > 2 && codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  631. {
  632. // wmav2 currently only supports two channel output
  633. return 2;
  634. }
  635. }
  636. if (request.MaxAudioChannels.HasValue)
  637. {
  638. if (audioStream != null && audioStream.Channels.HasValue)
  639. {
  640. return Math.Min(request.MaxAudioChannels.Value, audioStream.Channels.Value);
  641. }
  642. return request.MaxAudioChannels.Value;
  643. }
  644. return request.AudioChannels;
  645. }
  646. /// <summary>
  647. /// Determines whether the specified stream is H264.
  648. /// </summary>
  649. /// <param name="stream">The stream.</param>
  650. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  651. protected bool IsH264(MediaStream stream)
  652. {
  653. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  654. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  655. }
  656. /// <summary>
  657. /// Gets the name of the output audio codec
  658. /// </summary>
  659. /// <param name="request">The request.</param>
  660. /// <returns>System.String.</returns>
  661. protected string GetAudioCodec(StreamRequest request)
  662. {
  663. var codec = request.AudioCodec;
  664. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  665. {
  666. return "aac -strict experimental";
  667. }
  668. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  669. {
  670. return "libmp3lame";
  671. }
  672. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  673. {
  674. return "libvorbis";
  675. }
  676. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  677. {
  678. return "wmav2";
  679. }
  680. return codec.ToLower();
  681. }
  682. /// <summary>
  683. /// Gets the name of the output video codec
  684. /// </summary>
  685. /// <param name="request">The request.</param>
  686. /// <returns>System.String.</returns>
  687. protected string GetVideoCodec(VideoStreamRequest request)
  688. {
  689. var codec = request.VideoCodec;
  690. if (!string.IsNullOrEmpty(codec))
  691. {
  692. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  693. {
  694. return "libx264";
  695. }
  696. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  697. {
  698. return "libvpx";
  699. }
  700. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  701. {
  702. return "wmv2";
  703. }
  704. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  705. {
  706. return "libtheora";
  707. }
  708. return codec.ToLower();
  709. }
  710. return "copy";
  711. }
  712. /// <summary>
  713. /// Gets the input argument.
  714. /// </summary>
  715. /// <param name="state">The state.</param>
  716. /// <returns>System.String.</returns>
  717. protected string GetInputArgument(StreamState state)
  718. {
  719. var type = InputType.File;
  720. var inputPath = new[] { state.MediaPath };
  721. if (state.IsInputVideo)
  722. {
  723. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  724. {
  725. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  726. }
  727. }
  728. return MediaEncoder.GetInputArgument(inputPath, type);
  729. }
  730. /// <summary>
  731. /// Starts the FFMPEG.
  732. /// </summary>
  733. /// <param name="state">The state.</param>
  734. /// <param name="outputPath">The output path.</param>
  735. /// <returns>Task.</returns>
  736. protected async Task StartFfMpeg(StreamState state, string outputPath)
  737. {
  738. if (!File.Exists(MediaEncoder.EncoderPath))
  739. {
  740. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  741. }
  742. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  743. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  744. {
  745. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  746. }
  747. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  748. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  749. {
  750. commandLineArgs = "-loglevel debug " + commandLineArgs;
  751. }
  752. var process = new Process
  753. {
  754. StartInfo = new ProcessStartInfo
  755. {
  756. CreateNoWindow = true,
  757. UseShellExecute = false,
  758. // Must consume both stdout and stderr or deadlocks may occur
  759. RedirectStandardOutput = true,
  760. RedirectStandardError = true,
  761. FileName = MediaEncoder.EncoderPath,
  762. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  763. Arguments = commandLineArgs,
  764. WindowStyle = ProcessWindowStyle.Hidden,
  765. ErrorDialog = false
  766. },
  767. EnableRaisingEvents = true
  768. };
  769. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  770. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  771. Logger.Info(commandLineLogMessage);
  772. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
  773. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  774. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  775. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  776. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  777. await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length).ConfigureAwait(false);
  778. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  779. try
  780. {
  781. process.Start();
  782. }
  783. catch (Exception ex)
  784. {
  785. Logger.ErrorException("Error starting ffmpeg", ex);
  786. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  787. throw;
  788. }
  789. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  790. process.BeginOutputReadLine();
  791. #pragma warning disable 4014
  792. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  793. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  794. #pragma warning restore 4014
  795. // Wait for the file to exist before proceeeding
  796. while (!File.Exists(outputPath))
  797. {
  798. await Task.Delay(100).ConfigureAwait(false);
  799. }
  800. // Allow a small amount of time to buffer a little
  801. if (state.IsInputVideo)
  802. {
  803. await Task.Delay(500).ConfigureAwait(false);
  804. }
  805. // This is arbitrary, but add a little buffer time when internet streaming
  806. if (state.IsRemote)
  807. {
  808. await Task.Delay(3000).ConfigureAwait(false);
  809. }
  810. }
  811. protected int? GetVideoBitrateParamValue(StreamState state)
  812. {
  813. var bitrate = state.VideoRequest.VideoBitRate;
  814. if (state.VideoStream != null)
  815. {
  816. var isUpscaling = state.VideoRequest.Height.HasValue && state.VideoStream.Height.HasValue &&
  817. state.VideoRequest.Height.Value > state.VideoStream.Height.Value;
  818. if (state.VideoRequest.Width.HasValue && state.VideoStream.Width.HasValue &&
  819. state.VideoRequest.Width.Value > state.VideoStream.Width.Value)
  820. {
  821. isUpscaling = true;
  822. }
  823. // Don't allow bitrate increases unless upscaling
  824. if (!isUpscaling)
  825. {
  826. if (bitrate.HasValue && state.VideoStream.BitRate.HasValue)
  827. {
  828. bitrate = Math.Min(bitrate.Value, state.VideoStream.BitRate.Value);
  829. }
  830. }
  831. }
  832. return bitrate;
  833. }
  834. protected string GetVideoBitrateParam(StreamState state, string videoCodec, bool isHls)
  835. {
  836. var bitrate = GetVideoBitrateParamValue(state);
  837. if (bitrate.HasValue)
  838. {
  839. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  840. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  841. {
  842. if (hasFixedResolution)
  843. {
  844. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  845. }
  846. // With vpx when crf is used, b:v becomes a max rate
  847. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide. But higher bitrate source files -b:v causes judder so limite the bitrate but dont allow it to "saturate" the bitrate. So dont contrain it down just up.
  848. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  849. }
  850. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  851. {
  852. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  853. }
  854. // H264
  855. if (hasFixedResolution)
  856. {
  857. if (isHls)
  858. {
  859. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  860. }
  861. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  862. }
  863. return string.Format(" -maxrate {0} -bufsize {1}",
  864. bitrate.Value.ToString(UsCulture),
  865. (bitrate.Value * 2).ToString(UsCulture));
  866. }
  867. return string.Empty;
  868. }
  869. protected int? GetAudioBitrateParam(StreamState state)
  870. {
  871. if (state.Request.AudioBitRate.HasValue)
  872. {
  873. // Make sure we don't request a bitrate higher than the source
  874. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  875. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  876. }
  877. return null;
  878. }
  879. /// <summary>
  880. /// Gets the user agent param.
  881. /// </summary>
  882. /// <param name="path">The path.</param>
  883. /// <returns>System.String.</returns>
  884. private string GetUserAgentParam(string path)
  885. {
  886. var useragent = GetUserAgent(path);
  887. if (!string.IsNullOrEmpty(useragent))
  888. {
  889. return "-user-agent \"" + useragent + "\"";
  890. }
  891. return string.Empty;
  892. }
  893. /// <summary>
  894. /// Gets the user agent.
  895. /// </summary>
  896. /// <param name="path">The path.</param>
  897. /// <returns>System.String.</returns>
  898. protected string GetUserAgent(string path)
  899. {
  900. if (string.IsNullOrEmpty(path))
  901. {
  902. throw new ArgumentNullException("path");
  903. }
  904. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  905. {
  906. return "QuickTime/7.7.4";
  907. }
  908. return string.Empty;
  909. }
  910. /// <summary>
  911. /// Processes the exited.
  912. /// </summary>
  913. /// <param name="process">The process.</param>
  914. /// <param name="state">The state.</param>
  915. protected void OnFfMpegProcessExited(Process process, StreamState state)
  916. {
  917. state.Dispose();
  918. var outputFilePath = GetOutputFilePath(state);
  919. try
  920. {
  921. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  922. }
  923. catch
  924. {
  925. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  926. }
  927. }
  928. protected double? GetFramerateParam(StreamState state)
  929. {
  930. if (state.VideoRequest != null)
  931. {
  932. if (state.VideoRequest.Framerate.HasValue)
  933. {
  934. return state.VideoRequest.Framerate.Value;
  935. }
  936. var maxrate = state.VideoRequest.MaxFramerate ?? 23.97602;
  937. if (state.VideoStream != null)
  938. {
  939. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  940. if (contentRate.HasValue && contentRate.Value > maxrate)
  941. {
  942. return maxrate;
  943. }
  944. }
  945. }
  946. return null;
  947. }
  948. /// <summary>
  949. /// Parses the parameters.
  950. /// </summary>
  951. /// <param name="request">The request.</param>
  952. private void ParseParams(StreamRequest request)
  953. {
  954. var vals = request.Params.Split(';');
  955. var videoRequest = request as VideoStreamRequest;
  956. for (var i = 0; i < vals.Length; i++)
  957. {
  958. var val = vals[i];
  959. if (string.IsNullOrWhiteSpace(val))
  960. {
  961. continue;
  962. }
  963. if (i == 0)
  964. {
  965. request.DeviceProfileId = val;
  966. }
  967. else if (i == 1)
  968. {
  969. request.DeviceId = val;
  970. }
  971. else if (i == 2)
  972. {
  973. request.MediaSourceId = val;
  974. }
  975. else if (i == 3)
  976. {
  977. request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  978. }
  979. else if (i == 4)
  980. {
  981. if (videoRequest != null)
  982. {
  983. videoRequest.VideoCodec = val;
  984. }
  985. }
  986. else if (i == 5)
  987. {
  988. request.AudioCodec = val;
  989. }
  990. else if (i == 6)
  991. {
  992. if (videoRequest != null)
  993. {
  994. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  995. }
  996. }
  997. else if (i == 7)
  998. {
  999. if (videoRequest != null)
  1000. {
  1001. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  1002. }
  1003. }
  1004. else if (i == 8)
  1005. {
  1006. if (videoRequest != null)
  1007. {
  1008. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  1009. }
  1010. }
  1011. else if (i == 9)
  1012. {
  1013. request.AudioBitRate = int.Parse(val, UsCulture);
  1014. }
  1015. else if (i == 10)
  1016. {
  1017. request.MaxAudioChannels = int.Parse(val, UsCulture);
  1018. }
  1019. else if (i == 11)
  1020. {
  1021. if (videoRequest != null)
  1022. {
  1023. videoRequest.MaxFramerate = double.Parse(val, UsCulture);
  1024. }
  1025. }
  1026. else if (i == 12)
  1027. {
  1028. if (videoRequest != null)
  1029. {
  1030. videoRequest.MaxWidth = int.Parse(val, UsCulture);
  1031. }
  1032. }
  1033. else if (i == 13)
  1034. {
  1035. if (videoRequest != null)
  1036. {
  1037. videoRequest.MaxHeight = int.Parse(val, UsCulture);
  1038. }
  1039. }
  1040. else if (i == 14)
  1041. {
  1042. request.StartTimeTicks = long.Parse(val, UsCulture);
  1043. }
  1044. else if (i == 15)
  1045. {
  1046. if (videoRequest != null)
  1047. {
  1048. videoRequest.Level = val;
  1049. }
  1050. }
  1051. }
  1052. }
  1053. /// <summary>
  1054. /// Parses the dlna headers.
  1055. /// </summary>
  1056. /// <param name="request">The request.</param>
  1057. private void ParseDlnaHeaders(StreamRequest request)
  1058. {
  1059. if (!request.StartTimeTicks.HasValue)
  1060. {
  1061. var timeSeek = GetHeader("TimeSeekRange.dlna.org");
  1062. request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
  1063. }
  1064. }
  1065. /// <summary>
  1066. /// Parses the time seek header.
  1067. /// </summary>
  1068. private long? ParseTimeSeekHeader(string value)
  1069. {
  1070. if (string.IsNullOrWhiteSpace(value))
  1071. {
  1072. return null;
  1073. }
  1074. if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
  1075. {
  1076. throw new ArgumentException("Invalid timeseek header");
  1077. }
  1078. value = value.Substring(4).Split(new[] { '-' }, 2)[0];
  1079. if (value.IndexOf(':') == -1)
  1080. {
  1081. // Parses npt times in the format of '417.33'
  1082. double seconds;
  1083. if (double.TryParse(value, NumberStyles.Any, UsCulture, out seconds))
  1084. {
  1085. return TimeSpan.FromSeconds(seconds).Ticks;
  1086. }
  1087. throw new ArgumentException("Invalid timeseek header");
  1088. }
  1089. // Parses npt times in the format of '10:19:25.7'
  1090. var tokens = value.Split(new[] { ':' }, 3);
  1091. double secondsSum = 0;
  1092. var timeFactor = 3600;
  1093. foreach (var time in tokens)
  1094. {
  1095. double digit;
  1096. if (double.TryParse(time, NumberStyles.Any, UsCulture, out digit))
  1097. {
  1098. secondsSum += (digit * timeFactor);
  1099. }
  1100. else
  1101. {
  1102. throw new ArgumentException("Invalid timeseek header");
  1103. }
  1104. timeFactor /= 60;
  1105. }
  1106. return TimeSpan.FromSeconds(secondsSum).Ticks;
  1107. }
  1108. /// <summary>
  1109. /// Gets the state.
  1110. /// </summary>
  1111. /// <param name="request">The request.</param>
  1112. /// <param name="cancellationToken">The cancellation token.</param>
  1113. /// <returns>StreamState.</returns>
  1114. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  1115. {
  1116. ParseDlnaHeaders(request);
  1117. if (!string.IsNullOrWhiteSpace(request.Params))
  1118. {
  1119. ParseParams(request);
  1120. }
  1121. var user = AuthorizationRequestFilterAttribute.GetCurrentUser(Request, UserManager);
  1122. var url = Request.PathInfo;
  1123. if (string.IsNullOrEmpty(request.AudioCodec))
  1124. {
  1125. request.AudioCodec = InferAudioCodec(url);
  1126. }
  1127. var state = new StreamState(LiveTvManager, Logger)
  1128. {
  1129. Request = request,
  1130. RequestedUrl = url
  1131. };
  1132. if (!string.IsNullOrWhiteSpace(request.AudioCodec))
  1133. {
  1134. state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  1135. state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault();
  1136. }
  1137. var item = string.IsNullOrEmpty(request.MediaSourceId) ?
  1138. DtoService.GetItemByDtoId(request.Id) :
  1139. DtoService.GetItemByDtoId(request.MediaSourceId);
  1140. if (user != null && item.GetPlayAccess(user) != PlayAccess.Full)
  1141. {
  1142. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  1143. }
  1144. if (item is ILiveTvRecording)
  1145. {
  1146. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  1147. state.VideoType = VideoType.VideoFile;
  1148. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1149. state.PlayableStreamFileNames = new List<string>();
  1150. var path = recording.RecordingInfo.Path;
  1151. var mediaUrl = recording.RecordingInfo.Url;
  1152. if (string.IsNullOrWhiteSpace(path) && string.IsNullOrWhiteSpace(mediaUrl))
  1153. {
  1154. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  1155. state.LiveTvStreamId = streamInfo.Id;
  1156. path = streamInfo.Path;
  1157. mediaUrl = streamInfo.Url;
  1158. }
  1159. if (!string.IsNullOrEmpty(path))
  1160. {
  1161. state.MediaPath = path;
  1162. state.IsRemote = false;
  1163. }
  1164. else if (!string.IsNullOrEmpty(mediaUrl))
  1165. {
  1166. state.MediaPath = mediaUrl;
  1167. state.IsRemote = true;
  1168. }
  1169. state.RunTimeTicks = recording.RunTimeTicks;
  1170. if (recording.RecordingInfo.Status == RecordingStatus.InProgress)
  1171. {
  1172. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1173. }
  1174. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  1175. state.AudioSync = "1000";
  1176. state.DeInterlace = true;
  1177. state.InputVideoSync = "-1";
  1178. state.InputAudioSync = "1";
  1179. }
  1180. else if (item is LiveTvChannel)
  1181. {
  1182. var channel = LiveTvManager.GetInternalChannel(request.Id);
  1183. state.VideoType = VideoType.VideoFile;
  1184. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1185. state.PlayableStreamFileNames = new List<string>();
  1186. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  1187. state.LiveTvStreamId = streamInfo.Id;
  1188. if (!string.IsNullOrEmpty(streamInfo.Path))
  1189. {
  1190. state.MediaPath = streamInfo.Path;
  1191. state.IsRemote = false;
  1192. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1193. }
  1194. else if (!string.IsNullOrEmpty(streamInfo.Url))
  1195. {
  1196. state.MediaPath = streamInfo.Url;
  1197. state.IsRemote = true;
  1198. }
  1199. state.ReadInputAtNativeFramerate = true;
  1200. state.AudioSync = "1000";
  1201. state.DeInterlace = true;
  1202. state.InputVideoSync = "-1";
  1203. state.InputAudioSync = "1";
  1204. }
  1205. else
  1206. {
  1207. state.MediaPath = item.Path;
  1208. state.IsRemote = item.LocationType == LocationType.Remote;
  1209. var video = item as Video;
  1210. if (video != null)
  1211. {
  1212. state.IsInputVideo = true;
  1213. state.VideoType = video.VideoType;
  1214. state.IsoType = video.IsoType;
  1215. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  1216. ? new List<string>()
  1217. : video.PlayableStreamFileNames.ToList();
  1218. }
  1219. state.RunTimeTicks = item.RunTimeTicks;
  1220. }
  1221. var videoRequest = request as VideoStreamRequest;
  1222. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  1223. {
  1224. ItemId = item.Id
  1225. }).ToList();
  1226. if (videoRequest != null)
  1227. {
  1228. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  1229. {
  1230. videoRequest.VideoCodec = InferVideoCodec(url);
  1231. }
  1232. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1233. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1234. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1235. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  1236. {
  1237. state.DeInterlace = true;
  1238. }
  1239. EnforceResolutionLimit(state, videoRequest);
  1240. }
  1241. else
  1242. {
  1243. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1244. }
  1245. state.HasMediaStreams = mediaStreams.Count > 0;
  1246. state.SegmentLength = state.ReadInputAtNativeFramerate ? 5 : 10;
  1247. state.HlsListSize = state.ReadInputAtNativeFramerate ? 100 : 1440;
  1248. ApplyDeviceProfileSettings(state);
  1249. if (videoRequest != null)
  1250. {
  1251. if (state.VideoStream != null && CanStreamCopyVideo(videoRequest, state.VideoStream))
  1252. {
  1253. videoRequest.VideoCodec = "copy";
  1254. }
  1255. if (state.AudioStream != null && CanStreamCopyAudio(request, state.AudioStream, state.SupportedAudioCodecs))
  1256. {
  1257. request.AudioCodec = "copy";
  1258. }
  1259. }
  1260. return state;
  1261. }
  1262. private bool CanStreamCopyVideo(VideoStreamRequest request, MediaStream videoStream)
  1263. {
  1264. if (videoStream.IsInterlaced)
  1265. {
  1266. return false;
  1267. }
  1268. // Source and target codecs must match
  1269. if (!string.Equals(request.VideoCodec, videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  1270. {
  1271. return false;
  1272. }
  1273. // If client is requesting a specific video profile, it must match the source
  1274. if (!string.IsNullOrEmpty(request.Profile) && !string.Equals(request.Profile, videoStream.Profile, StringComparison.OrdinalIgnoreCase))
  1275. {
  1276. return false;
  1277. }
  1278. // Video width must fall within requested value
  1279. if (request.MaxWidth.HasValue)
  1280. {
  1281. if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
  1282. {
  1283. return false;
  1284. }
  1285. }
  1286. // Video height must fall within requested value
  1287. if (request.MaxHeight.HasValue)
  1288. {
  1289. if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
  1290. {
  1291. return false;
  1292. }
  1293. }
  1294. // Video framerate must fall within requested value
  1295. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  1296. if (requestedFramerate.HasValue)
  1297. {
  1298. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  1299. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  1300. {
  1301. return false;
  1302. }
  1303. }
  1304. // Video bitrate must fall within requested value
  1305. if (request.VideoBitRate.HasValue)
  1306. {
  1307. if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
  1308. {
  1309. return false;
  1310. }
  1311. }
  1312. // If a specific level was requested, the source must match or be less than
  1313. if (!string.IsNullOrEmpty(request.Level))
  1314. {
  1315. double requestLevel;
  1316. if (double.TryParse(request.Level, NumberStyles.Any, UsCulture, out requestLevel))
  1317. {
  1318. if (!videoStream.Level.HasValue)
  1319. {
  1320. return false;
  1321. }
  1322. if (videoStream.Level.Value > requestLevel)
  1323. {
  1324. return false;
  1325. }
  1326. }
  1327. }
  1328. return request.EnableAutoStreamCopy;
  1329. }
  1330. private bool CanStreamCopyAudio(StreamRequest request, MediaStream audioStream, List<string> supportedAudioCodecs)
  1331. {
  1332. // Source and target codecs must match
  1333. if (string.IsNullOrEmpty(audioStream.Codec) || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  1334. {
  1335. return false;
  1336. }
  1337. // Video bitrate must fall within requested value
  1338. if (request.AudioBitRate.HasValue)
  1339. {
  1340. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value > request.AudioBitRate.Value)
  1341. {
  1342. return false;
  1343. }
  1344. }
  1345. // Channels must fall within requested value
  1346. var channels = request.AudioChannels ?? request.MaxAudioChannels;
  1347. if (channels.HasValue)
  1348. {
  1349. if (!audioStream.Channels.HasValue || audioStream.Channels.Value > channels.Value)
  1350. {
  1351. return false;
  1352. }
  1353. }
  1354. // Sample rate must fall within requested value
  1355. if (request.AudioSampleRate.HasValue)
  1356. {
  1357. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  1358. {
  1359. return false;
  1360. }
  1361. }
  1362. return true;
  1363. }
  1364. private void ApplyDeviceProfileSettings(StreamState state)
  1365. {
  1366. var headers = new Dictionary<string, string>();
  1367. foreach (var key in Request.Headers.AllKeys)
  1368. {
  1369. headers[key] = Request.Headers[key];
  1370. }
  1371. var profile = string.IsNullOrWhiteSpace(state.Request.DeviceProfileId) ?
  1372. DlnaManager.GetProfile(headers) :
  1373. DlnaManager.GetProfile(state.Request.DeviceProfileId);
  1374. if (profile == null)
  1375. {
  1376. // Don't use settings from the default profile.
  1377. // Only use a specific profile if it was requested.
  1378. return;
  1379. }
  1380. var container = Path.GetExtension(state.RequestedUrl);
  1381. if (string.IsNullOrEmpty(container))
  1382. {
  1383. container = Path.GetExtension(GetOutputFilePath(state));
  1384. }
  1385. var audioCodec = state.Request.AudioCodec;
  1386. if (string.Equals(audioCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.AudioStream != null)
  1387. {
  1388. audioCodec = state.AudioStream.Codec;
  1389. }
  1390. var videoCodec = state.VideoRequest == null ? null : state.VideoRequest.VideoCodec;
  1391. if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.VideoStream != null)
  1392. {
  1393. videoCodec = state.VideoStream.Codec;
  1394. }
  1395. var mediaProfile = state.VideoRequest == null ?
  1396. profile.GetAudioMediaProfile(container, audioCodec, state.AudioStream) :
  1397. profile.GetVideoMediaProfile(container, audioCodec, videoCodec, state.AudioStream, state.VideoStream);
  1398. if (mediaProfile != null)
  1399. {
  1400. state.MimeType = mediaProfile.MimeType;
  1401. state.OrgPn = mediaProfile.OrgPn;
  1402. }
  1403. var transcodingProfile = state.VideoRequest == null ?
  1404. profile.GetAudioTranscodingProfile(container, audioCodec) :
  1405. profile.GetVideoTranscodingProfile(container, audioCodec, videoCodec);
  1406. if (transcodingProfile != null)
  1407. {
  1408. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  1409. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  1410. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  1411. if (state.VideoRequest != null && string.IsNullOrWhiteSpace(state.VideoRequest.Profile))
  1412. {
  1413. state.VideoRequest.Profile = transcodingProfile.VideoProfile;
  1414. }
  1415. }
  1416. }
  1417. /// <summary>
  1418. /// Adds the dlna headers.
  1419. /// </summary>
  1420. /// <param name="state">The state.</param>
  1421. /// <param name="responseHeaders">The response headers.</param>
  1422. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  1423. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1424. protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  1425. {
  1426. var transferMode = GetHeader("transferMode.dlna.org");
  1427. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  1428. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  1429. var contentFeatures = string.Empty;
  1430. var extension = GetOutputFileExtension(state);
  1431. // first bit means Time based seek supported, second byte range seek supported (not sure about the order now), so 01 = only byte seek, 10 = time based, 11 = both, 00 = none
  1432. var orgOp = ";DLNA.ORG_OP=" + DlnaMaps.GetOrgOpValue(state.RunTimeTicks.HasValue, isStaticallyStreamed, state.TranscodeSeekInfo);
  1433. if (state.RunTimeTicks.HasValue && !isStaticallyStreamed)
  1434. {
  1435. AddTimeSeekResponseHeaders(state, responseHeaders);
  1436. }
  1437. // 0 = native, 1 = transcoded
  1438. var orgCi = isStaticallyStreamed ? ";DLNA.ORG_CI=0" : ";DLNA.ORG_CI=1";
  1439. var flagValue = DlnaFlags.StreamingTransferMode |
  1440. DlnaFlags.BackgroundTransferMode |
  1441. DlnaFlags.DlnaV15;
  1442. if (isStaticallyStreamed)
  1443. {
  1444. //flagValue = flagValue | DlnaFlags.DLNA_ORG_FLAG_BYTE_BASED_SEEK;
  1445. }
  1446. else if (state.RunTimeTicks.HasValue)
  1447. {
  1448. //flagValue = flagValue | DlnaFlags.DLNA_ORG_FLAG_TIME_BASED_SEEK;
  1449. }
  1450. var dlnaflags = string.Format(";DLNA.ORG_FLAGS={0}000000000000000000000000",
  1451. Enum.Format(typeof(DlnaFlags), flagValue, "x"));
  1452. if (!string.IsNullOrWhiteSpace(state.OrgPn))
  1453. {
  1454. contentFeatures = "DLNA.ORG_PN=" + state.OrgPn;
  1455. }
  1456. else if (string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase))
  1457. {
  1458. contentFeatures = "DLNA.ORG_PN=MP3";
  1459. }
  1460. else if (string.Equals(extension, ".aac", StringComparison.OrdinalIgnoreCase))
  1461. {
  1462. contentFeatures = "DLNA.ORG_PN=AAC_ISO";
  1463. }
  1464. else if (string.Equals(extension, ".wma", StringComparison.OrdinalIgnoreCase))
  1465. {
  1466. contentFeatures = "DLNA.ORG_PN=WMABASE";
  1467. }
  1468. else if (string.Equals(extension, ".avi", StringComparison.OrdinalIgnoreCase))
  1469. {
  1470. contentFeatures = "DLNA.ORG_PN=AVI";
  1471. }
  1472. else if (string.Equals(extension, ".mkv", StringComparison.OrdinalIgnoreCase))
  1473. {
  1474. contentFeatures = "DLNA.ORG_PN=MATROSKA";
  1475. }
  1476. else if (string.Equals(extension, ".mp4", StringComparison.OrdinalIgnoreCase))
  1477. {
  1478. contentFeatures = "DLNA.ORG_PN=AVC_MP4_MP_HD_720p_AAC";
  1479. }
  1480. else if (string.Equals(extension, ".mpeg", StringComparison.OrdinalIgnoreCase))
  1481. {
  1482. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1483. }
  1484. else if (string.Equals(extension, ".ts", StringComparison.OrdinalIgnoreCase))
  1485. {
  1486. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1487. }
  1488. if (!string.IsNullOrEmpty(contentFeatures))
  1489. {
  1490. responseHeaders["contentFeatures.dlna.org"] = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
  1491. }
  1492. foreach (var item in responseHeaders)
  1493. {
  1494. Request.Response.AddHeader(item.Key, item.Value);
  1495. }
  1496. }
  1497. private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
  1498. {
  1499. var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
  1500. var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
  1501. responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
  1502. responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
  1503. }
  1504. /// <summary>
  1505. /// Enforces the resolution limit.
  1506. /// </summary>
  1507. /// <param name="state">The state.</param>
  1508. /// <param name="videoRequest">The video request.</param>
  1509. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1510. {
  1511. // If enabled, allow whatever the client asks for
  1512. if (ServerConfigurationManager.Configuration.AllowVideoUpscaling)
  1513. {
  1514. return;
  1515. }
  1516. // Switch the incoming params to be ceilings rather than fixed values
  1517. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1518. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1519. videoRequest.Width = null;
  1520. videoRequest.Height = null;
  1521. }
  1522. protected string GetInputModifier(StreamState state)
  1523. {
  1524. var inputModifier = string.Empty;
  1525. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  1526. inputModifier += " " + probeSize;
  1527. inputModifier = inputModifier.Trim();
  1528. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  1529. inputModifier = inputModifier.Trim();
  1530. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1531. inputModifier = inputModifier.Trim();
  1532. if (state.VideoRequest != null)
  1533. {
  1534. inputModifier += " -fflags genpts";
  1535. }
  1536. if (!string.IsNullOrEmpty(state.InputFormat))
  1537. {
  1538. inputModifier += " -f " + state.InputFormat;
  1539. }
  1540. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  1541. {
  1542. inputModifier += " -vcodec " + state.InputVideoCodec;
  1543. }
  1544. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  1545. {
  1546. inputModifier += " -acodec " + state.InputAudioCodec;
  1547. }
  1548. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1549. {
  1550. inputModifier += " -async " + state.InputAudioSync;
  1551. }
  1552. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1553. {
  1554. inputModifier += " -vsync " + state.InputVideoSync;
  1555. }
  1556. if (state.ReadInputAtNativeFramerate)
  1557. {
  1558. inputModifier += " -re";
  1559. }
  1560. return inputModifier;
  1561. }
  1562. /// <summary>
  1563. /// Infers the audio codec based on the url
  1564. /// </summary>
  1565. /// <param name="url">The URL.</param>
  1566. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1567. private string InferAudioCodec(string url)
  1568. {
  1569. var ext = Path.GetExtension(url);
  1570. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1571. {
  1572. return "mp3";
  1573. }
  1574. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1575. {
  1576. return "aac";
  1577. }
  1578. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1579. {
  1580. return "wma";
  1581. }
  1582. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1583. {
  1584. return "vorbis";
  1585. }
  1586. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1587. {
  1588. return "vorbis";
  1589. }
  1590. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1591. {
  1592. return "vorbis";
  1593. }
  1594. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1595. {
  1596. return "vorbis";
  1597. }
  1598. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1599. {
  1600. return "vorbis";
  1601. }
  1602. return "copy";
  1603. }
  1604. /// <summary>
  1605. /// Infers the video codec.
  1606. /// </summary>
  1607. /// <param name="url">The URL.</param>
  1608. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1609. private string InferVideoCodec(string url)
  1610. {
  1611. var ext = Path.GetExtension(url);
  1612. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1613. {
  1614. return "wmv";
  1615. }
  1616. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1617. {
  1618. return "vpx";
  1619. }
  1620. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1621. {
  1622. return "theora";
  1623. }
  1624. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1625. {
  1626. return "h264";
  1627. }
  1628. return "copy";
  1629. }
  1630. }
  1631. }