BaseStreamingService.cs 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Dlna;
  5. using MediaBrowser.Controller.Dto;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Controller.MediaEncoding;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.Dlna;
  13. using MediaBrowser.Model.Drawing;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Library;
  17. using MediaBrowser.Model.LiveTv;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Diagnostics;
  21. using System.Globalization;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Text;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. namespace MediaBrowser.Api.Playback
  28. {
  29. /// <summary>
  30. /// Class BaseStreamingService
  31. /// </summary>
  32. public abstract class BaseStreamingService : BaseApiService
  33. {
  34. /// <summary>
  35. /// Gets or sets the application paths.
  36. /// </summary>
  37. /// <value>The application paths.</value>
  38. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  39. /// <summary>
  40. /// Gets or sets the user manager.
  41. /// </summary>
  42. /// <value>The user manager.</value>
  43. protected IUserManager UserManager { get; private set; }
  44. /// <summary>
  45. /// Gets or sets the library manager.
  46. /// </summary>
  47. /// <value>The library manager.</value>
  48. protected ILibraryManager LibraryManager { get; private set; }
  49. /// <summary>
  50. /// Gets or sets the iso manager.
  51. /// </summary>
  52. /// <value>The iso manager.</value>
  53. protected IIsoManager IsoManager { get; private set; }
  54. /// <summary>
  55. /// Gets or sets the media encoder.
  56. /// </summary>
  57. /// <value>The media encoder.</value>
  58. protected IMediaEncoder MediaEncoder { get; private set; }
  59. protected IEncodingManager EncodingManager { get; private set; }
  60. protected IDtoService DtoService { get; private set; }
  61. protected IFileSystem FileSystem { get; private set; }
  62. protected IItemRepository ItemRepository { get; private set; }
  63. protected ILiveTvManager LiveTvManager { get; private set; }
  64. protected IDlnaManager DlnaManager { get; private set; }
  65. /// <summary>
  66. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  67. /// </summary>
  68. /// <param name="serverConfig">The server configuration.</param>
  69. /// <param name="userManager">The user manager.</param>
  70. /// <param name="libraryManager">The library manager.</param>
  71. /// <param name="isoManager">The iso manager.</param>
  72. /// <param name="mediaEncoder">The media encoder.</param>
  73. /// <param name="dtoService">The dto service.</param>
  74. /// <param name="fileSystem">The file system.</param>
  75. /// <param name="itemRepository">The item repository.</param>
  76. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager, IEncodingManager encodingManager, IDlnaManager dlnaManager)
  77. {
  78. DlnaManager = dlnaManager;
  79. EncodingManager = encodingManager;
  80. LiveTvManager = liveTvManager;
  81. ItemRepository = itemRepository;
  82. FileSystem = fileSystem;
  83. DtoService = dtoService;
  84. ServerConfigurationManager = serverConfig;
  85. UserManager = userManager;
  86. LibraryManager = libraryManager;
  87. IsoManager = isoManager;
  88. MediaEncoder = mediaEncoder;
  89. }
  90. /// <summary>
  91. /// Gets the command line arguments.
  92. /// </summary>
  93. /// <param name="outputPath">The output path.</param>
  94. /// <param name="state">The state.</param>
  95. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  96. /// <returns>System.String.</returns>
  97. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions);
  98. /// <summary>
  99. /// Gets the type of the transcoding job.
  100. /// </summary>
  101. /// <value>The type of the transcoding job.</value>
  102. protected abstract TranscodingJobType TranscodingJobType { get; }
  103. /// <summary>
  104. /// Gets the output file extension.
  105. /// </summary>
  106. /// <param name="state">The state.</param>
  107. /// <returns>System.String.</returns>
  108. protected virtual string GetOutputFileExtension(StreamState state)
  109. {
  110. return Path.GetExtension(state.RequestedUrl);
  111. }
  112. /// <summary>
  113. /// Gets the output file path.
  114. /// </summary>
  115. /// <param name="state">The state.</param>
  116. /// <returns>System.String.</returns>
  117. protected virtual string GetOutputFilePath(StreamState state)
  118. {
  119. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  120. var outputFileExtension = GetOutputFileExtension(state);
  121. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  122. }
  123. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  124. /// <summary>
  125. /// The fast seek offset seconds
  126. /// </summary>
  127. private const int FastSeekOffsetSeconds = 1;
  128. /// <summary>
  129. /// Gets the fast seek command line parameter.
  130. /// </summary>
  131. /// <param name="request">The request.</param>
  132. /// <returns>System.String.</returns>
  133. /// <value>The fast seek command line parameter.</value>
  134. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  135. {
  136. var time = request.StartTimeTicks;
  137. if (time.HasValue)
  138. {
  139. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds;
  140. if (seconds > 0)
  141. {
  142. return string.Format("-ss {0}", seconds.ToString(UsCulture));
  143. }
  144. }
  145. return string.Empty;
  146. }
  147. /// <summary>
  148. /// Gets the slow seek command line parameter.
  149. /// </summary>
  150. /// <param name="request">The request.</param>
  151. /// <returns>System.String.</returns>
  152. /// <value>The slow seek command line parameter.</value>
  153. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  154. {
  155. return string.Empty;
  156. }
  157. /// <summary>
  158. /// Gets the map args.
  159. /// </summary>
  160. /// <param name="state">The state.</param>
  161. /// <returns>System.String.</returns>
  162. protected virtual string GetMapArgs(StreamState state)
  163. {
  164. var args = string.Empty;
  165. if (!state.HasMediaStreams)
  166. {
  167. return state.IsInputVideo ? "-sn" : string.Empty;
  168. }
  169. if (state.VideoStream != null)
  170. {
  171. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  172. }
  173. else
  174. {
  175. args += "-map -0:v";
  176. }
  177. if (state.AudioStream != null)
  178. {
  179. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  180. }
  181. else
  182. {
  183. args += " -map -0:a";
  184. }
  185. if (state.SubtitleStream == null)
  186. {
  187. args += " -map -0:s";
  188. }
  189. return args;
  190. }
  191. /// <summary>
  192. /// Determines which stream will be used for playback
  193. /// </summary>
  194. /// <param name="allStream">All stream.</param>
  195. /// <param name="desiredIndex">Index of the desired.</param>
  196. /// <param name="type">The type.</param>
  197. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  198. /// <returns>MediaStream.</returns>
  199. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  200. {
  201. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  202. if (desiredIndex.HasValue)
  203. {
  204. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  205. if (stream != null)
  206. {
  207. return stream;
  208. }
  209. }
  210. if (type == MediaStreamType.Video)
  211. {
  212. streams = streams.Where(i => !string.Equals(i.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)).ToList();
  213. }
  214. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  215. {
  216. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  217. streams.FirstOrDefault();
  218. }
  219. // Just return the first one
  220. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  221. }
  222. protected EncodingQuality GetQualitySetting()
  223. {
  224. var quality = ServerConfigurationManager.Configuration.MediaEncodingQuality;
  225. if (quality == EncodingQuality.Auto)
  226. {
  227. var cpuCount = Environment.ProcessorCount;
  228. if (cpuCount >= 4)
  229. {
  230. //return EncodingQuality.HighQuality;
  231. }
  232. return EncodingQuality.HighSpeed;
  233. }
  234. return quality;
  235. }
  236. /// <summary>
  237. /// Gets the number of threads.
  238. /// </summary>
  239. /// <returns>System.Int32.</returns>
  240. /// <exception cref="System.Exception">Unrecognized MediaEncodingQuality value.</exception>
  241. protected int GetNumberOfThreads(StreamState state, bool isWebm)
  242. {
  243. // Use more when this is true. -re will keep cpu usage under control
  244. if (state.ReadInputAtNativeFramerate)
  245. {
  246. if (isWebm)
  247. {
  248. return Math.Max(Environment.ProcessorCount - 1, 2);
  249. }
  250. return 0;
  251. }
  252. // Webm: http://www.webmproject.org/docs/encoder-parameters/
  253. // The decoder will usually automatically use an appropriate number of threads according to how many cores are available but it can only use multiple threads
  254. // for the coefficient data if the encoder selected --token-parts > 0 at encode time.
  255. switch (GetQualitySetting())
  256. {
  257. case EncodingQuality.HighSpeed:
  258. return 2;
  259. case EncodingQuality.HighQuality:
  260. return 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, "transcode-" + 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. if (!string.IsNullOrWhiteSpace(request.AudioCodec))
  1130. {
  1131. state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  1132. state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault();
  1133. }
  1134. var item = string.IsNullOrEmpty(request.MediaSourceId) ?
  1135. DtoService.GetItemByDtoId(request.Id) :
  1136. DtoService.GetItemByDtoId(request.MediaSourceId);
  1137. if (user != null && item.GetPlayAccess(user) != PlayAccess.Full)
  1138. {
  1139. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  1140. }
  1141. if (item is ILiveTvRecording)
  1142. {
  1143. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  1144. state.VideoType = VideoType.VideoFile;
  1145. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1146. state.PlayableStreamFileNames = new List<string>();
  1147. var path = recording.RecordingInfo.Path;
  1148. var mediaUrl = recording.RecordingInfo.Url;
  1149. if (string.IsNullOrWhiteSpace(path) && string.IsNullOrWhiteSpace(mediaUrl))
  1150. {
  1151. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  1152. state.LiveTvStreamId = streamInfo.Id;
  1153. path = streamInfo.Path;
  1154. mediaUrl = streamInfo.Url;
  1155. }
  1156. if (!string.IsNullOrEmpty(path))
  1157. {
  1158. state.MediaPath = path;
  1159. state.IsRemote = false;
  1160. }
  1161. else if (!string.IsNullOrEmpty(mediaUrl))
  1162. {
  1163. state.MediaPath = mediaUrl;
  1164. state.IsRemote = true;
  1165. }
  1166. state.RunTimeTicks = recording.RunTimeTicks;
  1167. if (recording.RecordingInfo.Status == RecordingStatus.InProgress)
  1168. {
  1169. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1170. }
  1171. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  1172. state.AudioSync = "1000";
  1173. state.DeInterlace = true;
  1174. state.InputVideoSync = "-1";
  1175. state.InputAudioSync = "1";
  1176. }
  1177. else if (item is LiveTvChannel)
  1178. {
  1179. var channel = LiveTvManager.GetInternalChannel(request.Id);
  1180. state.VideoType = VideoType.VideoFile;
  1181. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1182. state.PlayableStreamFileNames = new List<string>();
  1183. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  1184. state.LiveTvStreamId = streamInfo.Id;
  1185. if (!string.IsNullOrEmpty(streamInfo.Path))
  1186. {
  1187. state.MediaPath = streamInfo.Path;
  1188. state.IsRemote = false;
  1189. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1190. }
  1191. else if (!string.IsNullOrEmpty(streamInfo.Url))
  1192. {
  1193. state.MediaPath = streamInfo.Url;
  1194. state.IsRemote = true;
  1195. }
  1196. state.ReadInputAtNativeFramerate = true;
  1197. state.AudioSync = "1000";
  1198. state.DeInterlace = true;
  1199. state.InputVideoSync = "-1";
  1200. state.InputAudioSync = "1";
  1201. }
  1202. else
  1203. {
  1204. state.MediaPath = item.Path;
  1205. state.IsRemote = item.LocationType == LocationType.Remote;
  1206. var video = item as Video;
  1207. if (video != null)
  1208. {
  1209. state.IsInputVideo = true;
  1210. state.VideoType = video.VideoType;
  1211. state.IsoType = video.IsoType;
  1212. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  1213. ? new List<string>()
  1214. : video.PlayableStreamFileNames.ToList();
  1215. }
  1216. state.RunTimeTicks = item.RunTimeTicks;
  1217. }
  1218. var videoRequest = request as VideoStreamRequest;
  1219. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  1220. {
  1221. ItemId = item.Id
  1222. }).ToList();
  1223. if (videoRequest != null)
  1224. {
  1225. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  1226. {
  1227. videoRequest.VideoCodec = InferVideoCodec(url);
  1228. }
  1229. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1230. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1231. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1232. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  1233. {
  1234. state.DeInterlace = true;
  1235. }
  1236. EnforceResolutionLimit(state, videoRequest);
  1237. }
  1238. else
  1239. {
  1240. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1241. }
  1242. state.HasMediaStreams = mediaStreams.Count > 0;
  1243. state.SegmentLength = state.ReadInputAtNativeFramerate ? 5 : 10;
  1244. state.HlsListSize = state.ReadInputAtNativeFramerate ? 100 : 1440;
  1245. ApplyDeviceProfileSettings(state);
  1246. if (videoRequest != null)
  1247. {
  1248. if (state.VideoStream != null && CanStreamCopyVideo(videoRequest, state.VideoStream))
  1249. {
  1250. videoRequest.VideoCodec = "copy";
  1251. }
  1252. if (state.AudioStream != null && CanStreamCopyAudio(request, state.AudioStream, state.SupportedAudioCodecs))
  1253. {
  1254. request.AudioCodec = "copy";
  1255. }
  1256. }
  1257. return state;
  1258. }
  1259. private bool CanStreamCopyVideo(VideoStreamRequest request, MediaStream videoStream)
  1260. {
  1261. if (videoStream.IsInterlaced)
  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 request.EnableAutoStreamCopy;
  1326. }
  1327. private bool CanStreamCopyAudio(StreamRequest request, MediaStream audioStream, List<string> supportedAudioCodecs)
  1328. {
  1329. // Source and target codecs must match
  1330. if (string.IsNullOrEmpty(audioStream.Codec) || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.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 true;
  1360. }
  1361. private void ApplyDeviceProfileSettings(StreamState state)
  1362. {
  1363. var headers = new Dictionary<string, string>();
  1364. foreach (var key in Request.Headers.AllKeys)
  1365. {
  1366. headers[key] = Request.Headers[key];
  1367. }
  1368. var profile = string.IsNullOrWhiteSpace(state.Request.DeviceProfileId) ?
  1369. DlnaManager.GetProfile(headers) :
  1370. DlnaManager.GetProfile(state.Request.DeviceProfileId);
  1371. if (profile == null)
  1372. {
  1373. // Don't use settings from the default profile.
  1374. // Only use a specific profile if it was requested.
  1375. return;
  1376. }
  1377. var container = Path.GetExtension(state.RequestedUrl);
  1378. if (string.IsNullOrEmpty(container))
  1379. {
  1380. container = Path.GetExtension(GetOutputFilePath(state));
  1381. }
  1382. var audioCodec = state.Request.AudioCodec;
  1383. if (string.Equals(audioCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.AudioStream != null)
  1384. {
  1385. audioCodec = state.AudioStream.Codec;
  1386. }
  1387. var videoCodec = state.VideoRequest == null ? null : state.VideoRequest.VideoCodec;
  1388. if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.VideoStream != null)
  1389. {
  1390. videoCodec = state.VideoStream.Codec;
  1391. }
  1392. var mediaProfile = state.VideoRequest == null ?
  1393. profile.GetAudioMediaProfile(container, audioCodec, state.AudioStream) :
  1394. profile.GetVideoMediaProfile(container, audioCodec, videoCodec, state.AudioStream, state.VideoStream);
  1395. if (mediaProfile != null)
  1396. {
  1397. state.MimeType = mediaProfile.MimeType;
  1398. state.OrgPn = mediaProfile.OrgPn;
  1399. }
  1400. var transcodingProfile = state.VideoRequest == null ?
  1401. profile.GetAudioTranscodingProfile(container, audioCodec) :
  1402. profile.GetVideoTranscodingProfile(container, audioCodec, videoCodec);
  1403. if (transcodingProfile != null)
  1404. {
  1405. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  1406. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  1407. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  1408. if (state.VideoRequest != null && string.IsNullOrWhiteSpace(state.VideoRequest.Profile))
  1409. {
  1410. state.VideoRequest.Profile = transcodingProfile.VideoProfile;
  1411. }
  1412. }
  1413. }
  1414. /// <summary>
  1415. /// Adds the dlna headers.
  1416. /// </summary>
  1417. /// <param name="state">The state.</param>
  1418. /// <param name="responseHeaders">The response headers.</param>
  1419. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  1420. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1421. protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  1422. {
  1423. var transferMode = GetHeader("transferMode.dlna.org");
  1424. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  1425. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  1426. var contentFeatures = string.Empty;
  1427. var extension = GetOutputFileExtension(state);
  1428. // 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
  1429. var orgOp = ";DLNA.ORG_OP=";
  1430. if (state.RunTimeTicks.HasValue)
  1431. {
  1432. // Time-based seeking currently only possible when transcoding
  1433. orgOp += isStaticallyStreamed ? "0" : "1";
  1434. // Byte-based seeking only possible when not transcoding
  1435. orgOp += isStaticallyStreamed || state.TranscodeSeekInfo == TranscodeSeekInfo.Bytes ? "1" : "0";
  1436. if (!isStaticallyStreamed)
  1437. {
  1438. AddTimeSeekResponseHeaders(state, responseHeaders);
  1439. }
  1440. }
  1441. else
  1442. {
  1443. // No seeking is available if we don't know the content runtime
  1444. orgOp += "00";
  1445. }
  1446. // 0 = native, 1 = transcoded
  1447. var orgCi = isStaticallyStreamed ? ";DLNA.ORG_CI=0" : ";DLNA.ORG_CI=1";
  1448. var flagValue = DlnaFlags.DLNA_ORG_FLAG_STREAMING_TRANSFER_MODE |
  1449. DlnaFlags.DLNA_ORG_FLAG_BACKGROUND_TRANSFERT_MODE |
  1450. DlnaFlags.DLNA_ORG_FLAG_DLNA_V15;
  1451. if (isStaticallyStreamed)
  1452. {
  1453. //flagValue = flagValue | DlnaFlags.DLNA_ORG_FLAG_BYTE_BASED_SEEK;
  1454. }
  1455. else if (state.RunTimeTicks.HasValue)
  1456. {
  1457. //flagValue = flagValue | DlnaFlags.DLNA_ORG_FLAG_TIME_BASED_SEEK;
  1458. }
  1459. var dlnaflags = string.Format(";DLNA.ORG_FLAGS={0}000000000000000000000000",
  1460. Enum.Format(typeof(DlnaFlags), flagValue, "x"));
  1461. if (!string.IsNullOrWhiteSpace(state.OrgPn))
  1462. {
  1463. contentFeatures = "DLNA.ORG_PN=" + state.OrgPn;
  1464. }
  1465. else if (string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase))
  1466. {
  1467. contentFeatures = "DLNA.ORG_PN=MP3";
  1468. }
  1469. else if (string.Equals(extension, ".aac", StringComparison.OrdinalIgnoreCase))
  1470. {
  1471. contentFeatures = "DLNA.ORG_PN=AAC_ISO";
  1472. }
  1473. else if (string.Equals(extension, ".wma", StringComparison.OrdinalIgnoreCase))
  1474. {
  1475. contentFeatures = "DLNA.ORG_PN=WMABASE";
  1476. }
  1477. else if (string.Equals(extension, ".avi", StringComparison.OrdinalIgnoreCase))
  1478. {
  1479. contentFeatures = "DLNA.ORG_PN=AVI";
  1480. }
  1481. else if (string.Equals(extension, ".mkv", StringComparison.OrdinalIgnoreCase))
  1482. {
  1483. contentFeatures = "DLNA.ORG_PN=MATROSKA";
  1484. }
  1485. else if (string.Equals(extension, ".mp4", StringComparison.OrdinalIgnoreCase))
  1486. {
  1487. contentFeatures = "DLNA.ORG_PN=AVC_MP4_MP_HD_720p_AAC";
  1488. }
  1489. else if (string.Equals(extension, ".mpeg", StringComparison.OrdinalIgnoreCase))
  1490. {
  1491. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1492. }
  1493. else if (string.Equals(extension, ".ts", StringComparison.OrdinalIgnoreCase))
  1494. {
  1495. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1496. }
  1497. if (!string.IsNullOrEmpty(contentFeatures))
  1498. {
  1499. responseHeaders["contentFeatures.dlna.org"] = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
  1500. }
  1501. foreach (var item in responseHeaders)
  1502. {
  1503. Request.Response.AddHeader(item.Key, item.Value);
  1504. }
  1505. }
  1506. [Flags]
  1507. private enum DlnaFlags
  1508. {
  1509. DLNA_ORG_FLAG_SENDER_PACED = (1 << 31),
  1510. DLNA_ORG_FLAG_TIME_BASED_SEEK = (1 << 30),
  1511. DLNA_ORG_FLAG_BYTE_BASED_SEEK = (1 << 29),
  1512. DLNA_ORG_FLAG_PLAY_CONTAINER = (1 << 28),
  1513. DLNA_ORG_FLAG_S0_INCREASE = (1 << 27),
  1514. DLNA_ORG_FLAG_SN_INCREASE = (1 << 26),
  1515. DLNA_ORG_FLAG_RTSP_PAUSE = (1 << 25),
  1516. DLNA_ORG_FLAG_STREAMING_TRANSFER_MODE = (1 << 24),
  1517. DLNA_ORG_FLAG_INTERACTIVE_TRANSFERT_MODE = (1 << 23),
  1518. DLNA_ORG_FLAG_BACKGROUND_TRANSFERT_MODE = (1 << 22),
  1519. DLNA_ORG_FLAG_CONNECTION_STALL = (1 << 21),
  1520. DLNA_ORG_FLAG_DLNA_V15 = (1 << 20),
  1521. };
  1522. private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
  1523. {
  1524. var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
  1525. var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
  1526. responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
  1527. responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
  1528. }
  1529. /// <summary>
  1530. /// Enforces the resolution limit.
  1531. /// </summary>
  1532. /// <param name="state">The state.</param>
  1533. /// <param name="videoRequest">The video request.</param>
  1534. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1535. {
  1536. // If enabled, allow whatever the client asks for
  1537. if (ServerConfigurationManager.Configuration.AllowVideoUpscaling)
  1538. {
  1539. return;
  1540. }
  1541. // Switch the incoming params to be ceilings rather than fixed values
  1542. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1543. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1544. videoRequest.Width = null;
  1545. videoRequest.Height = null;
  1546. }
  1547. protected string GetInputModifier(StreamState state)
  1548. {
  1549. var inputModifier = string.Empty;
  1550. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  1551. inputModifier += " " + probeSize;
  1552. inputModifier = inputModifier.Trim();
  1553. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  1554. inputModifier = inputModifier.Trim();
  1555. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1556. inputModifier = inputModifier.Trim();
  1557. if (state.VideoRequest != null)
  1558. {
  1559. inputModifier += " -fflags genpts";
  1560. }
  1561. if (!string.IsNullOrEmpty(state.InputFormat))
  1562. {
  1563. inputModifier += " -f " + state.InputFormat;
  1564. }
  1565. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  1566. {
  1567. inputModifier += " -vcodec " + state.InputVideoCodec;
  1568. }
  1569. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  1570. {
  1571. inputModifier += " -acodec " + state.InputAudioCodec;
  1572. }
  1573. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1574. {
  1575. inputModifier += " -async " + state.InputAudioSync;
  1576. }
  1577. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1578. {
  1579. inputModifier += " -vsync " + state.InputVideoSync;
  1580. }
  1581. if (state.ReadInputAtNativeFramerate)
  1582. {
  1583. inputModifier += " -re";
  1584. }
  1585. return inputModifier;
  1586. }
  1587. /// <summary>
  1588. /// Infers the audio codec based on the url
  1589. /// </summary>
  1590. /// <param name="url">The URL.</param>
  1591. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1592. private string InferAudioCodec(string url)
  1593. {
  1594. var ext = Path.GetExtension(url);
  1595. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1596. {
  1597. return "mp3";
  1598. }
  1599. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1600. {
  1601. return "aac";
  1602. }
  1603. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1604. {
  1605. return "wma";
  1606. }
  1607. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1608. {
  1609. return "vorbis";
  1610. }
  1611. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1612. {
  1613. return "vorbis";
  1614. }
  1615. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1616. {
  1617. return "vorbis";
  1618. }
  1619. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1620. {
  1621. return "vorbis";
  1622. }
  1623. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1624. {
  1625. return "vorbis";
  1626. }
  1627. return "copy";
  1628. }
  1629. /// <summary>
  1630. /// Infers the video codec.
  1631. /// </summary>
  1632. /// <param name="url">The URL.</param>
  1633. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1634. private string InferVideoCodec(string url)
  1635. {
  1636. var ext = Path.GetExtension(url);
  1637. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1638. {
  1639. return "wmv";
  1640. }
  1641. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1642. {
  1643. return "vpx";
  1644. }
  1645. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1646. {
  1647. return "theora";
  1648. }
  1649. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1650. {
  1651. return "h264";
  1652. }
  1653. return "copy";
  1654. }
  1655. }
  1656. }