EncodingHelper.cs 132 KB

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