BaseStreamingService.cs 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986
  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)
  377. {
  378. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  379. {
  380. volParam = ",volume=2.000000";
  381. }
  382. }
  383. if (state.Request.AudioSampleRate.HasValue)
  384. {
  385. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  386. }
  387. var adelay = isHls ? "adelay=1," : string.Empty;
  388. var pts = string.Empty;
  389. if (state.SubtitleStream != null)
  390. {
  391. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  392. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  393. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  394. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  395. {
  396. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  397. pts = string.Format(",asetpts=PTS-{0}/TB",
  398. Math.Round(seconds).ToString(UsCulture));
  399. }
  400. }
  401. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  402. adelay,
  403. audioSampleRate,
  404. volParam,
  405. pts,
  406. state.AudioSync);
  407. }
  408. /// <summary>
  409. /// If we're going to put a fixed size on the command line, this will calculate it
  410. /// </summary>
  411. /// <param name="state">The state.</param>
  412. /// <param name="outputVideoCodec">The output video codec.</param>
  413. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  414. /// <returns>System.String.</returns>
  415. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  416. {
  417. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  418. var assSubtitleParam = string.Empty;
  419. var copyTsParam = string.Empty;
  420. var yadifParam = state.DeInterlace ? "yadif=0:-1:0," : string.Empty;
  421. var request = state.VideoRequest;
  422. if (state.SubtitleStream != null)
  423. {
  424. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  425. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  426. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  427. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  428. {
  429. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  430. copyTsParam = " -copyts";
  431. }
  432. }
  433. // If fixed dimensions were supplied
  434. if (request.Width.HasValue && request.Height.HasValue)
  435. {
  436. var widthParam = request.Width.Value.ToString(UsCulture);
  437. var heightParam = request.Height.Value.ToString(UsCulture);
  438. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  439. }
  440. // 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
  441. if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  442. {
  443. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  444. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  445. 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);
  446. }
  447. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  448. // If a fixed width was requested
  449. if (request.Width.HasValue)
  450. {
  451. var widthParam = request.Width.Value.ToString(UsCulture);
  452. return isH264Output ?
  453. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  454. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam);
  455. }
  456. // If a fixed height was requested
  457. if (request.Height.HasValue)
  458. {
  459. var heightParam = request.Height.Value.ToString(UsCulture);
  460. return isH264Output ?
  461. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  462. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam);
  463. }
  464. // If a max width was requested
  465. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  466. {
  467. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  468. return isH264Output ?
  469. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  470. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  471. }
  472. // If a max height was requested
  473. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  474. {
  475. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  476. return isH264Output ?
  477. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  478. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  479. }
  480. if (state.VideoStream == null)
  481. {
  482. // No way to figure this out
  483. return string.Empty;
  484. }
  485. // Need to perform calculations manually
  486. // Try to account for bad media info
  487. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  488. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  489. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  490. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  491. if (isH264Output)
  492. {
  493. var widthParam = outputSize.Width.ToString(UsCulture);
  494. var heightParam = outputSize.Height.ToString(UsCulture);
  495. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  496. }
  497. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  498. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  499. }
  500. /// <summary>
  501. /// Gets the text subtitle param.
  502. /// </summary>
  503. /// <param name="state">The state.</param>
  504. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  505. /// <returns>System.String.</returns>
  506. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  507. {
  508. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  509. GetExtractedAssPath(state, performConversion);
  510. if (string.IsNullOrEmpty(path))
  511. {
  512. return string.Empty;
  513. }
  514. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  515. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  516. path.Replace('\\', '/').Replace(":/", "\\:/"),
  517. Math.Round(seconds).ToString(UsCulture));
  518. }
  519. /// <summary>
  520. /// Gets the extracted ass path.
  521. /// </summary>
  522. /// <param name="state">The state.</param>
  523. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  524. /// <returns>System.String.</returns>
  525. private string GetExtractedAssPath(StreamState state, bool performConversion)
  526. {
  527. var path = EncodingManager.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream.Index, ".ass");
  528. if (performConversion)
  529. {
  530. InputType type;
  531. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  532. try
  533. {
  534. var parentPath = Path.GetDirectoryName(path);
  535. Directory.CreateDirectory(parentPath);
  536. // Don't re-encode ass/ssa to ass because ffmpeg ass encoder fails if there's more than one ass rectangle. Affect Anime mostly.
  537. // See https://lists.ffmpeg.org/pipermail/ffmpeg-cvslog/2013-April/063616.html
  538. var isAssSubtitle = string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase);
  539. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, isAssSubtitle, path, CancellationToken.None);
  540. Task.WaitAll(task);
  541. }
  542. catch
  543. {
  544. return null;
  545. }
  546. }
  547. return path;
  548. }
  549. /// <summary>
  550. /// Gets the converted ass path.
  551. /// </summary>
  552. /// <param name="mediaPath">The media path.</param>
  553. /// <param name="subtitleStream">The subtitle stream.</param>
  554. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  555. /// <returns>System.String.</returns>
  556. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  557. {
  558. var path = EncodingManager.GetSubtitleCachePath(subtitleStream.Path, ".ass");
  559. if (performConversion)
  560. {
  561. try
  562. {
  563. var parentPath = Path.GetDirectoryName(path);
  564. Directory.CreateDirectory(parentPath);
  565. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  566. Task.WaitAll(task);
  567. }
  568. catch
  569. {
  570. return null;
  571. }
  572. }
  573. return path;
  574. }
  575. /// <summary>
  576. /// Gets the internal graphical subtitle param.
  577. /// </summary>
  578. /// <param name="state">The state.</param>
  579. /// <param name="outputVideoCodec">The output video codec.</param>
  580. /// <returns>System.String.</returns>
  581. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  582. {
  583. var outputSizeParam = string.Empty;
  584. var request = state.VideoRequest;
  585. // Add resolution params, if specified
  586. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  587. {
  588. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  589. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  590. }
  591. var videoSizeParam = string.Empty;
  592. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  593. {
  594. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  595. }
  596. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  597. state.SubtitleStream.Index,
  598. state.VideoStream.Index,
  599. outputSizeParam,
  600. videoSizeParam);
  601. }
  602. /// <summary>
  603. /// Gets the probe size argument.
  604. /// </summary>
  605. /// <param name="mediaPath">The media path.</param>
  606. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  607. /// <param name="videoType">Type of the video.</param>
  608. /// <param name="isoType">Type of the iso.</param>
  609. /// <returns>System.String.</returns>
  610. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  611. {
  612. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  613. MediaEncoderHelpers.GetInputType(videoType, isoType);
  614. return MediaEncoder.GetProbeSizeArgument(type);
  615. }
  616. /// <summary>
  617. /// Gets the number of audio channels to specify on the command line
  618. /// </summary>
  619. /// <param name="request">The request.</param>
  620. /// <param name="audioStream">The audio stream.</param>
  621. /// <returns>System.Nullable{System.Int32}.</returns>
  622. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  623. {
  624. if (audioStream != null)
  625. {
  626. var codec = request.AudioCodec ?? string.Empty;
  627. if (audioStream.Channels > 2 && codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  628. {
  629. // wmav2 currently only supports two channel output
  630. return 2;
  631. }
  632. }
  633. if (request.MaxAudioChannels.HasValue)
  634. {
  635. if (audioStream != null && audioStream.Channels.HasValue)
  636. {
  637. return Math.Min(request.MaxAudioChannels.Value, audioStream.Channels.Value);
  638. }
  639. return request.MaxAudioChannels.Value;
  640. }
  641. return request.AudioChannels;
  642. }
  643. /// <summary>
  644. /// Determines whether the specified stream is H264.
  645. /// </summary>
  646. /// <param name="stream">The stream.</param>
  647. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  648. protected bool IsH264(MediaStream stream)
  649. {
  650. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  651. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  652. }
  653. /// <summary>
  654. /// Gets the name of the output audio codec
  655. /// </summary>
  656. /// <param name="request">The request.</param>
  657. /// <returns>System.String.</returns>
  658. protected string GetAudioCodec(StreamRequest request)
  659. {
  660. var codec = request.AudioCodec;
  661. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  662. {
  663. return "aac -strict experimental";
  664. }
  665. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  666. {
  667. return "libmp3lame";
  668. }
  669. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  670. {
  671. return "libvorbis";
  672. }
  673. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  674. {
  675. return "wmav2";
  676. }
  677. return codec.ToLower();
  678. }
  679. /// <summary>
  680. /// Gets the name of the output video codec
  681. /// </summary>
  682. /// <param name="request">The request.</param>
  683. /// <returns>System.String.</returns>
  684. protected string GetVideoCodec(VideoStreamRequest request)
  685. {
  686. var codec = request.VideoCodec;
  687. if (!string.IsNullOrEmpty(codec))
  688. {
  689. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  690. {
  691. return "libx264";
  692. }
  693. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  694. {
  695. return "libvpx";
  696. }
  697. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  698. {
  699. return "wmv2";
  700. }
  701. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  702. {
  703. return "libtheora";
  704. }
  705. return codec.ToLower();
  706. }
  707. return "copy";
  708. }
  709. /// <summary>
  710. /// Gets the input argument.
  711. /// </summary>
  712. /// <param name="state">The state.</param>
  713. /// <returns>System.String.</returns>
  714. protected string GetInputArgument(StreamState state)
  715. {
  716. var type = InputType.File;
  717. var inputPath = new[] { state.MediaPath };
  718. if (state.IsInputVideo)
  719. {
  720. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  721. {
  722. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  723. }
  724. }
  725. return MediaEncoder.GetInputArgument(inputPath, type);
  726. }
  727. /// <summary>
  728. /// Starts the FFMPEG.
  729. /// </summary>
  730. /// <param name="state">The state.</param>
  731. /// <param name="outputPath">The output path.</param>
  732. /// <returns>Task.</returns>
  733. protected async Task StartFfMpeg(StreamState state, string outputPath)
  734. {
  735. if (!File.Exists(MediaEncoder.EncoderPath))
  736. {
  737. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  738. }
  739. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  740. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  741. {
  742. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  743. }
  744. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  745. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  746. {
  747. commandLineArgs = "-loglevel debug " + commandLineArgs;
  748. }
  749. var process = new Process
  750. {
  751. StartInfo = new ProcessStartInfo
  752. {
  753. CreateNoWindow = true,
  754. UseShellExecute = false,
  755. // Must consume both stdout and stderr or deadlocks may occur
  756. RedirectStandardOutput = true,
  757. RedirectStandardError = true,
  758. FileName = MediaEncoder.EncoderPath,
  759. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  760. Arguments = commandLineArgs,
  761. WindowStyle = ProcessWindowStyle.Hidden,
  762. ErrorDialog = false
  763. },
  764. EnableRaisingEvents = true
  765. };
  766. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  767. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  768. Logger.Info(commandLineLogMessage);
  769. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  770. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  771. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  772. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  773. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  774. await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length).ConfigureAwait(false);
  775. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  776. try
  777. {
  778. process.Start();
  779. }
  780. catch (Exception ex)
  781. {
  782. Logger.ErrorException("Error starting ffmpeg", ex);
  783. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  784. throw;
  785. }
  786. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  787. process.BeginOutputReadLine();
  788. #pragma warning disable 4014
  789. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  790. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  791. #pragma warning restore 4014
  792. // Wait for the file to exist before proceeeding
  793. while (!File.Exists(outputPath))
  794. {
  795. await Task.Delay(100).ConfigureAwait(false);
  796. }
  797. // Allow a small amount of time to buffer a little
  798. if (state.IsInputVideo)
  799. {
  800. await Task.Delay(500).ConfigureAwait(false);
  801. }
  802. // This is arbitrary, but add a little buffer time when internet streaming
  803. if (state.IsRemote)
  804. {
  805. await Task.Delay(3000).ConfigureAwait(false);
  806. }
  807. }
  808. protected int? GetVideoBitrateParamValue(StreamState state)
  809. {
  810. var bitrate = state.VideoRequest.VideoBitRate;
  811. if (state.VideoStream != null)
  812. {
  813. var isUpscaling = state.VideoRequest.Height.HasValue && state.VideoStream.Height.HasValue &&
  814. state.VideoRequest.Height.Value > state.VideoStream.Height.Value;
  815. if (state.VideoRequest.Width.HasValue && state.VideoStream.Width.HasValue &&
  816. state.VideoRequest.Width.Value > state.VideoStream.Width.Value)
  817. {
  818. isUpscaling = true;
  819. }
  820. // Don't allow bitrate increases unless upscaling
  821. if (!isUpscaling)
  822. {
  823. if (bitrate.HasValue && state.VideoStream.BitRate.HasValue)
  824. {
  825. bitrate = Math.Min(bitrate.Value, state.VideoStream.BitRate.Value);
  826. }
  827. }
  828. }
  829. return bitrate;
  830. }
  831. protected string GetVideoBitrateParam(StreamState state, string videoCodec, bool isHls)
  832. {
  833. var bitrate = GetVideoBitrateParamValue(state);
  834. if (bitrate.HasValue)
  835. {
  836. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  837. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  838. {
  839. if (hasFixedResolution)
  840. {
  841. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  842. }
  843. // With vpx when crf is used, b:v becomes a max rate
  844. // 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.
  845. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  846. }
  847. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  848. {
  849. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  850. }
  851. // H264
  852. if (hasFixedResolution)
  853. {
  854. if (isHls)
  855. {
  856. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  857. }
  858. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  859. }
  860. return string.Format(" -maxrate {0} -bufsize {1}",
  861. bitrate.Value.ToString(UsCulture),
  862. (bitrate.Value * 2).ToString(UsCulture));
  863. }
  864. return string.Empty;
  865. }
  866. protected int? GetAudioBitrateParam(StreamState state)
  867. {
  868. if (state.Request.AudioBitRate.HasValue)
  869. {
  870. // Make sure we don't request a bitrate higher than the source
  871. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  872. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  873. }
  874. return null;
  875. }
  876. /// <summary>
  877. /// Gets the user agent param.
  878. /// </summary>
  879. /// <param name="path">The path.</param>
  880. /// <returns>System.String.</returns>
  881. private string GetUserAgentParam(string path)
  882. {
  883. var useragent = GetUserAgent(path);
  884. if (!string.IsNullOrEmpty(useragent))
  885. {
  886. return "-user-agent \"" + useragent + "\"";
  887. }
  888. return string.Empty;
  889. }
  890. /// <summary>
  891. /// Gets the user agent.
  892. /// </summary>
  893. /// <param name="path">The path.</param>
  894. /// <returns>System.String.</returns>
  895. protected string GetUserAgent(string path)
  896. {
  897. if (string.IsNullOrEmpty(path))
  898. {
  899. throw new ArgumentNullException("path");
  900. }
  901. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  902. {
  903. return "QuickTime/7.7.4";
  904. }
  905. return string.Empty;
  906. }
  907. /// <summary>
  908. /// Processes the exited.
  909. /// </summary>
  910. /// <param name="process">The process.</param>
  911. /// <param name="state">The state.</param>
  912. protected void OnFfMpegProcessExited(Process process, StreamState state)
  913. {
  914. state.Dispose();
  915. var outputFilePath = GetOutputFilePath(state);
  916. try
  917. {
  918. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  919. }
  920. catch
  921. {
  922. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  923. }
  924. }
  925. protected double? GetFramerateParam(StreamState state)
  926. {
  927. if (state.VideoRequest != null)
  928. {
  929. if (state.VideoRequest.Framerate.HasValue)
  930. {
  931. return state.VideoRequest.Framerate.Value;
  932. }
  933. var maxrate = state.VideoRequest.MaxFramerate ?? 23.97602;
  934. if (state.VideoStream != null)
  935. {
  936. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  937. if (contentRate.HasValue && contentRate.Value > maxrate)
  938. {
  939. return maxrate;
  940. }
  941. }
  942. }
  943. return null;
  944. }
  945. /// <summary>
  946. /// Parses the parameters.
  947. /// </summary>
  948. /// <param name="request">The request.</param>
  949. private void ParseParams(StreamRequest request)
  950. {
  951. var vals = request.Params.Split(';');
  952. var videoRequest = request as VideoStreamRequest;
  953. for (var i = 0; i < vals.Length; i++)
  954. {
  955. var val = vals[i];
  956. if (string.IsNullOrWhiteSpace(val))
  957. {
  958. continue;
  959. }
  960. if (i == 0)
  961. {
  962. request.DeviceProfileId = val;
  963. }
  964. else if (i == 1)
  965. {
  966. request.DeviceId = val;
  967. }
  968. else if (i == 2)
  969. {
  970. request.MediaSourceId = val;
  971. }
  972. else if (i == 3)
  973. {
  974. request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  975. }
  976. else if (i == 4)
  977. {
  978. if (videoRequest != null)
  979. {
  980. videoRequest.VideoCodec = val;
  981. }
  982. }
  983. else if (i == 5)
  984. {
  985. request.AudioCodec = val;
  986. }
  987. else if (i == 6)
  988. {
  989. if (videoRequest != null)
  990. {
  991. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  992. }
  993. }
  994. else if (i == 7)
  995. {
  996. if (videoRequest != null)
  997. {
  998. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  999. }
  1000. }
  1001. else if (i == 8)
  1002. {
  1003. if (videoRequest != null)
  1004. {
  1005. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  1006. }
  1007. }
  1008. else if (i == 9)
  1009. {
  1010. request.AudioBitRate = int.Parse(val, UsCulture);
  1011. }
  1012. else if (i == 10)
  1013. {
  1014. request.MaxAudioChannels = int.Parse(val, UsCulture);
  1015. }
  1016. else if (i == 11)
  1017. {
  1018. if (videoRequest != null)
  1019. {
  1020. videoRequest.MaxFramerate = double.Parse(val, UsCulture);
  1021. }
  1022. }
  1023. else if (i == 12)
  1024. {
  1025. if (videoRequest != null)
  1026. {
  1027. videoRequest.MaxWidth = int.Parse(val, UsCulture);
  1028. }
  1029. }
  1030. else if (i == 13)
  1031. {
  1032. if (videoRequest != null)
  1033. {
  1034. videoRequest.MaxHeight = int.Parse(val, UsCulture);
  1035. }
  1036. }
  1037. else if (i == 14)
  1038. {
  1039. request.StartTimeTicks = long.Parse(val, UsCulture);
  1040. }
  1041. else if (i == 15)
  1042. {
  1043. if (videoRequest != null)
  1044. {
  1045. videoRequest.Level = val;
  1046. }
  1047. }
  1048. }
  1049. }
  1050. /// <summary>
  1051. /// Parses the dlna headers.
  1052. /// </summary>
  1053. /// <param name="request">The request.</param>
  1054. private void ParseDlnaHeaders(StreamRequest request)
  1055. {
  1056. if (!request.StartTimeTicks.HasValue)
  1057. {
  1058. var timeSeek = GetHeader("TimeSeekRange.dlna.org");
  1059. request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
  1060. }
  1061. }
  1062. /// <summary>
  1063. /// Parses the time seek header.
  1064. /// </summary>
  1065. private long? ParseTimeSeekHeader(string value)
  1066. {
  1067. if (string.IsNullOrWhiteSpace(value))
  1068. {
  1069. return null;
  1070. }
  1071. if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
  1072. {
  1073. throw new ArgumentException("Invalid timeseek header");
  1074. }
  1075. value = value.Substring(4).Split(new[] { '-' }, 2)[0];
  1076. if (value.IndexOf(':') == -1)
  1077. {
  1078. // Parses npt times in the format of '417.33'
  1079. double seconds;
  1080. if (double.TryParse(value, NumberStyles.Any, UsCulture, out seconds))
  1081. {
  1082. return TimeSpan.FromSeconds(seconds).Ticks;
  1083. }
  1084. throw new ArgumentException("Invalid timeseek header");
  1085. }
  1086. // Parses npt times in the format of '10:19:25.7'
  1087. var tokens = value.Split(new[] { ':' }, 3);
  1088. double secondsSum = 0;
  1089. var timeFactor = 3600;
  1090. foreach (var time in tokens)
  1091. {
  1092. double digit;
  1093. if (double.TryParse(time, NumberStyles.Any, UsCulture, out digit))
  1094. {
  1095. secondsSum += (digit * timeFactor);
  1096. }
  1097. else
  1098. {
  1099. throw new ArgumentException("Invalid timeseek header");
  1100. }
  1101. timeFactor /= 60;
  1102. }
  1103. return TimeSpan.FromSeconds(secondsSum).Ticks;
  1104. }
  1105. /// <summary>
  1106. /// Gets the state.
  1107. /// </summary>
  1108. /// <param name="request">The request.</param>
  1109. /// <param name="cancellationToken">The cancellation token.</param>
  1110. /// <returns>StreamState.</returns>
  1111. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  1112. {
  1113. ParseDlnaHeaders(request);
  1114. if (!string.IsNullOrWhiteSpace(request.Params))
  1115. {
  1116. ParseParams(request);
  1117. }
  1118. var user = AuthorizationRequestFilterAttribute.GetCurrentUser(Request, UserManager);
  1119. var url = Request.PathInfo;
  1120. if (string.IsNullOrEmpty(request.AudioCodec))
  1121. {
  1122. request.AudioCodec = InferAudioCodec(url);
  1123. }
  1124. var state = new StreamState(LiveTvManager, Logger)
  1125. {
  1126. Request = request,
  1127. RequestedUrl = url
  1128. };
  1129. var item = string.IsNullOrEmpty(request.MediaSourceId) ?
  1130. DtoService.GetItemByDtoId(request.Id) :
  1131. DtoService.GetItemByDtoId(request.MediaSourceId);
  1132. if (user != null && item.GetPlayAccess(user) != PlayAccess.Full)
  1133. {
  1134. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  1135. }
  1136. if (item is ILiveTvRecording)
  1137. {
  1138. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  1139. state.VideoType = VideoType.VideoFile;
  1140. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1141. state.PlayableStreamFileNames = new List<string>();
  1142. var path = recording.RecordingInfo.Path;
  1143. var mediaUrl = recording.RecordingInfo.Url;
  1144. if (string.IsNullOrWhiteSpace(path) && string.IsNullOrWhiteSpace(mediaUrl))
  1145. {
  1146. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  1147. state.LiveTvStreamId = streamInfo.Id;
  1148. path = streamInfo.Path;
  1149. mediaUrl = streamInfo.Url;
  1150. }
  1151. if (!string.IsNullOrEmpty(path))
  1152. {
  1153. state.MediaPath = path;
  1154. state.IsRemote = false;
  1155. }
  1156. else if (!string.IsNullOrEmpty(mediaUrl))
  1157. {
  1158. state.MediaPath = mediaUrl;
  1159. state.IsRemote = true;
  1160. }
  1161. state.RunTimeTicks = recording.RunTimeTicks;
  1162. if (recording.RecordingInfo.Status == RecordingStatus.InProgress)
  1163. {
  1164. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1165. }
  1166. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  1167. state.AudioSync = "1000";
  1168. state.DeInterlace = true;
  1169. state.InputVideoSync = "-1";
  1170. state.InputAudioSync = "1";
  1171. }
  1172. else if (item is LiveTvChannel)
  1173. {
  1174. var channel = LiveTvManager.GetInternalChannel(request.Id);
  1175. state.VideoType = VideoType.VideoFile;
  1176. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1177. state.PlayableStreamFileNames = new List<string>();
  1178. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  1179. state.LiveTvStreamId = streamInfo.Id;
  1180. if (!string.IsNullOrEmpty(streamInfo.Path))
  1181. {
  1182. state.MediaPath = streamInfo.Path;
  1183. state.IsRemote = false;
  1184. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1185. }
  1186. else if (!string.IsNullOrEmpty(streamInfo.Url))
  1187. {
  1188. state.MediaPath = streamInfo.Url;
  1189. state.IsRemote = true;
  1190. }
  1191. state.ReadInputAtNativeFramerate = true;
  1192. state.AudioSync = "1000";
  1193. state.DeInterlace = true;
  1194. state.InputVideoSync = "-1";
  1195. state.InputAudioSync = "1";
  1196. }
  1197. else
  1198. {
  1199. state.MediaPath = item.Path;
  1200. state.IsRemote = item.LocationType == LocationType.Remote;
  1201. var video = item as Video;
  1202. if (video != null)
  1203. {
  1204. state.IsInputVideo = true;
  1205. state.VideoType = video.VideoType;
  1206. state.IsoType = video.IsoType;
  1207. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  1208. ? new List<string>()
  1209. : video.PlayableStreamFileNames.ToList();
  1210. }
  1211. state.RunTimeTicks = item.RunTimeTicks;
  1212. }
  1213. var videoRequest = request as VideoStreamRequest;
  1214. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  1215. {
  1216. ItemId = item.Id
  1217. }).ToList();
  1218. if (videoRequest != null)
  1219. {
  1220. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  1221. {
  1222. videoRequest.VideoCodec = InferVideoCodec(url);
  1223. }
  1224. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1225. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1226. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1227. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  1228. {
  1229. state.DeInterlace = true;
  1230. }
  1231. EnforceResolutionLimit(state, videoRequest);
  1232. }
  1233. else
  1234. {
  1235. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1236. }
  1237. state.HasMediaStreams = mediaStreams.Count > 0;
  1238. state.SegmentLength = state.ReadInputAtNativeFramerate ? 5 : 10;
  1239. state.HlsListSize = state.ReadInputAtNativeFramerate ? 100 : 1440;
  1240. ApplyDeviceProfileSettings(state);
  1241. if (videoRequest != null && state.VideoStream != null)
  1242. {
  1243. if (CanStreamCopyVideo(videoRequest, state.VideoStream, state.VideoType))
  1244. {
  1245. videoRequest.VideoCodec = "copy";
  1246. }
  1247. }
  1248. if (state.AudioStream != null)
  1249. {
  1250. //if (CanStreamCopyAudio(request, state.AudioStream))
  1251. //{
  1252. // request.AudioCodec = "copy";
  1253. //}
  1254. }
  1255. return state;
  1256. }
  1257. private bool CanStreamCopyVideo(VideoStreamRequest request, MediaStream videoStream, VideoType videoType)
  1258. {
  1259. if (videoStream.IsInterlaced)
  1260. {
  1261. return false;
  1262. }
  1263. // Not going to attempt this with folder rips
  1264. if (videoType != VideoType.VideoFile)
  1265. {
  1266. return false;
  1267. }
  1268. // Source and target codecs must match
  1269. if (!string.Equals(request.VideoCodec, videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  1270. {
  1271. return false;
  1272. }
  1273. // If client is requesting a specific video profile, it must match the source
  1274. if (!string.IsNullOrEmpty(request.Profile) && !string.Equals(request.Profile, videoStream.Profile, StringComparison.OrdinalIgnoreCase))
  1275. {
  1276. return false;
  1277. }
  1278. // Video width must fall within requested value
  1279. if (request.MaxWidth.HasValue)
  1280. {
  1281. if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
  1282. {
  1283. return false;
  1284. }
  1285. }
  1286. // Video height must fall within requested value
  1287. if (request.MaxHeight.HasValue)
  1288. {
  1289. if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
  1290. {
  1291. return false;
  1292. }
  1293. }
  1294. // Video framerate must fall within requested value
  1295. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  1296. if (requestedFramerate.HasValue)
  1297. {
  1298. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  1299. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  1300. {
  1301. return false;
  1302. }
  1303. }
  1304. // Video bitrate must fall within requested value
  1305. if (request.VideoBitRate.HasValue)
  1306. {
  1307. if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
  1308. {
  1309. return false;
  1310. }
  1311. }
  1312. // If a specific level was requested, the source must match or be less than
  1313. if (!string.IsNullOrEmpty(request.Level))
  1314. {
  1315. double requestLevel;
  1316. if (double.TryParse(request.Level, NumberStyles.Any, UsCulture, out requestLevel))
  1317. {
  1318. if (!videoStream.Level.HasValue)
  1319. {
  1320. return false;
  1321. }
  1322. if (videoStream.Level.Value > requestLevel)
  1323. {
  1324. return false;
  1325. }
  1326. }
  1327. }
  1328. return SupportsAutomaticVideoStreamCopy;
  1329. }
  1330. private bool CanStreamCopyAudio(StreamRequest request, MediaStream audioStream)
  1331. {
  1332. // Source and target codecs must match
  1333. if (string.IsNullOrEmpty(request.AudioCodec) || !string.Equals(request.AudioCodec, audioStream.Codec, StringComparison.OrdinalIgnoreCase))
  1334. {
  1335. return false;
  1336. }
  1337. // Video bitrate must fall within requested value
  1338. if (request.AudioBitRate.HasValue)
  1339. {
  1340. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value > request.AudioBitRate.Value)
  1341. {
  1342. return false;
  1343. }
  1344. }
  1345. // Channels must fall within requested value
  1346. var channels = request.AudioChannels ?? request.MaxAudioChannels;
  1347. if (channels.HasValue)
  1348. {
  1349. if (!audioStream.Channels.HasValue || audioStream.Channels.Value > channels.Value)
  1350. {
  1351. return false;
  1352. }
  1353. }
  1354. // Sample rate must fall within requested value
  1355. if (request.AudioSampleRate.HasValue)
  1356. {
  1357. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  1358. {
  1359. return false;
  1360. }
  1361. }
  1362. return SupportsAutomaticVideoStreamCopy;
  1363. }
  1364. protected virtual bool SupportsAutomaticVideoStreamCopy
  1365. {
  1366. get
  1367. {
  1368. return false;
  1369. }
  1370. }
  1371. private void ApplyDeviceProfileSettings(StreamState state)
  1372. {
  1373. var headers = new Dictionary<string, string>();
  1374. foreach (var key in Request.Headers.AllKeys)
  1375. {
  1376. headers[key] = Request.Headers[key];
  1377. }
  1378. var profile = string.IsNullOrWhiteSpace(state.Request.DeviceProfileId) ?
  1379. DlnaManager.GetProfile(headers) :
  1380. DlnaManager.GetProfile(state.Request.DeviceProfileId);
  1381. if (profile == null)
  1382. {
  1383. // Don't use settings from the default profile.
  1384. // Only use a specific profile if it was requested.
  1385. return;
  1386. }
  1387. var container = Path.GetExtension(state.RequestedUrl);
  1388. if (string.IsNullOrEmpty(container))
  1389. {
  1390. container = Path.GetExtension(GetOutputFilePath(state));
  1391. }
  1392. var audioCodec = state.Request.AudioCodec;
  1393. if (string.Equals(audioCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.AudioStream != null)
  1394. {
  1395. audioCodec = state.AudioStream.Codec;
  1396. }
  1397. var videoCodec = state.VideoRequest == null ? null : state.VideoRequest.VideoCodec;
  1398. if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.VideoStream != null)
  1399. {
  1400. videoCodec = state.VideoStream.Codec;
  1401. }
  1402. var mediaProfile = state.VideoRequest == null ?
  1403. profile.GetAudioMediaProfile(container, audioCodec, state.AudioStream) :
  1404. profile.GetVideoMediaProfile(container, audioCodec, videoCodec, state.AudioStream, state.VideoStream);
  1405. if (mediaProfile != null)
  1406. {
  1407. state.MimeType = mediaProfile.MimeType;
  1408. state.OrgPn = mediaProfile.OrgPn;
  1409. }
  1410. var transcodingProfile = state.VideoRequest == null ?
  1411. profile.GetAudioTranscodingProfile(container, audioCodec) :
  1412. profile.GetVideoTranscodingProfile(container, audioCodec, videoCodec);
  1413. if (transcodingProfile != null)
  1414. {
  1415. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  1416. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  1417. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  1418. if (state.VideoRequest != null && string.IsNullOrWhiteSpace(state.VideoRequest.Profile))
  1419. {
  1420. state.VideoRequest.Profile = transcodingProfile.VideoProfile;
  1421. }
  1422. }
  1423. }
  1424. /// <summary>
  1425. /// Adds the dlna headers.
  1426. /// </summary>
  1427. /// <param name="state">The state.</param>
  1428. /// <param name="responseHeaders">The response headers.</param>
  1429. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  1430. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1431. protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  1432. {
  1433. var transferMode = GetHeader("transferMode.dlna.org");
  1434. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  1435. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  1436. var contentFeatures = string.Empty;
  1437. var extension = GetOutputFileExtension(state);
  1438. // 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
  1439. var orgOp = ";DLNA.ORG_OP=";
  1440. if (state.RunTimeTicks.HasValue)
  1441. {
  1442. // Time-based seeking currently only possible when transcoding
  1443. orgOp += isStaticallyStreamed ? "0" : "1";
  1444. // Byte-based seeking only possible when not transcoding
  1445. orgOp += isStaticallyStreamed || state.TranscodeSeekInfo == TranscodeSeekInfo.Bytes ? "1" : "0";
  1446. if (!isStaticallyStreamed)
  1447. {
  1448. AddTimeSeekResponseHeaders(state, responseHeaders);
  1449. }
  1450. }
  1451. else
  1452. {
  1453. // No seeking is available if we don't know the content runtime
  1454. orgOp += "00";
  1455. }
  1456. // 0 = native, 1 = transcoded
  1457. var orgCi = isStaticallyStreamed ? ";DLNA.ORG_CI=0" : ";DLNA.ORG_CI=1";
  1458. var flagValue = DlnaFlags.DLNA_ORG_FLAG_STREAMING_TRANSFER_MODE |
  1459. DlnaFlags.DLNA_ORG_FLAG_BACKGROUND_TRANSFERT_MODE |
  1460. DlnaFlags.DLNA_ORG_FLAG_DLNA_V15;
  1461. if (isStaticallyStreamed)
  1462. {
  1463. //flagValue = flagValue | DlnaFlags.DLNA_ORG_FLAG_BYTE_BASED_SEEK;
  1464. }
  1465. else if (state.RunTimeTicks.HasValue)
  1466. {
  1467. //flagValue = flagValue | DlnaFlags.DLNA_ORG_FLAG_TIME_BASED_SEEK;
  1468. }
  1469. var dlnaflags = string.Format(";DLNA.ORG_FLAGS={0}000000000000000000000000",
  1470. Enum.Format(typeof(DlnaFlags), flagValue, "x"));
  1471. if (!string.IsNullOrWhiteSpace(state.OrgPn))
  1472. {
  1473. contentFeatures = "DLNA.ORG_PN=" + state.OrgPn;
  1474. }
  1475. else if (string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase))
  1476. {
  1477. contentFeatures = "DLNA.ORG_PN=MP3";
  1478. }
  1479. else if (string.Equals(extension, ".aac", StringComparison.OrdinalIgnoreCase))
  1480. {
  1481. contentFeatures = "DLNA.ORG_PN=AAC_ISO";
  1482. }
  1483. else if (string.Equals(extension, ".wma", StringComparison.OrdinalIgnoreCase))
  1484. {
  1485. contentFeatures = "DLNA.ORG_PN=WMABASE";
  1486. }
  1487. else if (string.Equals(extension, ".avi", StringComparison.OrdinalIgnoreCase))
  1488. {
  1489. contentFeatures = "DLNA.ORG_PN=AVI";
  1490. }
  1491. else if (string.Equals(extension, ".mkv", StringComparison.OrdinalIgnoreCase))
  1492. {
  1493. contentFeatures = "DLNA.ORG_PN=MATROSKA";
  1494. }
  1495. else if (string.Equals(extension, ".mp4", StringComparison.OrdinalIgnoreCase))
  1496. {
  1497. contentFeatures = "DLNA.ORG_PN=AVC_MP4_MP_HD_720p_AAC";
  1498. }
  1499. else if (string.Equals(extension, ".mpeg", StringComparison.OrdinalIgnoreCase))
  1500. {
  1501. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1502. }
  1503. else if (string.Equals(extension, ".ts", StringComparison.OrdinalIgnoreCase))
  1504. {
  1505. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1506. }
  1507. if (!string.IsNullOrEmpty(contentFeatures))
  1508. {
  1509. responseHeaders["contentFeatures.dlna.org"] = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
  1510. }
  1511. foreach (var item in responseHeaders)
  1512. {
  1513. Request.Response.AddHeader(item.Key, item.Value);
  1514. }
  1515. }
  1516. [Flags]
  1517. private enum DlnaFlags
  1518. {
  1519. DLNA_ORG_FLAG_SENDER_PACED = (1 << 31),
  1520. DLNA_ORG_FLAG_TIME_BASED_SEEK = (1 << 30),
  1521. DLNA_ORG_FLAG_BYTE_BASED_SEEK = (1 << 29),
  1522. DLNA_ORG_FLAG_PLAY_CONTAINER = (1 << 28),
  1523. DLNA_ORG_FLAG_S0_INCREASE = (1 << 27),
  1524. DLNA_ORG_FLAG_SN_INCREASE = (1 << 26),
  1525. DLNA_ORG_FLAG_RTSP_PAUSE = (1 << 25),
  1526. DLNA_ORG_FLAG_STREAMING_TRANSFER_MODE = (1 << 24),
  1527. DLNA_ORG_FLAG_INTERACTIVE_TRANSFERT_MODE = (1 << 23),
  1528. DLNA_ORG_FLAG_BACKGROUND_TRANSFERT_MODE = (1 << 22),
  1529. DLNA_ORG_FLAG_CONNECTION_STALL = (1 << 21),
  1530. DLNA_ORG_FLAG_DLNA_V15 = (1 << 20),
  1531. };
  1532. private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
  1533. {
  1534. var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
  1535. var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
  1536. responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
  1537. responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
  1538. }
  1539. /// <summary>
  1540. /// Enforces the resolution limit.
  1541. /// </summary>
  1542. /// <param name="state">The state.</param>
  1543. /// <param name="videoRequest">The video request.</param>
  1544. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1545. {
  1546. // If enabled, allow whatever the client asks for
  1547. if (ServerConfigurationManager.Configuration.AllowVideoUpscaling)
  1548. {
  1549. return;
  1550. }
  1551. // Switch the incoming params to be ceilings rather than fixed values
  1552. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1553. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1554. videoRequest.Width = null;
  1555. videoRequest.Height = null;
  1556. }
  1557. protected string GetInputModifier(StreamState state)
  1558. {
  1559. var inputModifier = string.Empty;
  1560. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  1561. inputModifier += " " + probeSize;
  1562. inputModifier = inputModifier.Trim();
  1563. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  1564. inputModifier = inputModifier.Trim();
  1565. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1566. inputModifier = inputModifier.Trim();
  1567. if (state.VideoRequest != null)
  1568. {
  1569. inputModifier += " -fflags genpts";
  1570. }
  1571. if (!string.IsNullOrEmpty(state.InputFormat))
  1572. {
  1573. inputModifier += " -f " + state.InputFormat;
  1574. }
  1575. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  1576. {
  1577. inputModifier += " -vcodec " + state.InputVideoCodec;
  1578. }
  1579. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  1580. {
  1581. inputModifier += " -acodec " + state.InputAudioCodec;
  1582. }
  1583. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1584. {
  1585. inputModifier += " -async " + state.InputAudioSync;
  1586. }
  1587. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1588. {
  1589. inputModifier += " -vsync " + state.InputVideoSync;
  1590. }
  1591. if (state.ReadInputAtNativeFramerate)
  1592. {
  1593. inputModifier += " -re";
  1594. }
  1595. return inputModifier;
  1596. }
  1597. /// <summary>
  1598. /// Infers the audio codec based on the url
  1599. /// </summary>
  1600. /// <param name="url">The URL.</param>
  1601. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1602. private string InferAudioCodec(string url)
  1603. {
  1604. var ext = Path.GetExtension(url);
  1605. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1606. {
  1607. return "mp3";
  1608. }
  1609. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1610. {
  1611. return "aac";
  1612. }
  1613. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1614. {
  1615. return "wma";
  1616. }
  1617. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1618. {
  1619. return "vorbis";
  1620. }
  1621. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1622. {
  1623. return "vorbis";
  1624. }
  1625. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1626. {
  1627. return "vorbis";
  1628. }
  1629. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1630. {
  1631. return "vorbis";
  1632. }
  1633. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1634. {
  1635. return "vorbis";
  1636. }
  1637. return "copy";
  1638. }
  1639. /// <summary>
  1640. /// Infers the video codec.
  1641. /// </summary>
  1642. /// <param name="url">The URL.</param>
  1643. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1644. private string InferVideoCodec(string url)
  1645. {
  1646. var ext = Path.GetExtension(url);
  1647. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1648. {
  1649. return "wmv";
  1650. }
  1651. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1652. {
  1653. return "vpx";
  1654. }
  1655. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1656. {
  1657. return "theora";
  1658. }
  1659. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1660. {
  1661. return "h264";
  1662. }
  1663. return "copy";
  1664. }
  1665. }
  1666. }