EncodingHelper.cs 128 KB

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