BaseStreamingService.cs 75 KB

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