BaseStreamingService.cs 83 KB

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