BaseStreamingService.cs 81 KB

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