BaseStreamingService.cs 84 KB

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