EncodingHelper.cs 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Extensions;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.Dlna;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.MediaInfo;
  16. using Microsoft.Extensions.Configuration;
  17. namespace MediaBrowser.Controller.MediaEncoding
  18. {
  19. public class EncodingHelper
  20. {
  21. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  22. private readonly IMediaEncoder _mediaEncoder;
  23. private readonly IFileSystem _fileSystem;
  24. private readonly ISubtitleEncoder _subtitleEncoder;
  25. private readonly IConfiguration _configuration;
  26. private static readonly string[] _videoProfiles = new[]
  27. {
  28. "ConstrainedBaseline",
  29. "Baseline",
  30. "Extended",
  31. "Main",
  32. "High",
  33. "ProgressiveHigh",
  34. "ConstrainedHigh"
  35. };
  36. public EncodingHelper(
  37. IMediaEncoder mediaEncoder,
  38. IFileSystem fileSystem,
  39. ISubtitleEncoder subtitleEncoder,
  40. IConfiguration configuration)
  41. {
  42. _mediaEncoder = mediaEncoder;
  43. _fileSystem = fileSystem;
  44. _subtitleEncoder = subtitleEncoder;
  45. _configuration = configuration;
  46. }
  47. public string GetH264Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  48. => GetH264OrH265Encoder("libx264", "h264", state, encodingOptions);
  49. public string GetH265Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  50. => GetH264OrH265Encoder("libx265", "hevc", state, encodingOptions);
  51. private string GetH264OrH265Encoder(string defaultEncoder, string hwEncoder, EncodingJobInfo state, EncodingOptions encodingOptions)
  52. {
  53. // Only use alternative encoders for video files.
  54. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  55. // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
  56. if (state.VideoType == VideoType.VideoFile)
  57. {
  58. var hwType = encodingOptions.HardwareAccelerationType;
  59. var codecMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
  60. {
  61. {"qsv", hwEncoder + "_qsv"},
  62. {hwEncoder + "_qsv", hwEncoder + "_qsv"},
  63. {"nvenc", hwEncoder + "_nvenc"},
  64. {"amf", hwEncoder + "_amf"},
  65. {"omx", hwEncoder + "_omx"},
  66. {hwEncoder + "_v4l2m2m", hwEncoder + "_v4l2m2m"},
  67. {"mediacodec", hwEncoder + "_mediacodec"},
  68. {"vaapi", hwEncoder + "_vaapi"}
  69. };
  70. if (!string.IsNullOrEmpty(hwType)
  71. && encodingOptions.EnableHardwareEncoding
  72. && codecMap.ContainsKey(hwType))
  73. {
  74. var preferredEncoder = codecMap[hwType];
  75. if (_mediaEncoder.SupportsEncoder(preferredEncoder))
  76. {
  77. return preferredEncoder;
  78. }
  79. }
  80. }
  81. return defaultEncoder;
  82. }
  83. private bool IsVaapiSupported(EncodingJobInfo state)
  84. {
  85. var videoStream = state.VideoStream;
  86. // vaapi will throw an error with this input
  87. // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
  88. if (string.Equals(videoStream?.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  89. {
  90. return false;
  91. }
  92. if (!_mediaEncoder.SupportsHwaccel("vaapi"))
  93. {
  94. return false;
  95. }
  96. return true;
  97. }
  98. /// <summary>
  99. /// Gets the name of the output video codec
  100. /// </summary>
  101. public string GetVideoEncoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  102. {
  103. var codec = state.OutputVideoCodec;
  104. if (!string.IsNullOrEmpty(codec))
  105. {
  106. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  107. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
  108. {
  109. return GetH265Encoder(state, encodingOptions);
  110. }
  111. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  112. {
  113. return GetH264Encoder(state, encodingOptions);
  114. }
  115. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  116. {
  117. return "libvpx";
  118. }
  119. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  120. {
  121. return "wmv2";
  122. }
  123. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  124. {
  125. return "libtheora";
  126. }
  127. return codec.ToLowerInvariant();
  128. }
  129. return "copy";
  130. }
  131. /// <summary>
  132. /// Gets the user agent param.
  133. /// </summary>
  134. /// <param name="state">The state.</param>
  135. /// <returns>System.String.</returns>
  136. public string GetUserAgentParam(EncodingJobInfo state)
  137. {
  138. if (state.RemoteHttpHeaders.TryGetValue("User-Agent", out string useragent))
  139. {
  140. return "-user_agent \"" + useragent + "\"";
  141. }
  142. return string.Empty;
  143. }
  144. public static string GetInputFormat(string container)
  145. {
  146. if (string.IsNullOrEmpty(container))
  147. {
  148. return null;
  149. }
  150. container = container.Replace("mkv", "matroska", StringComparison.OrdinalIgnoreCase);
  151. if (string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
  152. {
  153. return "mpegts";
  154. }
  155. // For these need to find out the ffmpeg names
  156. if (string.Equals(container, "m2ts", StringComparison.OrdinalIgnoreCase))
  157. {
  158. return null;
  159. }
  160. if (string.Equals(container, "wmv", StringComparison.OrdinalIgnoreCase))
  161. {
  162. return null;
  163. }
  164. if (string.Equals(container, "mts", StringComparison.OrdinalIgnoreCase))
  165. {
  166. return null;
  167. }
  168. if (string.Equals(container, "vob", StringComparison.OrdinalIgnoreCase))
  169. {
  170. return null;
  171. }
  172. if (string.Equals(container, "mpg", StringComparison.OrdinalIgnoreCase))
  173. {
  174. return null;
  175. }
  176. if (string.Equals(container, "mpeg", StringComparison.OrdinalIgnoreCase))
  177. {
  178. return null;
  179. }
  180. if (string.Equals(container, "rec", StringComparison.OrdinalIgnoreCase))
  181. {
  182. return null;
  183. }
  184. if (string.Equals(container, "dvr-ms", StringComparison.OrdinalIgnoreCase))
  185. {
  186. return null;
  187. }
  188. if (string.Equals(container, "ogm", StringComparison.OrdinalIgnoreCase))
  189. {
  190. return null;
  191. }
  192. if (string.Equals(container, "divx", StringComparison.OrdinalIgnoreCase))
  193. {
  194. return null;
  195. }
  196. if (string.Equals(container, "tp", StringComparison.OrdinalIgnoreCase))
  197. {
  198. return null;
  199. }
  200. if (string.Equals(container, "rmvb", StringComparison.OrdinalIgnoreCase))
  201. {
  202. return null;
  203. }
  204. if (string.Equals(container, "rtp", StringComparison.OrdinalIgnoreCase))
  205. {
  206. return null;
  207. }
  208. // Seeing reported failures here, not sure yet if this is related to specfying input format
  209. if (string.Equals(container, "m4v", StringComparison.OrdinalIgnoreCase))
  210. {
  211. return null;
  212. }
  213. // obviously don't do this for strm files
  214. if (string.Equals(container, "strm", StringComparison.OrdinalIgnoreCase))
  215. {
  216. return null;
  217. }
  218. return container;
  219. }
  220. public string GetDecoderFromCodec(string codec)
  221. {
  222. // For these need to find out the ffmpeg names
  223. if (string.Equals(codec, "mp2", StringComparison.OrdinalIgnoreCase))
  224. {
  225. return null;
  226. }
  227. if (string.Equals(codec, "aac_latm", StringComparison.OrdinalIgnoreCase))
  228. {
  229. return null;
  230. }
  231. if (string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
  232. {
  233. return null;
  234. }
  235. if (_mediaEncoder.SupportsDecoder(codec))
  236. {
  237. return codec;
  238. }
  239. return null;
  240. }
  241. /// <summary>
  242. /// Infers the audio codec based on the url
  243. /// </summary>
  244. public string InferAudioCodec(string container)
  245. {
  246. var ext = "." + (container ?? string.Empty);
  247. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  248. {
  249. return "mp3";
  250. }
  251. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  252. {
  253. return "aac";
  254. }
  255. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  256. {
  257. return "wma";
  258. }
  259. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  260. {
  261. return "vorbis";
  262. }
  263. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  264. {
  265. return "vorbis";
  266. }
  267. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  268. {
  269. return "vorbis";
  270. }
  271. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  272. {
  273. return "vorbis";
  274. }
  275. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  276. {
  277. return "vorbis";
  278. }
  279. return "copy";
  280. }
  281. /// <summary>
  282. /// Infers the video codec.
  283. /// </summary>
  284. /// <param name="url">The URL.</param>
  285. /// <returns>System.Nullable{VideoCodecs}.</returns>
  286. public string InferVideoCodec(string url)
  287. {
  288. var ext = Path.GetExtension(url);
  289. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  290. {
  291. return "wmv";
  292. }
  293. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  294. {
  295. return "vpx";
  296. }
  297. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  298. {
  299. return "theora";
  300. }
  301. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  302. {
  303. return "h264";
  304. }
  305. return "copy";
  306. }
  307. public int GetVideoProfileScore(string profile)
  308. {
  309. // strip spaces because they may be stripped out on the query string
  310. profile = profile.Replace(" ", "");
  311. return Array.FindIndex(_videoProfiles, x => string.Equals(x, profile, StringComparison.OrdinalIgnoreCase));
  312. }
  313. public string GetInputPathArgument(EncodingJobInfo state)
  314. {
  315. var protocol = state.InputProtocol;
  316. var mediaPath = state.MediaPath ?? string.Empty;
  317. string[] inputPath;
  318. if (state.IsInputVideo
  319. && !(state.VideoType == VideoType.Iso && state.IsoMount == null))
  320. {
  321. inputPath = MediaEncoderHelpers.GetInputArgument(
  322. _fileSystem,
  323. mediaPath,
  324. state.IsoMount,
  325. state.PlayableStreamFileNames);
  326. }
  327. else
  328. {
  329. inputPath = new[] { mediaPath };
  330. }
  331. return _mediaEncoder.GetInputArgument(inputPath, protocol);
  332. }
  333. /// <summary>
  334. /// Gets the audio encoder.
  335. /// </summary>
  336. /// <param name="state">The state.</param>
  337. /// <returns>System.String.</returns>
  338. public string GetAudioEncoder(EncodingJobInfo state)
  339. {
  340. var codec = state.OutputAudioCodec;
  341. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  342. {
  343. // Use libfdk_aac for better audio quality if using custom build of FFmpeg which has fdk_aac support
  344. if (_mediaEncoder.SupportsEncoder("libfdk_aac"))
  345. {
  346. return "libfdk_aac";
  347. }
  348. return "aac";
  349. }
  350. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  351. {
  352. return "libmp3lame";
  353. }
  354. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  355. {
  356. return "libvorbis";
  357. }
  358. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  359. {
  360. return "wmav2";
  361. }
  362. if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
  363. {
  364. return "libopus";
  365. }
  366. return codec.ToLowerInvariant();
  367. }
  368. /// <summary>
  369. /// Gets the input argument.
  370. /// </summary>
  371. public string GetInputArgument(EncodingJobInfo state, EncodingOptions encodingOptions)
  372. {
  373. var arg = new StringBuilder();
  374. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
  375. var outputVideoCodec = GetVideoEncoder(state, encodingOptions);
  376. if (state.IsVideoRequest && string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  377. {
  378. // While using VAAPI decoder
  379. if ((videoDecoder ?? string.Empty).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1)
  380. {
  381. arg.Append("-hwaccel_output_format vaapi")
  382. .Append(" -vaapi_device ")
  383. .Append(encodingOptions.VaapiDevice)
  384. .Append(" ");
  385. }
  386. // While using SW decoder and VAAPI encoder
  387. else if ((videoDecoder ?? string.Empty).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) == -1
  388. && (outputVideoCodec ?? string.Empty).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1)
  389. {
  390. arg.Append("-vaapi_device ")
  391. .Append(encodingOptions.VaapiDevice)
  392. .Append(" ");
  393. }
  394. }
  395. if (state.IsVideoRequest && string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  396. {
  397. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
  398. var outputVideoCodec = GetVideoEncoder(state, encodingOptions);
  399. var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  400. if (!hasTextSubs)
  401. {
  402. // While using QSV encoder
  403. if ((outputVideoCodec ?? string.Empty).IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1)
  404. {
  405. // While using QSV decoder
  406. if ((videoDecoder ?? string.Empty).IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1)
  407. {
  408. arg.Append("-hwaccel qsv ");
  409. }
  410. // While using SW decoder
  411. else
  412. {
  413. arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
  414. }
  415. }
  416. }
  417. }
  418. arg.Append("-i ")
  419. .Append(GetInputPathArgument(state));
  420. if (state.SubtitleStream != null
  421. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode
  422. && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  423. {
  424. var subtitlePath = state.SubtitleStream.Path;
  425. if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
  426. {
  427. var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
  428. if (File.Exists(idxFile))
  429. {
  430. subtitlePath = idxFile;
  431. }
  432. }
  433. arg.Append(" -i \"").Append(subtitlePath).Append('\"');
  434. }
  435. return arg.ToString();
  436. }
  437. /// <summary>
  438. /// Determines whether the specified stream is H264.
  439. /// </summary>
  440. /// <param name="stream">The stream.</param>
  441. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  442. public bool IsH264(MediaStream stream)
  443. {
  444. var codec = stream.Codec ?? string.Empty;
  445. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1
  446. || codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  447. }
  448. public bool IsH265(MediaStream stream)
  449. {
  450. var codec = stream.Codec ?? string.Empty;
  451. return codec.IndexOf("265", StringComparison.OrdinalIgnoreCase) != -1
  452. || codec.IndexOf("hevc", StringComparison.OrdinalIgnoreCase) != -1;
  453. }
  454. public string GetBitStreamArgs(MediaStream stream)
  455. {
  456. if (IsH264(stream))
  457. {
  458. return "-bsf:v h264_mp4toannexb";
  459. }
  460. else if (IsH265(stream))
  461. {
  462. return "-bsf:v hevc_mp4toannexb";
  463. }
  464. else
  465. {
  466. return null;
  467. }
  468. }
  469. public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec)
  470. {
  471. var bitrate = state.OutputVideoBitrate;
  472. if (bitrate.HasValue)
  473. {
  474. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  475. {
  476. // With vpx when crf is used, b:v becomes a max rate
  477. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide.
  478. return string.Format(
  479. CultureInfo.InvariantCulture,
  480. " -maxrate:v {0} -bufsize:v {1} -b:v {0}",
  481. bitrate.Value,
  482. bitrate.Value * 2);
  483. }
  484. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  485. {
  486. return string.Format(
  487. CultureInfo.InvariantCulture,
  488. " -b:v {0}",
  489. bitrate.Value);
  490. }
  491. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase) ||
  492. string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  493. {
  494. // h264
  495. return string.Format(
  496. CultureInfo.InvariantCulture,
  497. " -maxrate {0} -bufsize {1}",
  498. bitrate.Value,
  499. bitrate.Value * 2);
  500. }
  501. // h264
  502. return string.Format(
  503. CultureInfo.InvariantCulture,
  504. " -b:v {0} -maxrate {0} -bufsize {1}",
  505. bitrate.Value,
  506. bitrate.Value * 2);
  507. }
  508. return string.Empty;
  509. }
  510. public string NormalizeTranscodingLevel(string videoCodec, string level)
  511. {
  512. // Clients may direct play higher than level 41, but there's no reason to transcode higher
  513. if (double.TryParse(level, NumberStyles.Any, _usCulture, out double requestLevel)
  514. && requestLevel > 41
  515. && (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)
  516. || string.Equals(videoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  517. || string.Equals(videoCodec, "hevc", StringComparison.OrdinalIgnoreCase)))
  518. {
  519. return "41";
  520. }
  521. return level;
  522. }
  523. /// <summary>
  524. /// Gets the text subtitle param.
  525. /// </summary>
  526. /// <param name="state">The state.</param>
  527. /// <returns>System.String.</returns>
  528. public string GetTextSubtitleParam(EncodingJobInfo state)
  529. {
  530. var seconds = Math.Round(TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds);
  531. // hls always copies timestamps
  532. var setPtsParam = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive
  533. ? string.Empty
  534. : string.Format(CultureInfo.InvariantCulture, ",setpts=PTS -{0}/TB", seconds);
  535. // TODO
  536. // var fallbackFontPath = Path.Combine(_appPaths.ProgramDataPath, "fonts", "DroidSansFallback.ttf");
  537. // string fallbackFontParam = string.Empty;
  538. // if (!File.Exists(fallbackFontPath))
  539. // {
  540. // _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath));
  541. // using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf"))
  542. // {
  543. // using (var fileStream = new FileStream(fallbackFontPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  544. // {
  545. // stream.CopyTo(fileStream);
  546. // }
  547. // }
  548. // }
  549. // fallbackFontParam = string.Format(":force_style='FontName=Droid Sans Fallback':fontsdir='{0}'", _mediaEncoder.EscapeSubtitleFilterPath(_fileSystem.GetDirectoryName(fallbackFontPath)));
  550. if (state.SubtitleStream.IsExternal)
  551. {
  552. var subtitlePath = state.SubtitleStream.Path;
  553. var charsetParam = string.Empty;
  554. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  555. {
  556. var charenc = _subtitleEncoder.GetSubtitleFileCharacterSet(
  557. subtitlePath,
  558. state.SubtitleStream.Language,
  559. state.MediaSource.Protocol,
  560. CancellationToken.None).GetAwaiter().GetResult();
  561. if (!string.IsNullOrEmpty(charenc))
  562. {
  563. charsetParam = ":charenc=" + charenc;
  564. }
  565. }
  566. // TODO: Perhaps also use original_size=1920x800 ??
  567. return string.Format(
  568. CultureInfo.InvariantCulture,
  569. "subtitles=filename='{0}'{1}{2}",
  570. _mediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  571. charsetParam,
  572. // fallbackFontParam,
  573. setPtsParam);
  574. }
  575. var mediaPath = state.MediaPath ?? string.Empty;
  576. return string.Format(
  577. CultureInfo.InvariantCulture,
  578. "subtitles='{0}:si={1}'{2}",
  579. _mediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  580. state.InternalSubtitleStreamOffset.ToString(_usCulture),
  581. // fallbackFontParam,
  582. setPtsParam);
  583. }
  584. public double? GetFramerateParam(EncodingJobInfo state)
  585. {
  586. var request = state.BaseRequest;
  587. if (request.Framerate.HasValue)
  588. {
  589. return request.Framerate.Value;
  590. }
  591. var maxrate = request.MaxFramerate;
  592. if (maxrate.HasValue && state.VideoStream != null)
  593. {
  594. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  595. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  596. {
  597. return maxrate;
  598. }
  599. }
  600. return null;
  601. }
  602. /// <summary>
  603. /// Gets the video bitrate to specify on the command line
  604. /// </summary>
  605. public string GetVideoQualityParam(EncodingJobInfo state, string videoEncoder, EncodingOptions encodingOptions, string defaultPreset)
  606. {
  607. var param = string.Empty;
  608. var isVc1 = state.VideoStream != null &&
  609. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  610. var isLibX265 = string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase);
  611. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) || isLibX265)
  612. {
  613. if (!string.IsNullOrEmpty(encodingOptions.EncoderPreset))
  614. {
  615. param += "-preset " + encodingOptions.EncoderPreset;
  616. }
  617. else
  618. {
  619. param += "-preset " + defaultPreset;
  620. }
  621. int encodeCrf = encodingOptions.H264Crf;
  622. if (isLibX265)
  623. {
  624. encodeCrf = encodingOptions.H265Crf;
  625. }
  626. if (encodeCrf >= 0 && encodeCrf <= 51)
  627. {
  628. param += " -crf " + encodeCrf.ToString(CultureInfo.InvariantCulture);
  629. }
  630. else
  631. {
  632. string defaultCrf = "23";
  633. if (isLibX265)
  634. {
  635. defaultCrf = "28";
  636. }
  637. param += " -crf " + defaultCrf;
  638. }
  639. }
  640. else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)) // h264 (h264_qsv)
  641. {
  642. string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" };
  643. if (valid_h264_qsv.Contains(encodingOptions.EncoderPreset, StringComparer.OrdinalIgnoreCase))
  644. {
  645. param += "-preset " + encodingOptions.EncoderPreset;
  646. }
  647. else
  648. {
  649. param += "-preset 7";
  650. }
  651. param += " -look_ahead 0";
  652. }
  653. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc)
  654. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
  655. {
  656. switch (encodingOptions.EncoderPreset)
  657. {
  658. case "veryslow":
  659. param += "-preset slow"; //lossless is only supported on maxwell and newer(2014+)
  660. break;
  661. case "slow":
  662. case "slower":
  663. param += "-preset slow";
  664. break;
  665. case "medium":
  666. param += "-preset medium";
  667. break;
  668. case "fast":
  669. case "faster":
  670. case "veryfast":
  671. case "superfast":
  672. case "ultrafast":
  673. param += "-preset fast";
  674. break;
  675. default:
  676. param += "-preset default";
  677. break;
  678. }
  679. }
  680. else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase)) // webm
  681. {
  682. // Values 0-3, 0 being highest quality but slower
  683. var profileScore = 0;
  684. string crf;
  685. var qmin = "0";
  686. var qmax = "50";
  687. crf = "10";
  688. if (isVc1)
  689. {
  690. profileScore++;
  691. }
  692. // Max of 2
  693. profileScore = Math.Min(profileScore, 2);
  694. // http://www.webmproject.org/docs/encoder-parameters/
  695. param += string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  696. profileScore.ToString(_usCulture),
  697. crf,
  698. qmin,
  699. qmax);
  700. }
  701. else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
  702. {
  703. param += "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  704. }
  705. else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase)) // asf/wmv
  706. {
  707. param += "-qmin 2";
  708. }
  709. else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  710. {
  711. param += "-mbd 2";
  712. }
  713. param += GetVideoBitrateParam(state, videoEncoder);
  714. var framerate = GetFramerateParam(state);
  715. if (framerate.HasValue)
  716. {
  717. param += string.Format(" -r {0}", framerate.Value.ToString(_usCulture));
  718. }
  719. var targetVideoCodec = state.ActualOutputVideoCodec;
  720. var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault();
  721. // vaapi does not support Baseline profile, force Constrained Baseline in this case,
  722. // which is compatible (and ugly)
  723. if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  724. && profile != null
  725. && profile.IndexOf("baseline", StringComparison.OrdinalIgnoreCase) != -1)
  726. {
  727. profile = "constrained_baseline";
  728. }
  729. if (!string.IsNullOrEmpty(profile))
  730. {
  731. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  732. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  733. {
  734. // not supported by h264_omx
  735. param += " -profile:v " + profile;
  736. }
  737. }
  738. var level = state.GetRequestedLevel(targetVideoCodec);
  739. if (!string.IsNullOrEmpty(level))
  740. {
  741. level = NormalizeTranscodingLevel(state.OutputVideoCodec, level);
  742. // h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
  743. // also needed for libx264 due to https://trac.ffmpeg.org/ticket/3307
  744. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  745. || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  746. || string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  747. {
  748. switch (level)
  749. {
  750. case "30":
  751. param += " -level 3.0";
  752. break;
  753. case "31":
  754. param += " -level 3.1";
  755. break;
  756. case "32":
  757. param += " -level 3.2";
  758. break;
  759. case "40":
  760. param += " -level 4.0";
  761. break;
  762. case "41":
  763. param += " -level 4.1";
  764. break;
  765. case "42":
  766. param += " -level 4.2";
  767. break;
  768. case "50":
  769. param += " -level 5.0";
  770. break;
  771. case "51":
  772. param += " -level 5.1";
  773. break;
  774. case "52":
  775. param += " -level 5.2";
  776. break;
  777. default:
  778. param += " -level " + level;
  779. break;
  780. }
  781. }
  782. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  783. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
  784. {
  785. // nvenc doesn't decode with param -level set ?!
  786. // TODO:
  787. }
  788. else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase))
  789. {
  790. param += " -level " + level;
  791. }
  792. }
  793. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  794. {
  795. param += " -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none";
  796. }
  797. if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  798. {
  799. // todo
  800. }
  801. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  802. && !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  803. && !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  804. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  805. {
  806. param = "-pix_fmt yuv420p " + param;
  807. }
  808. if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  809. {
  810. param = "-pix_fmt nv21 " + param;
  811. }
  812. return param;
  813. }
  814. public bool CanStreamCopyVideo(EncodingJobInfo state, MediaStream videoStream)
  815. {
  816. var request = state.BaseRequest;
  817. if (!request.AllowVideoStreamCopy)
  818. {
  819. return false;
  820. }
  821. if (videoStream.IsInterlaced
  822. && state.DeInterlace(videoStream.Codec, false))
  823. {
  824. return false;
  825. }
  826. if (videoStream.IsAnamorphic ?? false)
  827. {
  828. if (request.RequireNonAnamorphic)
  829. {
  830. return false;
  831. }
  832. }
  833. // Can't stream copy if we're burning in subtitles
  834. if (request.SubtitleStreamIndex.HasValue
  835. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  836. {
  837. return false;
  838. }
  839. if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
  840. && videoStream.IsAVC.HasValue
  841. && !videoStream.IsAVC.Value
  842. && request.RequireAvc)
  843. {
  844. return false;
  845. }
  846. // Source and target codecs must match
  847. if (string.IsNullOrEmpty(videoStream.Codec)
  848. || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
  849. {
  850. return false;
  851. }
  852. var requestedProfiles = state.GetRequestedProfiles(videoStream.Codec);
  853. // If client is requesting a specific video profile, it must match the source
  854. if (requestedProfiles.Length > 0)
  855. {
  856. if (string.IsNullOrEmpty(videoStream.Profile))
  857. {
  858. //return false;
  859. }
  860. var requestedProfile = requestedProfiles[0];
  861. // strip spaces because they may be stripped out on the query string as well
  862. if (!string.IsNullOrEmpty(videoStream.Profile) && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", ""), StringComparer.OrdinalIgnoreCase))
  863. {
  864. var currentScore = GetVideoProfileScore(videoStream.Profile);
  865. var requestedScore = GetVideoProfileScore(requestedProfile);
  866. if (currentScore == -1 || currentScore > requestedScore)
  867. {
  868. return false;
  869. }
  870. }
  871. }
  872. // Video width must fall within requested value
  873. if (request.MaxWidth.HasValue
  874. && (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value))
  875. {
  876. return false;
  877. }
  878. // Video height must fall within requested value
  879. if (request.MaxHeight.HasValue
  880. && (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value))
  881. {
  882. return false;
  883. }
  884. // Video framerate must fall within requested value
  885. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  886. if (requestedFramerate.HasValue)
  887. {
  888. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  889. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  890. {
  891. return false;
  892. }
  893. }
  894. // Video bitrate must fall within requested value
  895. if (request.VideoBitRate.HasValue
  896. && (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value))
  897. {
  898. return false;
  899. }
  900. var maxBitDepth = state.GetRequestedVideoBitDepth(videoStream.Codec);
  901. if (maxBitDepth.HasValue)
  902. {
  903. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > maxBitDepth.Value)
  904. {
  905. return false;
  906. }
  907. }
  908. var maxRefFrames = state.GetRequestedMaxRefFrames(videoStream.Codec);
  909. if (maxRefFrames.HasValue
  910. && videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > maxRefFrames.Value)
  911. {
  912. return false;
  913. }
  914. // If a specific level was requested, the source must match or be less than
  915. var level = state.GetRequestedLevel(videoStream.Codec);
  916. if (!string.IsNullOrEmpty(level)
  917. && double.TryParse(level, NumberStyles.Any, _usCulture, out var requestLevel))
  918. {
  919. if (!videoStream.Level.HasValue)
  920. {
  921. //return false;
  922. }
  923. if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
  924. {
  925. return false;
  926. }
  927. }
  928. if (string.Equals(state.InputContainer, "avi", StringComparison.OrdinalIgnoreCase)
  929. && string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase)
  930. && !(videoStream.IsAVC ?? false))
  931. {
  932. // see Coach S01E01 - Kelly and the Professor(0).avi
  933. return false;
  934. }
  935. return request.EnableAutoStreamCopy;
  936. }
  937. public bool CanStreamCopyAudio(EncodingJobInfo state, MediaStream audioStream, IEnumerable<string> supportedAudioCodecs)
  938. {
  939. var request = state.BaseRequest;
  940. if (!request.AllowAudioStreamCopy)
  941. {
  942. return false;
  943. }
  944. var maxBitDepth = state.GetRequestedAudioBitDepth(audioStream.Codec);
  945. if (maxBitDepth.HasValue
  946. && audioStream.BitDepth.HasValue
  947. && audioStream.BitDepth.Value > maxBitDepth.Value)
  948. {
  949. return false;
  950. }
  951. // Source and target codecs must match
  952. if (string.IsNullOrEmpty(audioStream.Codec)
  953. || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  954. {
  955. return false;
  956. }
  957. // Channels must fall within requested value
  958. var channels = state.GetRequestedAudioChannels(audioStream.Codec);
  959. if (channels.HasValue)
  960. {
  961. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  962. {
  963. return false;
  964. }
  965. if (audioStream.Channels.Value > channels.Value)
  966. {
  967. return false;
  968. }
  969. }
  970. // Sample rate must fall within requested value
  971. if (request.AudioSampleRate.HasValue)
  972. {
  973. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  974. {
  975. return false;
  976. }
  977. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  978. {
  979. return false;
  980. }
  981. }
  982. // Video bitrate must fall within requested value
  983. if (request.AudioBitRate.HasValue)
  984. {
  985. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  986. {
  987. return false;
  988. }
  989. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  990. {
  991. return false;
  992. }
  993. }
  994. return request.EnableAutoStreamCopy;
  995. }
  996. public int? GetVideoBitrateParamValue(BaseEncodingJobOptions request, MediaStream videoStream, string outputVideoCodec)
  997. {
  998. var bitrate = request.VideoBitRate;
  999. if (videoStream != null)
  1000. {
  1001. var isUpscaling = request.Height.HasValue
  1002. && videoStream.Height.HasValue
  1003. && request.Height.Value > videoStream.Height.Value
  1004. && request.Width.HasValue
  1005. && videoStream.Width.HasValue
  1006. && request.Width.Value > videoStream.Width.Value;
  1007. // Don't allow bitrate increases unless upscaling
  1008. if (!isUpscaling && bitrate.HasValue && videoStream.BitRate.HasValue)
  1009. {
  1010. bitrate = GetMinBitrate(videoStream.BitRate.Value, bitrate.Value);
  1011. }
  1012. if (bitrate.HasValue)
  1013. {
  1014. var inputVideoCodec = videoStream.Codec;
  1015. bitrate = ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec);
  1016. // If a max bitrate was requested, don't let the scaled bitrate exceed it
  1017. if (request.VideoBitRate.HasValue)
  1018. {
  1019. bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value);
  1020. }
  1021. }
  1022. }
  1023. return bitrate;
  1024. }
  1025. private int GetMinBitrate(int sourceBitrate, int requestedBitrate)
  1026. {
  1027. // these values were chosen from testing to improve low bitrate streams
  1028. if (sourceBitrate <= 2000000)
  1029. {
  1030. sourceBitrate = Convert.ToInt32(sourceBitrate * 2.5);
  1031. }
  1032. else if (sourceBitrate <= 3000000)
  1033. {
  1034. sourceBitrate *= 2;
  1035. }
  1036. var bitrate = Math.Min(sourceBitrate, requestedBitrate);
  1037. return bitrate;
  1038. }
  1039. private static double GetVideoBitrateScaleFactor(string codec)
  1040. {
  1041. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  1042. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  1043. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  1044. {
  1045. return .5;
  1046. }
  1047. return 1;
  1048. }
  1049. private static int ScaleBitrate(int bitrate, string inputVideoCodec, string outputVideoCodec)
  1050. {
  1051. var inputScaleFactor = GetVideoBitrateScaleFactor(inputVideoCodec);
  1052. var outputScaleFactor = GetVideoBitrateScaleFactor(outputVideoCodec);
  1053. var scaleFactor = outputScaleFactor / inputScaleFactor;
  1054. if (bitrate <= 500000)
  1055. {
  1056. scaleFactor = Math.Max(scaleFactor, 4);
  1057. }
  1058. else if (bitrate <= 1000000)
  1059. {
  1060. scaleFactor = Math.Max(scaleFactor, 3);
  1061. }
  1062. else if (bitrate <= 2000000)
  1063. {
  1064. scaleFactor = Math.Max(scaleFactor, 2.5);
  1065. }
  1066. else if (bitrate <= 3000000)
  1067. {
  1068. scaleFactor = Math.Max(scaleFactor, 2);
  1069. }
  1070. return Convert.ToInt32(scaleFactor * bitrate);
  1071. }
  1072. public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream)
  1073. {
  1074. if (request.AudioBitRate.HasValue)
  1075. {
  1076. // Don't encode any higher than this
  1077. return Math.Min(384000, request.AudioBitRate.Value);
  1078. }
  1079. return null;
  1080. }
  1081. public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions, bool isHls)
  1082. {
  1083. var channels = state.OutputAudioChannels;
  1084. var filters = new List<string>();
  1085. // Boost volume to 200% when downsampling from 6ch to 2ch
  1086. if (channels.HasValue
  1087. && channels.Value <= 2
  1088. && state.AudioStream != null
  1089. && state.AudioStream.Channels.HasValue
  1090. && state.AudioStream.Channels.Value > 5
  1091. && !encodingOptions.DownMixAudioBoost.Equals(1))
  1092. {
  1093. filters.Add("volume=" + encodingOptions.DownMixAudioBoost.ToString(_usCulture));
  1094. }
  1095. var isCopyingTimestamps = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive;
  1096. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode && !isCopyingTimestamps)
  1097. {
  1098. var seconds = TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds;
  1099. filters.Add(
  1100. string.Format(
  1101. CultureInfo.InvariantCulture,
  1102. "asetpts=PTS-{0}/TB",
  1103. Math.Round(seconds)));
  1104. }
  1105. if (filters.Count > 0)
  1106. {
  1107. return "-af \"" + string.Join(",", filters) + "\"";
  1108. }
  1109. return string.Empty;
  1110. }
  1111. /// <summary>
  1112. /// Gets the number of audio channels to specify on the command line
  1113. /// </summary>
  1114. /// <param name="state">The state.</param>
  1115. /// <param name="audioStream">The audio stream.</param>
  1116. /// <param name="outputAudioCodec">The output audio codec.</param>
  1117. /// <returns>System.Nullable{System.Int32}.</returns>
  1118. public int? GetNumAudioChannelsParam(EncodingJobInfo state, MediaStream audioStream, string outputAudioCodec)
  1119. {
  1120. var request = state.BaseRequest;
  1121. var inputChannels = audioStream?.Channels;
  1122. if (inputChannels <= 0)
  1123. {
  1124. inputChannels = null;
  1125. }
  1126. var codec = outputAudioCodec ?? string.Empty;
  1127. int? transcoderChannelLimit;
  1128. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  1129. {
  1130. // wmav2 currently only supports two channel output
  1131. transcoderChannelLimit = 2;
  1132. }
  1133. else if (codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  1134. {
  1135. // libmp3lame currently only supports two channel output
  1136. transcoderChannelLimit = 2;
  1137. }
  1138. else
  1139. {
  1140. // If we don't have any media info then limit it to 6 to prevent encoding errors due to asking for too many channels
  1141. transcoderChannelLimit = 6;
  1142. }
  1143. var isTranscodingAudio = !string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase);
  1144. int? resultChannels = state.GetRequestedAudioChannels(codec);
  1145. if (isTranscodingAudio)
  1146. {
  1147. resultChannels = GetMinValue(request.TranscodingMaxAudioChannels, resultChannels);
  1148. }
  1149. if (inputChannels.HasValue)
  1150. {
  1151. resultChannels = resultChannels.HasValue
  1152. ? Math.Min(resultChannels.Value, inputChannels.Value)
  1153. : inputChannels.Value;
  1154. }
  1155. if (isTranscodingAudio && transcoderChannelLimit.HasValue)
  1156. {
  1157. resultChannels = resultChannels.HasValue
  1158. ? Math.Min(resultChannels.Value, transcoderChannelLimit.Value)
  1159. : transcoderChannelLimit.Value;
  1160. }
  1161. return resultChannels;
  1162. }
  1163. private int? GetMinValue(int? val1, int? val2)
  1164. {
  1165. if (!val1.HasValue)
  1166. {
  1167. return val2;
  1168. }
  1169. if (!val2.HasValue)
  1170. {
  1171. return val1;
  1172. }
  1173. return Math.Min(val1.Value, val2.Value);
  1174. }
  1175. /// <summary>
  1176. /// Enforces the resolution limit.
  1177. /// </summary>
  1178. /// <param name="state">The state.</param>
  1179. public void EnforceResolutionLimit(EncodingJobInfo state)
  1180. {
  1181. var videoRequest = state.BaseRequest;
  1182. // Switch the incoming params to be ceilings rather than fixed values
  1183. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1184. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1185. videoRequest.Width = null;
  1186. videoRequest.Height = null;
  1187. }
  1188. /// <summary>
  1189. /// Gets the fast seek command line parameter.
  1190. /// </summary>
  1191. /// <param name="request">The request.</param>
  1192. /// <returns>System.String.</returns>
  1193. /// <value>The fast seek command line parameter.</value>
  1194. public string GetFastSeekCommandLineParameter(BaseEncodingJobOptions request)
  1195. {
  1196. var time = request.StartTimeTicks ?? 0;
  1197. if (time > 0)
  1198. {
  1199. return string.Format("-ss {0}", _mediaEncoder.GetTimeParameter(time));
  1200. }
  1201. return string.Empty;
  1202. }
  1203. /// <summary>
  1204. /// Gets the map args.
  1205. /// </summary>
  1206. /// <param name="state">The state.</param>
  1207. /// <returns>System.String.</returns>
  1208. public string GetMapArgs(EncodingJobInfo state)
  1209. {
  1210. // If we don't have known media info
  1211. // If input is video, use -sn to drop subtitles
  1212. // Otherwise just return empty
  1213. if (state.VideoStream == null && state.AudioStream == null)
  1214. {
  1215. return state.IsInputVideo ? "-sn" : string.Empty;
  1216. }
  1217. // We have media info, but we don't know the stream indexes
  1218. if (state.VideoStream != null && state.VideoStream.Index == -1)
  1219. {
  1220. return "-sn";
  1221. }
  1222. // We have media info, but we don't know the stream indexes
  1223. if (state.AudioStream != null && state.AudioStream.Index == -1)
  1224. {
  1225. return state.IsInputVideo ? "-sn" : string.Empty;
  1226. }
  1227. var args = string.Empty;
  1228. if (state.VideoStream != null)
  1229. {
  1230. args += string.Format(
  1231. CultureInfo.InvariantCulture,
  1232. "-map 0:{0}",
  1233. state.VideoStream.Index);
  1234. }
  1235. else
  1236. {
  1237. // No known video stream
  1238. args += "-vn";
  1239. }
  1240. if (state.AudioStream != null)
  1241. {
  1242. args += string.Format(
  1243. CultureInfo.InvariantCulture,
  1244. " -map 0:{0}",
  1245. state.AudioStream.Index);
  1246. }
  1247. else
  1248. {
  1249. args += " -map -0:a";
  1250. }
  1251. var subtitleMethod = state.SubtitleDeliveryMethod;
  1252. if (state.SubtitleStream == null || subtitleMethod == SubtitleDeliveryMethod.Hls)
  1253. {
  1254. args += " -map -0:s";
  1255. }
  1256. else if (subtitleMethod == SubtitleDeliveryMethod.Embed)
  1257. {
  1258. args += string.Format(
  1259. CultureInfo.InvariantCulture,
  1260. " -map 0:{0}",
  1261. state.SubtitleStream.Index);
  1262. }
  1263. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  1264. {
  1265. args += " -map 1:0 -sn";
  1266. }
  1267. return args;
  1268. }
  1269. /// <summary>
  1270. /// Determines which stream will be used for playback
  1271. /// </summary>
  1272. /// <param name="allStream">All stream.</param>
  1273. /// <param name="desiredIndex">Index of the desired.</param>
  1274. /// <param name="type">The type.</param>
  1275. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  1276. /// <returns>MediaStream.</returns>
  1277. public MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  1278. {
  1279. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  1280. if (desiredIndex.HasValue)
  1281. {
  1282. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  1283. if (stream != null)
  1284. {
  1285. return stream;
  1286. }
  1287. }
  1288. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  1289. {
  1290. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  1291. streams.FirstOrDefault();
  1292. }
  1293. // Just return the first one
  1294. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  1295. }
  1296. /// <summary>
  1297. /// Gets the graphical subtitle param.
  1298. /// </summary>
  1299. public string GetGraphicalSubtitleParam(
  1300. EncodingJobInfo state,
  1301. EncodingOptions options,
  1302. string outputVideoCodec)
  1303. {
  1304. var outputSizeParam = string.Empty;
  1305. var request = state.BaseRequest;
  1306. // Add resolution params, if specified
  1307. if (request.Width.HasValue
  1308. || request.Height.HasValue
  1309. || request.MaxHeight.HasValue
  1310. || request.MaxWidth.HasValue)
  1311. {
  1312. outputSizeParam = GetOutputSizeParam(state, options, outputVideoCodec).TrimEnd('"');
  1313. var index = outputSizeParam.IndexOf("hwdownload", StringComparison.OrdinalIgnoreCase);
  1314. if (index != -1)
  1315. {
  1316. outputSizeParam = "," + outputSizeParam.Substring(index);
  1317. }
  1318. else
  1319. {
  1320. index = outputSizeParam.IndexOf("format", StringComparison.OrdinalIgnoreCase);
  1321. if (index != -1)
  1322. {
  1323. outputSizeParam = "," + outputSizeParam.Substring(index);
  1324. }
  1325. else
  1326. {
  1327. index = outputSizeParam.IndexOf("yadif", StringComparison.OrdinalIgnoreCase);
  1328. if (index != -1)
  1329. {
  1330. outputSizeParam = "," + outputSizeParam.Substring(index);
  1331. }
  1332. else
  1333. {
  1334. index = outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase);
  1335. if (index != -1)
  1336. {
  1337. outputSizeParam = "," + outputSizeParam.Substring(index);
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. var videoSizeParam = string.Empty;
  1344. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options);
  1345. // Setup subtitle scaling
  1346. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  1347. {
  1348. // force_original_aspect_ratio=decrease
  1349. // Enable decreasing output video width or height if necessary to keep the original aspect ratio
  1350. videoSizeParam = string.Format(
  1351. CultureInfo.InvariantCulture,
  1352. "scale={0}:{1}:force_original_aspect_ratio=decrease",
  1353. state.VideoStream.Width.Value,
  1354. state.VideoStream.Height.Value);
  1355. // For QSV, feed it into hardware encoder now
  1356. if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1357. {
  1358. videoSizeParam += ",hwupload=extra_hw_frames=64";
  1359. }
  1360. // For VAAPI and CUVID decoder
  1361. // these encoders cannot automatically adjust the size of graphical subtitles to fit the output video,
  1362. // thus needs to be manually adjusted.
  1363. if ((IsVaapiSupported(state) && string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  1364. || (videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1)
  1365. {
  1366. var videoStream = state.VideoStream;
  1367. var inputWidth = videoStream?.Width;
  1368. var inputHeight = videoStream?.Height;
  1369. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  1370. if (width.HasValue && height.HasValue)
  1371. {
  1372. videoSizeParam = string.Format(
  1373. CultureInfo.InvariantCulture,
  1374. "scale={0}:{1}:force_original_aspect_ratio=decrease",
  1375. width.Value,
  1376. height.Value);
  1377. }
  1378. }
  1379. }
  1380. var mapPrefix = state.SubtitleStream.IsExternal ?
  1381. 1 :
  1382. 0;
  1383. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  1384. ? 0
  1385. : state.SubtitleStream.Index;
  1386. // Setup default filtergraph utilizing FFMpeg overlay() and FFMpeg scale() (see the return of this function for index reference)
  1387. var retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay{3}\"";
  1388. // When the input may or may not be hardware VAAPI decodable
  1389. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1390. {
  1391. /*
  1392. [base]: HW scaling video to OutputSize
  1393. [sub]: SW scaling subtitle to FixedOutputSize
  1394. [base][sub]: SW overlay
  1395. */
  1396. outputSizeParam = outputSizeParam.TrimStart(',');
  1397. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload[base];[base][sub]overlay,format=nv12,hwupload\"";
  1398. }
  1399. // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first
  1400. else if (IsVaapiSupported(state) && string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)
  1401. && string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  1402. {
  1403. /*
  1404. [base]: SW scaling video to OutputSize
  1405. [sub]: SW scaling subtitle to FixedOutputSize
  1406. [base][sub]: SW overlay
  1407. */
  1408. outputSizeParam = outputSizeParam.TrimStart(',');
  1409. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"";
  1410. }
  1411. else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1412. {
  1413. /*
  1414. QSV in FFMpeg can now setup hardware overlay for transcodes.
  1415. For software decoding and hardware encoding option, frames must be hwuploaded into hardware
  1416. with fixed frame size.
  1417. */
  1418. if ((videoDecoder ?? string.Empty).IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1)
  1419. {
  1420. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay_qsv=x=(W-w)/2:y=(H-h)/2{3}\"";
  1421. }
  1422. else
  1423. {
  1424. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]hwupload=extra_hw_frames=64[v];[v][sub]overlay_qsv=x=(W-w)/2:y=(H-h)/2{3}\"";
  1425. }
  1426. }
  1427. return string.Format(
  1428. CultureInfo.InvariantCulture,
  1429. retStr,
  1430. mapPrefix,
  1431. subtitleStreamIndex,
  1432. state.VideoStream.Index,
  1433. outputSizeParam,
  1434. videoSizeParam);
  1435. }
  1436. private (int? width, int? height) GetFixedOutputSize(
  1437. int? videoWidth,
  1438. int? videoHeight,
  1439. int? requestedWidth,
  1440. int? requestedHeight,
  1441. int? requestedMaxWidth,
  1442. int? requestedMaxHeight)
  1443. {
  1444. if (!videoWidth.HasValue && !requestedWidth.HasValue)
  1445. {
  1446. return (null, null);
  1447. }
  1448. if (!videoHeight.HasValue && !requestedHeight.HasValue)
  1449. {
  1450. return (null, null);
  1451. }
  1452. decimal inputWidth = Convert.ToDecimal(videoWidth ?? requestedWidth);
  1453. decimal inputHeight = Convert.ToDecimal(videoHeight ?? requestedHeight);
  1454. decimal outputWidth = requestedWidth.HasValue ? Convert.ToDecimal(requestedWidth.Value) : inputWidth;
  1455. decimal outputHeight = requestedHeight.HasValue ? Convert.ToDecimal(requestedHeight.Value) : inputHeight;
  1456. decimal maximumWidth = requestedMaxWidth.HasValue ? Convert.ToDecimal(requestedMaxWidth.Value) : outputWidth;
  1457. decimal maximumHeight = requestedMaxHeight.HasValue ? Convert.ToDecimal(requestedMaxHeight.Value) : outputHeight;
  1458. if (outputWidth > maximumWidth || outputHeight > maximumHeight)
  1459. {
  1460. var scale = Math.Min(maximumWidth / outputWidth, maximumHeight / outputHeight);
  1461. outputWidth = Math.Min(maximumWidth, Math.Truncate(outputWidth * scale));
  1462. outputHeight = Math.Min(maximumHeight, Math.Truncate(outputHeight * scale));
  1463. }
  1464. outputWidth = 2 * Math.Truncate(outputWidth / 2);
  1465. outputHeight = 2 * Math.Truncate(outputHeight / 2);
  1466. return (Convert.ToInt32(outputWidth), Convert.ToInt32(outputHeight));
  1467. }
  1468. public List<string> GetScalingFilters(EncodingJobInfo state,
  1469. int? videoWidth,
  1470. int? videoHeight,
  1471. Video3DFormat? threedFormat,
  1472. string videoDecoder,
  1473. string videoEncoder,
  1474. int? requestedWidth,
  1475. int? requestedHeight,
  1476. int? requestedMaxWidth,
  1477. int? requestedMaxHeight)
  1478. {
  1479. var filters = new List<string>();
  1480. var (width, height) = GetFixedOutputSize(
  1481. videoWidth,
  1482. videoHeight,
  1483. requestedWidth,
  1484. requestedHeight,
  1485. requestedMaxWidth,
  1486. requestedMaxHeight);
  1487. var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  1488. if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) || (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) && !hasTextSubs)
  1489. && width.HasValue
  1490. && height.HasValue)
  1491. {
  1492. // Given the input dimensions (inputWidth, inputHeight), determine the output dimensions
  1493. // (outputWidth, outputHeight). The user may request precise output dimensions or maximum
  1494. // output dimensions. Output dimensions are guaranteed to be even.
  1495. var outputWidth = width.Value;
  1496. var outputHeight = height.Value;
  1497. var vaapi_or_qsv = string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) ? "qsv" : "vaapi";
  1498. if (!videoWidth.HasValue
  1499. || outputWidth != videoWidth.Value
  1500. || !videoHeight.HasValue
  1501. || outputHeight != videoHeight.Value)
  1502. {
  1503. // Force nv12 pixel format to enable 10-bit to 8-bit colour conversion.
  1504. filters.Add(
  1505. string.Format(
  1506. CultureInfo.InvariantCulture,
  1507. "scale_{0}=w={1}:h={2}:format=nv12",
  1508. vaapi_or_qsv,
  1509. outputWidth,
  1510. outputHeight));
  1511. }
  1512. else
  1513. {
  1514. filters.Add(string.Format(CultureInfo.InvariantCulture, "scale_{0}=format=nv12", vaapi_or_qsv));
  1515. }
  1516. }
  1517. else if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1
  1518. && width.HasValue
  1519. && height.HasValue)
  1520. {
  1521. // Nothing to do, it's handled as an input resize filter
  1522. }
  1523. else
  1524. {
  1525. var isExynosV4L2 = string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase);
  1526. // If fixed dimensions were supplied
  1527. if (requestedWidth.HasValue && requestedHeight.HasValue)
  1528. {
  1529. if (isExynosV4L2)
  1530. {
  1531. var widthParam = requestedWidth.Value.ToString(_usCulture);
  1532. var heightParam = requestedHeight.Value.ToString(_usCulture);
  1533. filters.Add(
  1534. string.Format(
  1535. CultureInfo.InvariantCulture,
  1536. "scale=trunc({0}/64)*64:trunc({1}/2)*2",
  1537. widthParam,
  1538. heightParam));
  1539. }
  1540. else
  1541. {
  1542. filters.Add(GetFixedSizeScalingFilter(threedFormat, requestedWidth.Value, requestedHeight.Value));
  1543. }
  1544. }
  1545. // 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
  1546. else if (requestedMaxWidth.HasValue && requestedMaxHeight.HasValue)
  1547. {
  1548. var maxWidthParam = requestedMaxWidth.Value.ToString(_usCulture);
  1549. var maxHeightParam = requestedMaxHeight.Value.ToString(_usCulture);
  1550. if (isExynosV4L2)
  1551. {
  1552. filters.Add(
  1553. string.Format(
  1554. CultureInfo.InvariantCulture,
  1555. "scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/64)*64:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2",
  1556. maxWidthParam,
  1557. maxHeightParam));
  1558. }
  1559. else
  1560. {
  1561. filters.Add(
  1562. string.Format(
  1563. CultureInfo.InvariantCulture,
  1564. "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",
  1565. maxWidthParam,
  1566. maxHeightParam));
  1567. }
  1568. }
  1569. // If a fixed width was requested
  1570. else if (requestedWidth.HasValue)
  1571. {
  1572. if (threedFormat.HasValue)
  1573. {
  1574. // This method can handle 0 being passed in for the requested height
  1575. filters.Add(GetFixedSizeScalingFilter(threedFormat, requestedWidth.Value, 0));
  1576. }
  1577. else
  1578. {
  1579. var widthParam = requestedWidth.Value.ToString(_usCulture);
  1580. filters.Add(
  1581. string.Format(
  1582. CultureInfo.InvariantCulture,
  1583. "scale={0}:trunc(ow/a/2)*2",
  1584. widthParam));
  1585. }
  1586. }
  1587. // If a fixed height was requested
  1588. else if (requestedHeight.HasValue)
  1589. {
  1590. var heightParam = requestedHeight.Value.ToString(_usCulture);
  1591. if (isExynosV4L2)
  1592. {
  1593. filters.Add(
  1594. string.Format(
  1595. CultureInfo.InvariantCulture,
  1596. "scale=trunc(oh*a/64)*64:{0}",
  1597. heightParam));
  1598. }
  1599. else
  1600. {
  1601. filters.Add(
  1602. string.Format(
  1603. CultureInfo.InvariantCulture,
  1604. "scale=trunc(oh*a/2)*2:{0}",
  1605. heightParam));
  1606. }
  1607. }
  1608. // If a max width was requested
  1609. else if (requestedMaxWidth.HasValue)
  1610. {
  1611. var maxWidthParam = requestedMaxWidth.Value.ToString(_usCulture);
  1612. if (isExynosV4L2)
  1613. {
  1614. filters.Add(
  1615. string.Format(
  1616. CultureInfo.InvariantCulture,
  1617. "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/64)*64:trunc(ow/dar/2)*2",
  1618. maxWidthParam));
  1619. }
  1620. else
  1621. {
  1622. filters.Add(
  1623. string.Format(
  1624. CultureInfo.InvariantCulture,
  1625. "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2",
  1626. maxWidthParam));
  1627. }
  1628. }
  1629. // If a max height was requested
  1630. else if (requestedMaxHeight.HasValue)
  1631. {
  1632. var maxHeightParam = requestedMaxHeight.Value.ToString(_usCulture);
  1633. if (isExynosV4L2)
  1634. {
  1635. filters.Add(
  1636. string.Format(
  1637. CultureInfo.InvariantCulture,
  1638. "scale=trunc(oh*a/64)*64:min(max(iw/dar\\,ih)\\,{0})",
  1639. maxHeightParam));
  1640. }
  1641. else
  1642. {
  1643. filters.Add(
  1644. string.Format(
  1645. CultureInfo.InvariantCulture,
  1646. "scale=trunc(oh*a/2)*2:min(max(iw/dar\\,ih)\\,{0})",
  1647. maxHeightParam));
  1648. }
  1649. }
  1650. }
  1651. return filters;
  1652. }
  1653. private string GetFixedSizeScalingFilter(Video3DFormat? threedFormat, int requestedWidth, int requestedHeight)
  1654. {
  1655. var widthParam = requestedWidth.ToString(CultureInfo.InvariantCulture);
  1656. var heightParam = requestedHeight.ToString(CultureInfo.InvariantCulture);
  1657. string filter = null;
  1658. if (threedFormat.HasValue)
  1659. {
  1660. switch (threedFormat.Value)
  1661. {
  1662. case Video3DFormat.HalfSideBySide:
  1663. filter = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
  1664. // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
  1665. break;
  1666. case Video3DFormat.FullSideBySide:
  1667. filter = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
  1668. //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to requestedWidth.
  1669. break;
  1670. case Video3DFormat.HalfTopAndBottom:
  1671. filter = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
  1672. //htab crop height in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
  1673. break;
  1674. case Video3DFormat.FullTopAndBottom:
  1675. filter = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
  1676. // ftab crop height in half, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
  1677. break;
  1678. default:
  1679. break;
  1680. }
  1681. }
  1682. // default
  1683. if (filter == null)
  1684. {
  1685. if (requestedHeight > 0)
  1686. {
  1687. filter = "scale=trunc({0}/2)*2:trunc({1}/2)*2";
  1688. }
  1689. else
  1690. {
  1691. filter = "scale={0}:trunc({0}/dar/2)*2";
  1692. }
  1693. }
  1694. return string.Format(CultureInfo.InvariantCulture, filter, widthParam, heightParam);
  1695. }
  1696. /// <summary>
  1697. /// If we're going to put a fixed size on the command line, this will calculate it
  1698. /// </summary>
  1699. public string GetOutputSizeParam(
  1700. EncodingJobInfo state,
  1701. EncodingOptions options,
  1702. string outputVideoCodec)
  1703. {
  1704. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  1705. var request = state.BaseRequest;
  1706. var videoStream = state.VideoStream;
  1707. var filters = new List<string>();
  1708. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options);
  1709. var inputWidth = videoStream?.Width;
  1710. var inputHeight = videoStream?.Height;
  1711. var threeDFormat = state.MediaSource.Video3DFormat;
  1712. var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  1713. // When the input may or may not be hardware VAAPI decodable
  1714. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1715. {
  1716. filters.Add("format=nv12|vaapi");
  1717. filters.Add("hwupload");
  1718. }
  1719. // When the input may or may not be hardware QSV decodable
  1720. else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1721. {
  1722. if (!hasTextSubs)
  1723. {
  1724. filters.Add("format=nv12|qsv");
  1725. filters.Add("hwupload=extra_hw_frames=64");
  1726. }
  1727. }
  1728. // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first
  1729. else if (IsVaapiSupported(state) && string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)
  1730. && string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  1731. {
  1732. var codec = videoStream.Codec.ToLowerInvariant();
  1733. var isColorDepth10 = !string.IsNullOrEmpty(videoStream.Profile) && (videoStream.Profile.Contains("Main 10", StringComparison.OrdinalIgnoreCase)
  1734. || videoStream.Profile.Contains("High 10", StringComparison.OrdinalIgnoreCase));
  1735. // Assert 10-bit hardware VAAPI decodable
  1736. if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  1737. || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  1738. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  1739. {
  1740. /*
  1741. Download data from GPU to CPU as p010le format.
  1742. Colorspace conversion is unnecessary here as libx264 will handle it.
  1743. If this step is missing, it will fail on AMD but not on intel.
  1744. */
  1745. filters.Add("hwdownload");
  1746. filters.Add("format=p010le");
  1747. }
  1748. // Assert 8-bit hardware VAAPI decodable
  1749. else if (!isColorDepth10)
  1750. {
  1751. filters.Add("hwdownload");
  1752. filters.Add("format=nv12");
  1753. }
  1754. }
  1755. // Add hardware deinterlace filter before scaling filter
  1756. if (state.DeInterlace("h264", true))
  1757. {
  1758. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1759. {
  1760. filters.Add(string.Format(CultureInfo.InvariantCulture, "deinterlace_vaapi"));
  1761. }
  1762. else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1763. {
  1764. if (!hasTextSubs)
  1765. {
  1766. filters.Add(string.Format(CultureInfo.InvariantCulture, "deinterlace_qsv"));
  1767. }
  1768. }
  1769. }
  1770. // Add software deinterlace filter before scaling filter
  1771. if (((state.DeInterlace("h264", true) || state.DeInterlace("h265", true) || state.DeInterlace("hevc", true))
  1772. && !string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1773. && !string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1774. || (hasTextSubs && state.DeInterlace("h264", true) && string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)))
  1775. {
  1776. var inputFramerate = videoStream?.RealFrameRate;
  1777. // If it is already 60fps then it will create an output framerate that is much too high for roku and others to handle
  1778. if (string.Equals(options.DeinterlaceMethod, "yadif_bob", StringComparison.OrdinalIgnoreCase) && (inputFramerate ?? 60) <= 30)
  1779. {
  1780. filters.Add("yadif=1:-1:0");
  1781. }
  1782. else
  1783. {
  1784. filters.Add("yadif=0:-1:0");
  1785. }
  1786. }
  1787. // Add scaling filter: scale_*=format=nv12 or scale_*=w=*:h=*:format=nv12 or scale=expr
  1788. filters.AddRange(GetScalingFilters(state, inputWidth, inputHeight, threeDFormat, videoDecoder, outputVideoCodec, request.Width, request.Height, request.MaxWidth, request.MaxHeight));
  1789. // Add parameters to use VAAPI with burn-in text subttiles (GH issue #642)
  1790. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1791. {
  1792. if (state.SubtitleStream != null
  1793. && state.SubtitleStream.IsTextSubtitleStream
  1794. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  1795. {
  1796. // Test passed on Intel and AMD gfx
  1797. filters.Add("hwmap=mode=read+write");
  1798. filters.Add("format=nv12");
  1799. }
  1800. }
  1801. var output = string.Empty;
  1802. if (state.SubtitleStream != null
  1803. && state.SubtitleStream.IsTextSubtitleStream
  1804. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  1805. {
  1806. var subParam = GetTextSubtitleParam(state);
  1807. filters.Add(subParam);
  1808. // Ensure proper filters are passed to ffmpeg in case of hardware acceleration via VA-API
  1809. // Reference: https://trac.ffmpeg.org/wiki/Hardware/VAAPI
  1810. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1811. {
  1812. filters.Add("hwmap");
  1813. }
  1814. }
  1815. if (filters.Count > 0)
  1816. {
  1817. output += string.Format(
  1818. CultureInfo.InvariantCulture,
  1819. " -vf \"{0}\"",
  1820. string.Join(",", filters));
  1821. }
  1822. return output;
  1823. }
  1824. /// <summary>
  1825. /// Gets the number of threads.
  1826. /// </summary>
  1827. public int GetNumberOfThreads(EncodingJobInfo state, EncodingOptions encodingOptions, string outputVideoCodec)
  1828. {
  1829. if (string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  1830. {
  1831. // per docs:
  1832. // -threads number of threads to use for encoding, can't be 0 [auto] with VP8
  1833. // (recommended value : number of real cores - 1)
  1834. return Math.Max(Environment.ProcessorCount - 1, 1);
  1835. }
  1836. var threads = state.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount;
  1837. // Automatic
  1838. if (threads <= 0 || threads >= Environment.ProcessorCount)
  1839. {
  1840. return 0;
  1841. }
  1842. return threads;
  1843. }
  1844. public void TryStreamCopy(EncodingJobInfo state)
  1845. {
  1846. if (state.VideoStream != null && CanStreamCopyVideo(state, state.VideoStream))
  1847. {
  1848. state.OutputVideoCodec = "copy";
  1849. }
  1850. else
  1851. {
  1852. var user = state.User;
  1853. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  1854. if (user != null && !user.Policy.EnableVideoPlaybackTranscoding)
  1855. {
  1856. state.OutputVideoCodec = "copy";
  1857. }
  1858. }
  1859. if (state.AudioStream != null
  1860. && CanStreamCopyAudio(state, state.AudioStream, state.SupportedAudioCodecs))
  1861. {
  1862. state.OutputAudioCodec = "copy";
  1863. }
  1864. else
  1865. {
  1866. var user = state.User;
  1867. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  1868. if (user != null && !user.Policy.EnableAudioPlaybackTranscoding)
  1869. {
  1870. state.OutputAudioCodec = "copy";
  1871. }
  1872. }
  1873. }
  1874. public string GetProbeSizeArgument(int numInputFiles)
  1875. => numInputFiles > 1 ? "-probesize " + _configuration.GetFFmpegProbeSize() : string.Empty;
  1876. public string GetAnalyzeDurationArgument(int numInputFiles)
  1877. => numInputFiles > 1 ? "-analyzeduration " + _configuration.GetFFmpegAnalyzeDuration() : string.Empty;
  1878. public string GetInputModifier(EncodingJobInfo state, EncodingOptions encodingOptions)
  1879. {
  1880. var inputModifier = string.Empty;
  1881. var numInputFiles = state.PlayableStreamFileNames.Length > 0 ? state.PlayableStreamFileNames.Length : 1;
  1882. var probeSizeArgument = GetProbeSizeArgument(numInputFiles);
  1883. string analyzeDurationArgument;
  1884. if (state.MediaSource.AnalyzeDurationMs.HasValue)
  1885. {
  1886. analyzeDurationArgument = "-analyzeduration " + (state.MediaSource.AnalyzeDurationMs.Value * 1000).ToString(CultureInfo.InvariantCulture);
  1887. }
  1888. else
  1889. {
  1890. analyzeDurationArgument = GetAnalyzeDurationArgument(numInputFiles);
  1891. }
  1892. if (!string.IsNullOrEmpty(probeSizeArgument))
  1893. {
  1894. inputModifier += " " + probeSizeArgument;
  1895. }
  1896. if (!string.IsNullOrEmpty(analyzeDurationArgument))
  1897. {
  1898. inputModifier += " " + analyzeDurationArgument;
  1899. }
  1900. inputModifier = inputModifier.Trim();
  1901. var userAgentParam = GetUserAgentParam(state);
  1902. if (!string.IsNullOrEmpty(userAgentParam))
  1903. {
  1904. inputModifier += " " + userAgentParam;
  1905. }
  1906. inputModifier = inputModifier.Trim();
  1907. inputModifier += " " + GetFastSeekCommandLineParameter(state.BaseRequest);
  1908. inputModifier = inputModifier.Trim();
  1909. if (state.InputProtocol == MediaProtocol.Rtsp)
  1910. {
  1911. inputModifier += " -rtsp_transport tcp -rtsp_transport udp -rtsp_flags prefer_tcp";
  1912. }
  1913. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1914. {
  1915. inputModifier += " -async " + state.InputAudioSync;
  1916. }
  1917. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1918. {
  1919. inputModifier += " -vsync " + state.InputVideoSync;
  1920. }
  1921. if (state.ReadInputAtNativeFramerate && state.InputProtocol != MediaProtocol.Rtsp)
  1922. {
  1923. inputModifier += " -re";
  1924. }
  1925. var flags = new List<string>();
  1926. if (state.IgnoreInputDts)
  1927. {
  1928. flags.Add("+igndts");
  1929. }
  1930. if (state.IgnoreInputIndex)
  1931. {
  1932. flags.Add("+ignidx");
  1933. }
  1934. if (state.GenPtsInput || string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  1935. {
  1936. flags.Add("+genpts");
  1937. }
  1938. if (state.DiscardCorruptFramesInput)
  1939. {
  1940. flags.Add("+discardcorrupt");
  1941. }
  1942. if (state.EnableFastSeekInput)
  1943. {
  1944. flags.Add("+fastseek");
  1945. }
  1946. if (flags.Count > 0)
  1947. {
  1948. inputModifier += " -fflags " + string.Join(string.Empty, flags);
  1949. }
  1950. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
  1951. if (!string.IsNullOrEmpty(videoDecoder))
  1952. {
  1953. inputModifier += " " + videoDecoder;
  1954. if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1)
  1955. {
  1956. var videoStream = state.VideoStream;
  1957. var inputWidth = videoStream?.Width;
  1958. var inputHeight = videoStream?.Height;
  1959. var request = state.BaseRequest;
  1960. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  1961. if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1
  1962. && width.HasValue
  1963. && height.HasValue)
  1964. {
  1965. inputModifier += string.Format(
  1966. CultureInfo.InvariantCulture,
  1967. " -resize {0}x{1}",
  1968. width.Value,
  1969. height.Value);
  1970. }
  1971. }
  1972. }
  1973. if (state.IsVideoRequest)
  1974. {
  1975. var outputVideoCodec = GetVideoEncoder(state, encodingOptions);
  1976. // Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking
  1977. if (!string.Equals(state.InputContainer, "wtv", StringComparison.OrdinalIgnoreCase)
  1978. && state.TranscodingType != TranscodingJobType.Progressive
  1979. && !state.EnableBreakOnNonKeyFrames(outputVideoCodec)
  1980. && (state.BaseRequest.StartTimeTicks ?? 0) > 0)
  1981. {
  1982. inputModifier += " -noaccurate_seek";
  1983. }
  1984. if (!string.IsNullOrEmpty(state.InputContainer) && state.VideoType == VideoType.VideoFile && string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
  1985. {
  1986. var inputFormat = GetInputFormat(state.InputContainer);
  1987. if (!string.IsNullOrEmpty(inputFormat))
  1988. {
  1989. inputModifier += " -f " + inputFormat;
  1990. }
  1991. }
  1992. }
  1993. if (state.MediaSource.RequiresLooping)
  1994. {
  1995. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  1996. }
  1997. return inputModifier;
  1998. }
  1999. public void AttachMediaSourceInfo(
  2000. EncodingJobInfo state,
  2001. MediaSourceInfo mediaSource,
  2002. string requestedUrl)
  2003. {
  2004. if (state == null)
  2005. {
  2006. throw new ArgumentNullException(nameof(state));
  2007. }
  2008. if (mediaSource == null)
  2009. {
  2010. throw new ArgumentNullException(nameof(mediaSource));
  2011. }
  2012. var path = mediaSource.Path;
  2013. var protocol = mediaSource.Protocol;
  2014. if (!string.IsNullOrEmpty(mediaSource.EncoderPath) && mediaSource.EncoderProtocol.HasValue)
  2015. {
  2016. path = mediaSource.EncoderPath;
  2017. protocol = mediaSource.EncoderProtocol.Value;
  2018. }
  2019. state.MediaPath = path;
  2020. state.InputProtocol = protocol;
  2021. state.InputContainer = mediaSource.Container;
  2022. state.RunTimeTicks = mediaSource.RunTimeTicks;
  2023. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  2024. state.IsoType = mediaSource.IsoType;
  2025. if (mediaSource.VideoType.HasValue)
  2026. {
  2027. state.VideoType = mediaSource.VideoType.Value;
  2028. if (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd)
  2029. {
  2030. state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, mediaSource.VideoType.Value).Select(Path.GetFileName).ToArray();
  2031. }
  2032. else if (mediaSource.VideoType.Value == VideoType.Iso && state.IsoType == IsoType.BluRay)
  2033. {
  2034. state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, VideoType.BluRay).Select(Path.GetFileName).ToArray();
  2035. }
  2036. else if (mediaSource.VideoType.Value == VideoType.Iso && state.IsoType == IsoType.Dvd)
  2037. {
  2038. state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, VideoType.Dvd).Select(Path.GetFileName).ToArray();
  2039. }
  2040. else
  2041. {
  2042. state.PlayableStreamFileNames = Array.Empty<string>();
  2043. }
  2044. }
  2045. else
  2046. {
  2047. state.PlayableStreamFileNames = Array.Empty<string>();
  2048. }
  2049. if (mediaSource.Timestamp.HasValue)
  2050. {
  2051. state.InputTimestamp = mediaSource.Timestamp.Value;
  2052. }
  2053. state.RunTimeTicks = mediaSource.RunTimeTicks;
  2054. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  2055. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  2056. if (state.ReadInputAtNativeFramerate
  2057. || mediaSource.Protocol == MediaProtocol.File
  2058. && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase))
  2059. {
  2060. state.InputVideoSync = "-1";
  2061. state.InputAudioSync = "1";
  2062. }
  2063. if (string.Equals(mediaSource.Container, "wma", StringComparison.OrdinalIgnoreCase)
  2064. || string.Equals(mediaSource.Container, "asf", StringComparison.OrdinalIgnoreCase))
  2065. {
  2066. // Seeing some stuttering when transcoding wma to audio-only HLS
  2067. state.InputAudioSync = "1";
  2068. }
  2069. var mediaStreams = mediaSource.MediaStreams;
  2070. if (state.IsVideoRequest)
  2071. {
  2072. var videoRequest = state.BaseRequest;
  2073. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  2074. {
  2075. if (string.IsNullOrEmpty(requestedUrl))
  2076. {
  2077. requestedUrl = "test." + videoRequest.Container;
  2078. }
  2079. videoRequest.VideoCodec = InferVideoCodec(requestedUrl);
  2080. }
  2081. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  2082. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  2083. state.SubtitleDeliveryMethod = videoRequest.SubtitleMethod;
  2084. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  2085. if (state.SubtitleStream != null && !state.SubtitleStream.IsExternal)
  2086. {
  2087. state.InternalSubtitleStreamOffset = mediaStreams.Where(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal).ToList().IndexOf(state.SubtitleStream);
  2088. }
  2089. EnforceResolutionLimit(state);
  2090. NormalizeSubtitleEmbed(state);
  2091. }
  2092. else
  2093. {
  2094. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  2095. }
  2096. state.MediaSource = mediaSource;
  2097. var request = state.BaseRequest;
  2098. if (!string.IsNullOrWhiteSpace(request.AudioCodec))
  2099. {
  2100. var supportedAudioCodecsList = request.AudioCodec.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
  2101. ShiftAudioCodecsIfNeeded(supportedAudioCodecsList, state.AudioStream);
  2102. state.SupportedAudioCodecs = supportedAudioCodecsList.ToArray();
  2103. request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => _mediaEncoder.CanEncodeToAudioCodec(i))
  2104. ?? state.SupportedAudioCodecs.FirstOrDefault();
  2105. }
  2106. }
  2107. private void ShiftAudioCodecsIfNeeded(List<string> audioCodecs, MediaStream audioStream)
  2108. {
  2109. // Nothing to do here
  2110. if (audioCodecs.Count < 2)
  2111. {
  2112. return;
  2113. }
  2114. var inputChannels = audioStream == null ? 6 : audioStream.Channels ?? 6;
  2115. if (inputChannels >= 6)
  2116. {
  2117. return;
  2118. }
  2119. // Transcoding to 2ch ac3 almost always causes a playback failure
  2120. // Keep it in the supported codecs list, but shift it to the end of the list so that if transcoding happens, another codec is used
  2121. var shiftAudioCodecs = new[] { "ac3", "eac3" };
  2122. if (audioCodecs.All(i => shiftAudioCodecs.Contains(i, StringComparer.OrdinalIgnoreCase)))
  2123. {
  2124. return;
  2125. }
  2126. while (shiftAudioCodecs.Contains(audioCodecs[0], StringComparer.OrdinalIgnoreCase))
  2127. {
  2128. var removed = shiftAudioCodecs[0];
  2129. audioCodecs.RemoveAt(0);
  2130. audioCodecs.Add(removed);
  2131. }
  2132. }
  2133. private void NormalizeSubtitleEmbed(EncodingJobInfo state)
  2134. {
  2135. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  2136. {
  2137. return;
  2138. }
  2139. // This is tricky to remux in, after converting to dvdsub it's not positioned correctly
  2140. // Therefore, let's just burn it in
  2141. if (string.Equals(state.SubtitleStream.Codec, "DVBSUB", StringComparison.OrdinalIgnoreCase))
  2142. {
  2143. state.SubtitleDeliveryMethod = SubtitleDeliveryMethod.Encode;
  2144. }
  2145. }
  2146. /// <summary>
  2147. /// Gets the name of the output video codec
  2148. /// </summary>
  2149. protected string GetHardwareAcceleratedVideoDecoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  2150. {
  2151. var videoType = state.MediaSource.VideoType ?? VideoType.VideoFile;
  2152. var videoStream = state.VideoStream;
  2153. var IsColorDepth10 = (videoStream.Profile ?? string.Empty).IndexOf("10", StringComparison.OrdinalIgnoreCase) != -1;
  2154. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  2155. {
  2156. return null;
  2157. }
  2158. // Only use alternative encoders for video files.
  2159. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  2160. // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
  2161. if (videoType != VideoType.VideoFile)
  2162. {
  2163. return null;
  2164. }
  2165. if (videoStream != null
  2166. && !string.IsNullOrEmpty(videoStream.Codec)
  2167. && !string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
  2168. {
  2169. // Only hevc and vp9 formats have 10-bit hardware decoder support now.
  2170. if (IsColorDepth10 && !(string.Equals(videoStream.Codec, "hevc", StringComparison.OrdinalIgnoreCase)
  2171. || string.Equals(videoStream.Codec, "h265", StringComparison.OrdinalIgnoreCase)
  2172. || string.Equals(videoStream.Codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  2173. {
  2174. return null;
  2175. }
  2176. if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  2177. {
  2178. switch (videoStream.Codec.ToLowerInvariant())
  2179. {
  2180. case "avc":
  2181. case "h264":
  2182. if (_mediaEncoder.SupportsDecoder("h264_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2183. {
  2184. // qsv decoder does not support 10-bit input
  2185. if ((videoStream.BitDepth ?? 8) > 8)
  2186. {
  2187. encodingOptions.HardwareDecodingCodecs = Array.Empty<string>();
  2188. return null;
  2189. }
  2190. return "-c:v h264_qsv";
  2191. }
  2192. break;
  2193. case "hevc":
  2194. case "h265":
  2195. if (_mediaEncoder.SupportsDecoder("hevc_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
  2196. {
  2197. if (IsColorDepth10)
  2198. {
  2199. if (encodingOptions.EnableDecodingColorDepth10)
  2200. {
  2201. return "-c:v hevc_qsv ";
  2202. }
  2203. return null;
  2204. }
  2205. return "-c:v hevc_qsv ";
  2206. }
  2207. break;
  2208. case "mpeg2video":
  2209. if (_mediaEncoder.SupportsDecoder("mpeg2_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2210. {
  2211. return "-c:v mpeg2_qsv";
  2212. }
  2213. break;
  2214. case "vc1":
  2215. if (_mediaEncoder.SupportsDecoder("vc1_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2216. {
  2217. return "-c:v vc1_qsv";
  2218. }
  2219. break;
  2220. case "vp8":
  2221. if (_mediaEncoder.SupportsDecoder("vp8_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase))
  2222. {
  2223. return "-c:v vp8_qsv ";
  2224. }
  2225. break;
  2226. case "vp9":
  2227. if (_mediaEncoder.SupportsDecoder("vp9_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
  2228. {
  2229. if (IsColorDepth10)
  2230. {
  2231. if (encodingOptions.EnableDecodingColorDepth10)
  2232. {
  2233. return "-c:v vp9_qsv ";
  2234. }
  2235. return null;
  2236. }
  2237. return "-c:v vp9_qsv ";
  2238. }
  2239. break;
  2240. }
  2241. }
  2242. else if (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  2243. {
  2244. switch (videoStream.Codec.ToLowerInvariant())
  2245. {
  2246. case "avc":
  2247. case "h264":
  2248. if (_mediaEncoder.SupportsDecoder("h264_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2249. {
  2250. // cuvid decoder does not support 10-bit input
  2251. if ((videoStream.BitDepth ?? 8) > 8)
  2252. {
  2253. encodingOptions.HardwareDecodingCodecs = Array.Empty<string>();
  2254. return null;
  2255. }
  2256. return "-c:v h264_cuvid";
  2257. }
  2258. break;
  2259. case "hevc":
  2260. case "h265":
  2261. if (_mediaEncoder.SupportsDecoder("hevc_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
  2262. {
  2263. if (IsColorDepth10)
  2264. {
  2265. if (encodingOptions.EnableDecodingColorDepth10)
  2266. {
  2267. return "-c:v hevc_cuvid ";
  2268. }
  2269. return null;
  2270. }
  2271. return "-c:v hevc_cuvid ";
  2272. }
  2273. break;
  2274. case "mpeg2video":
  2275. if (_mediaEncoder.SupportsDecoder("mpeg2_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2276. {
  2277. return "-c:v mpeg2_cuvid";
  2278. }
  2279. break;
  2280. case "vc1":
  2281. if (_mediaEncoder.SupportsDecoder("vc1_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2282. {
  2283. return "-c:v vc1_cuvid";
  2284. }
  2285. break;
  2286. case "mpeg4":
  2287. if (_mediaEncoder.SupportsDecoder("mpeg4_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2288. {
  2289. return "-c:v mpeg4_cuvid";
  2290. }
  2291. break;
  2292. case "vp8":
  2293. if (_mediaEncoder.SupportsDecoder("vp8_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase))
  2294. {
  2295. return "-c:v vp8_cuvid ";
  2296. }
  2297. break;
  2298. case "vp9":
  2299. if (_mediaEncoder.SupportsDecoder("vp9_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
  2300. {
  2301. if (IsColorDepth10)
  2302. {
  2303. if (encodingOptions.EnableDecodingColorDepth10)
  2304. {
  2305. return "-c:v vp9_cuvid ";
  2306. }
  2307. return null;
  2308. }
  2309. return "-c:v vp9_cuvid ";
  2310. }
  2311. break;
  2312. }
  2313. }
  2314. else if (string.Equals(encodingOptions.HardwareAccelerationType, "mediacodec", StringComparison.OrdinalIgnoreCase))
  2315. {
  2316. switch (videoStream.Codec.ToLowerInvariant())
  2317. {
  2318. case "avc":
  2319. case "h264":
  2320. if (_mediaEncoder.SupportsDecoder("h264_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2321. {
  2322. return "-c:v h264_mediacodec";
  2323. }
  2324. break;
  2325. case "hevc":
  2326. case "h265":
  2327. if (_mediaEncoder.SupportsDecoder("hevc_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
  2328. {
  2329. if (IsColorDepth10)
  2330. {
  2331. if (encodingOptions.EnableDecodingColorDepth10)
  2332. {
  2333. return "-c:v hevc_mediacodec ";
  2334. }
  2335. return null;
  2336. }
  2337. return "-c:v hevc_mediacodec ";
  2338. }
  2339. break;
  2340. case "mpeg2video":
  2341. if (_mediaEncoder.SupportsDecoder("mpeg2_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2342. {
  2343. return "-c:v mpeg2_mediacodec";
  2344. }
  2345. break;
  2346. case "mpeg4":
  2347. if (_mediaEncoder.SupportsDecoder("mpeg4_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2348. {
  2349. return "-c:v mpeg4_mediacodec";
  2350. }
  2351. break;
  2352. case "vp8":
  2353. if (_mediaEncoder.SupportsDecoder("vp8_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase))
  2354. {
  2355. return "-c:v vp8_mediacodec";
  2356. }
  2357. break;
  2358. case "vp9":
  2359. if (_mediaEncoder.SupportsDecoder("vp9_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
  2360. {
  2361. if (IsColorDepth10)
  2362. {
  2363. if (encodingOptions.EnableDecodingColorDepth10)
  2364. {
  2365. return "-c:v vp9_mediacodec ";
  2366. }
  2367. return null;
  2368. }
  2369. return "-c:v vp9_mediacodec ";
  2370. }
  2371. break;
  2372. }
  2373. }
  2374. else if (string.Equals(encodingOptions.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase))
  2375. {
  2376. switch (videoStream.Codec.ToLowerInvariant())
  2377. {
  2378. case "avc":
  2379. case "h264":
  2380. if (_mediaEncoder.SupportsDecoder("h264_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2381. {
  2382. return "-c:v h264_mmal";
  2383. }
  2384. break;
  2385. case "mpeg2video":
  2386. if (_mediaEncoder.SupportsDecoder("mpeg2_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2387. {
  2388. return "-c:v mpeg2_mmal";
  2389. }
  2390. break;
  2391. case "mpeg4":
  2392. if (_mediaEncoder.SupportsDecoder("mpeg4_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2393. {
  2394. return "-c:v mpeg4_mmal";
  2395. }
  2396. break;
  2397. case "vc1":
  2398. if (_mediaEncoder.SupportsDecoder("vc1_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2399. {
  2400. return "-c:v vc1_mmal";
  2401. }
  2402. break;
  2403. }
  2404. }
  2405. else if (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  2406. {
  2407. switch (videoStream.Codec.ToLowerInvariant())
  2408. {
  2409. case "avc":
  2410. case "h264":
  2411. return GetHwaccelType(state, encodingOptions, "h264");
  2412. case "hevc":
  2413. case "h265":
  2414. if (IsColorDepth10)
  2415. {
  2416. if (encodingOptions.EnableDecodingColorDepth10)
  2417. {
  2418. return GetHwaccelType(state, encodingOptions, "hevc");
  2419. }
  2420. return null;
  2421. }
  2422. return GetHwaccelType(state, encodingOptions, "hevc");
  2423. case "mpeg2video":
  2424. return GetHwaccelType(state, encodingOptions, "mpeg2video");
  2425. case "vc1":
  2426. return GetHwaccelType(state, encodingOptions, "vc1");
  2427. case "mpeg4":
  2428. return GetHwaccelType(state, encodingOptions, "mpeg4");
  2429. case "vp9":
  2430. if (IsColorDepth10)
  2431. {
  2432. if (encodingOptions.EnableDecodingColorDepth10)
  2433. {
  2434. return GetHwaccelType(state, encodingOptions, "vp9");
  2435. }
  2436. return null;
  2437. }
  2438. return GetHwaccelType(state, encodingOptions, "vp9");
  2439. }
  2440. }
  2441. else if (string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  2442. {
  2443. switch (videoStream.Codec.ToLowerInvariant())
  2444. {
  2445. case "avc":
  2446. case "h264":
  2447. return GetHwaccelType(state, encodingOptions, "h264");
  2448. case "hevc":
  2449. case "h265":
  2450. if (IsColorDepth10)
  2451. {
  2452. if (encodingOptions.EnableDecodingColorDepth10)
  2453. {
  2454. return GetHwaccelType(state, encodingOptions, "hevc");
  2455. }
  2456. return null;
  2457. }
  2458. return GetHwaccelType(state, encodingOptions, "hevc");
  2459. case "mpeg2video":
  2460. return GetHwaccelType(state, encodingOptions, "mpeg2video");
  2461. case "vc1":
  2462. return GetHwaccelType(state, encodingOptions, "vc1");
  2463. case "vp8":
  2464. return GetHwaccelType(state, encodingOptions, "vp8");
  2465. case "vp9":
  2466. if (IsColorDepth10)
  2467. {
  2468. if (encodingOptions.EnableDecodingColorDepth10)
  2469. {
  2470. return GetHwaccelType(state, encodingOptions, "vp9");
  2471. }
  2472. return null;
  2473. }
  2474. return GetHwaccelType(state, encodingOptions, "vp9");
  2475. }
  2476. }
  2477. }
  2478. var whichCodec = videoStream.Codec.ToLowerInvariant();
  2479. switch (whichCodec)
  2480. {
  2481. case "avc":
  2482. whichCodec = "h264";
  2483. break;
  2484. case "h265":
  2485. whichCodec = "hevc";
  2486. break;
  2487. }
  2488. // Avoid a second attempt if no hardware acceleration is being used
  2489. encodingOptions.HardwareDecodingCodecs = encodingOptions.HardwareDecodingCodecs.Where(val => val != whichCodec).ToArray();
  2490. // leave blank so ffmpeg will decide
  2491. return null;
  2492. }
  2493. /// <summary>
  2494. /// Gets a hwaccel type to use as a hardware decoder(dxva/vaapi) depending on the system
  2495. /// </summary>
  2496. public string GetHwaccelType(EncodingJobInfo state, EncodingOptions options, string videoCodec)
  2497. {
  2498. var IsWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;
  2499. var IsNewWindows = Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1);
  2500. var IsDxvaSupported = _mediaEncoder.SupportsHwaccel("dxva2") || _mediaEncoder.SupportsHwaccel("d3d11va");
  2501. if ((IsDxvaSupported || IsVaapiSupported(state)) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  2502. {
  2503. if (!IsWindows)
  2504. {
  2505. return "-hwaccel vaapi ";
  2506. }
  2507. else if (IsWindows && IsNewWindows)
  2508. {
  2509. return "-hwaccel d3d11va ";
  2510. }
  2511. else if (IsWindows && !IsNewWindows)
  2512. {
  2513. return "-hwaccel dxva2 ";
  2514. }
  2515. }
  2516. return null;
  2517. }
  2518. public string GetSubtitleEmbedArguments(EncodingJobInfo state)
  2519. {
  2520. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  2521. {
  2522. return string.Empty;
  2523. }
  2524. var format = state.SupportedSubtitleCodecs.FirstOrDefault();
  2525. string codec;
  2526. if (string.IsNullOrEmpty(format) || string.Equals(format, state.SubtitleStream.Codec, StringComparison.OrdinalIgnoreCase))
  2527. {
  2528. codec = "copy";
  2529. }
  2530. else
  2531. {
  2532. codec = format;
  2533. }
  2534. return " -codec:s:0 " + codec + " -disposition:s:0 default";
  2535. }
  2536. public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath, string defaultPreset)
  2537. {
  2538. // Get the output codec name
  2539. var videoCodec = GetVideoEncoder(state, encodingOptions);
  2540. var format = string.Empty;
  2541. var keyFrame = string.Empty;
  2542. if (string.Equals(Path.GetExtension(outputPath), ".mp4", StringComparison.OrdinalIgnoreCase)
  2543. && state.BaseRequest.Context == EncodingContext.Streaming)
  2544. {
  2545. // Comparison: https://github.com/jansmolders86/mediacenterjs/blob/master/lib/transcoding/desktop.js
  2546. format = " -f mp4 -movflags frag_keyframe+empty_moov";
  2547. }
  2548. var threads = GetNumberOfThreads(state, encodingOptions, videoCodec);
  2549. var inputModifier = GetInputModifier(state, encodingOptions);
  2550. return string.Format(
  2551. CultureInfo.InvariantCulture,
  2552. "{0} {1}{2} {3} {4} -map_metadata -1 -map_chapters -1 -threads {5} {6}{7}{8} -y \"{9}\"",
  2553. inputModifier,
  2554. GetInputArgument(state, encodingOptions),
  2555. keyFrame,
  2556. GetMapArgs(state),
  2557. GetProgressiveVideoArguments(state, encodingOptions, videoCodec, defaultPreset),
  2558. threads,
  2559. GetProgressiveVideoAudioArguments(state, encodingOptions),
  2560. GetSubtitleEmbedArguments(state),
  2561. format,
  2562. outputPath).Trim();
  2563. }
  2564. public string GetOutputFFlags(EncodingJobInfo state)
  2565. {
  2566. var flags = new List<string>();
  2567. if (state.GenPtsOutput)
  2568. {
  2569. flags.Add("+genpts");
  2570. }
  2571. if (flags.Count > 0)
  2572. {
  2573. return " -fflags " + string.Join("", flags);
  2574. }
  2575. return string.Empty;
  2576. }
  2577. public string GetProgressiveVideoArguments(EncodingJobInfo state, EncodingOptions encodingOptions, string videoCodec, string defaultPreset)
  2578. {
  2579. var args = "-codec:v:0 " + videoCodec;
  2580. if (state.BaseRequest.EnableMpegtsM2TsMode)
  2581. {
  2582. args += " -mpegts_m2ts_mode 1";
  2583. }
  2584. if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  2585. {
  2586. if (state.VideoStream != null
  2587. && string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase)
  2588. && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
  2589. {
  2590. string bitStreamArgs = GetBitStreamArgs(state.VideoStream);
  2591. if (!string.IsNullOrEmpty(bitStreamArgs))
  2592. {
  2593. args += " " + bitStreamArgs;
  2594. }
  2595. }
  2596. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  2597. {
  2598. args += " -copyts -avoid_negative_ts disabled -start_at_zero";
  2599. }
  2600. if (!state.RunTimeTicks.HasValue)
  2601. {
  2602. args += " -fflags +genpts";
  2603. }
  2604. }
  2605. else
  2606. {
  2607. var keyFrameArg = string.Format(
  2608. CultureInfo.InvariantCulture,
  2609. " -force_key_frames \"expr:gte(t,n_forced*{0})\"",
  2610. 5);
  2611. args += keyFrameArg;
  2612. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2613. var hasCopyTs = false;
  2614. // Add resolution params, if specified
  2615. if (!hasGraphicalSubs)
  2616. {
  2617. var outputSizeParam = GetOutputSizeParam(state, encodingOptions, videoCodec);
  2618. args += outputSizeParam;
  2619. hasCopyTs = outputSizeParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  2620. }
  2621. // This is for graphical subs
  2622. if (hasGraphicalSubs)
  2623. {
  2624. var graphicalSubtitleParam = GetGraphicalSubtitleParam(state, encodingOptions, videoCodec);
  2625. args += graphicalSubtitleParam;
  2626. hasCopyTs = graphicalSubtitleParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  2627. }
  2628. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  2629. {
  2630. if (!hasCopyTs)
  2631. {
  2632. args += " -copyts";
  2633. }
  2634. args += " -avoid_negative_ts disabled";
  2635. if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
  2636. {
  2637. args += " -start_at_zero";
  2638. }
  2639. }
  2640. var qualityParam = GetVideoQualityParam(state, videoCodec, encodingOptions, defaultPreset);
  2641. if (!string.IsNullOrEmpty(qualityParam))
  2642. {
  2643. args += " " + qualityParam.Trim();
  2644. }
  2645. }
  2646. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  2647. {
  2648. args += " -vsync " + state.OutputVideoSync;
  2649. }
  2650. args += GetOutputFFlags(state);
  2651. return args;
  2652. }
  2653. public string GetProgressiveVideoAudioArguments(EncodingJobInfo state, EncodingOptions encodingOptions)
  2654. {
  2655. // If the video doesn't have an audio stream, return a default.
  2656. if (state.AudioStream == null && state.VideoStream != null)
  2657. {
  2658. return string.Empty;
  2659. }
  2660. // Get the output codec name
  2661. var codec = GetAudioEncoder(state);
  2662. var args = "-codec:a:0 " + codec;
  2663. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  2664. {
  2665. return args;
  2666. }
  2667. // Add the number of audio channels
  2668. var channels = state.OutputAudioChannels;
  2669. if (channels.HasValue)
  2670. {
  2671. args += " -ac " + channels.Value;
  2672. }
  2673. var bitrate = state.OutputAudioBitrate;
  2674. if (bitrate.HasValue)
  2675. {
  2676. args += " -ab " + bitrate.Value.ToString(_usCulture);
  2677. }
  2678. if (state.OutputAudioSampleRate.HasValue)
  2679. {
  2680. args += " -ar " + state.OutputAudioSampleRate.Value.ToString(_usCulture);
  2681. }
  2682. args += " " + GetAudioFilterParam(state, encodingOptions, false);
  2683. return args;
  2684. }
  2685. public string GetProgressiveAudioFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath)
  2686. {
  2687. var audioTranscodeParams = new List<string>();
  2688. var bitrate = state.OutputAudioBitrate;
  2689. if (bitrate.HasValue)
  2690. {
  2691. audioTranscodeParams.Add("-ab " + bitrate.Value.ToString(_usCulture));
  2692. }
  2693. if (state.OutputAudioChannels.HasValue)
  2694. {
  2695. audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(_usCulture));
  2696. }
  2697. // opus will fail on 44100
  2698. if (!string.Equals(state.OutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase))
  2699. {
  2700. if (state.OutputAudioSampleRate.HasValue)
  2701. {
  2702. audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(_usCulture));
  2703. }
  2704. }
  2705. var threads = GetNumberOfThreads(state, encodingOptions, null);
  2706. var inputModifier = GetInputModifier(state, encodingOptions);
  2707. return string.Format(
  2708. CultureInfo.InvariantCulture,
  2709. "{0} {1}{7}{8} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1{6} -y \"{5}\"",
  2710. inputModifier,
  2711. GetInputArgument(state, encodingOptions),
  2712. threads,
  2713. " -vn",
  2714. string.Join(" ", audioTranscodeParams),
  2715. outputPath,
  2716. string.Empty,
  2717. string.Empty,
  2718. string.Empty).Trim();
  2719. }
  2720. }
  2721. }