BaseStreamingService.cs 81 KB

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