BaseStreamingService.cs 79 KB

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