BaseStreamingService.cs 75 KB

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