BaseStreamingService.cs 77 KB

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