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