EncodingHelper.cs 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using Jellyfin.Data.Enums;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.MediaInfo;
  17. namespace MediaBrowser.Controller.MediaEncoding
  18. {
  19. public class EncodingHelper
  20. {
  21. private readonly IMediaEncoder _mediaEncoder;
  22. private readonly ISubtitleEncoder _subtitleEncoder;
  23. private static readonly string[] _videoProfiles = new[]
  24. {
  25. "ConstrainedBaseline",
  26. "Baseline",
  27. "Extended",
  28. "Main",
  29. "High",
  30. "ProgressiveHigh",
  31. "ConstrainedHigh"
  32. };
  33. private static readonly Version _minVersionForCudaOverlay = new Version(4, 4);
  34. public EncodingHelper(
  35. IMediaEncoder mediaEncoder,
  36. ISubtitleEncoder subtitleEncoder)
  37. {
  38. _mediaEncoder = mediaEncoder;
  39. _subtitleEncoder = subtitleEncoder;
  40. }
  41. public string GetH264Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  42. => GetH264OrH265Encoder("libx264", "h264", state, encodingOptions);
  43. public string GetH265Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  44. => GetH264OrH265Encoder("libx265", "hevc", state, encodingOptions);
  45. private string GetH264OrH265Encoder(string defaultEncoder, string hwEncoder, EncodingJobInfo state, EncodingOptions encodingOptions)
  46. {
  47. // Only use alternative encoders for video files.
  48. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  49. // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this.
  50. if (state.VideoType == VideoType.VideoFile)
  51. {
  52. var hwType = encodingOptions.HardwareAccelerationType;
  53. var codecMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
  54. {
  55. { "qsv", hwEncoder + "_qsv" },
  56. { hwEncoder + "_qsv", hwEncoder + "_qsv" },
  57. { "nvenc", hwEncoder + "_nvenc" },
  58. { "amf", hwEncoder + "_amf" },
  59. { "omx", hwEncoder + "_omx" },
  60. { hwEncoder + "_v4l2m2m", hwEncoder + "_v4l2m2m" },
  61. { "mediacodec", hwEncoder + "_mediacodec" },
  62. { "vaapi", hwEncoder + "_vaapi" },
  63. { "videotoolbox", hwEncoder + "_videotoolbox" }
  64. };
  65. if (!string.IsNullOrEmpty(hwType)
  66. && encodingOptions.EnableHardwareEncoding
  67. && codecMap.ContainsKey(hwType))
  68. {
  69. var preferredEncoder = codecMap[hwType];
  70. if (_mediaEncoder.SupportsEncoder(preferredEncoder))
  71. {
  72. return preferredEncoder;
  73. }
  74. }
  75. }
  76. return defaultEncoder;
  77. }
  78. private bool IsVaapiSupported(EncodingJobInfo state)
  79. {
  80. var videoStream = state.VideoStream;
  81. // vaapi will throw an error with this input
  82. // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
  83. if (string.Equals(videoStream?.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  84. {
  85. return false;
  86. }
  87. return _mediaEncoder.SupportsHwaccel("vaapi");
  88. }
  89. private bool IsCudaSupported()
  90. {
  91. return _mediaEncoder.SupportsHwaccel("cuda")
  92. && _mediaEncoder.SupportsFilter("scale_cuda")
  93. && _mediaEncoder.SupportsFilter("yadif_cuda")
  94. && _mediaEncoder.SupportsFilter("hwupload_cuda");
  95. }
  96. private bool IsOpenclTonemappingSupported(EncodingJobInfo state, EncodingOptions options)
  97. {
  98. var videoStream = state.VideoStream;
  99. if (videoStream == null)
  100. {
  101. return false;
  102. }
  103. return options.EnableTonemapping
  104. && (string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  105. || string.Equals(videoStream.ColorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
  106. && IsColorDepth10(state)
  107. && _mediaEncoder.SupportsHwaccel("opencl")
  108. && _mediaEncoder.SupportsFilter("tonemap_opencl");
  109. }
  110. private bool IsCudaTonemappingSupported(EncodingJobInfo state, EncodingOptions options)
  111. {
  112. var videoStream = state.VideoStream;
  113. if (videoStream == null)
  114. {
  115. return false;
  116. }
  117. return options.EnableTonemapping
  118. && (string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  119. || string.Equals(videoStream.ColorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
  120. && IsColorDepth10(state)
  121. && _mediaEncoder.SupportsHwaccel("cuda")
  122. && _mediaEncoder.SupportsFilterWithOption(FilterOptionType.TonemapCudaName);
  123. }
  124. private bool IsVppTonemappingSupported(EncodingJobInfo state, EncodingOptions options)
  125. {
  126. var videoStream = state.VideoStream;
  127. if (videoStream == null)
  128. {
  129. // Remote stream doesn't have media info, disable vpp tonemapping.
  130. return false;
  131. }
  132. var codec = videoStream.Codec;
  133. if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  134. {
  135. // Limited to HEVC for now since the filter doesn't accept master data from VP9.
  136. return options.EnableVppTonemapping
  137. && string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  138. && IsColorDepth10(state)
  139. && string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  140. && _mediaEncoder.SupportsHwaccel("vaapi")
  141. && _mediaEncoder.SupportsFilter("tonemap_vaapi");
  142. }
  143. // Hybrid VPP tonemapping for QSV with VAAPI
  144. if (OperatingSystem.IsLinux() && string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  145. {
  146. // Limited to HEVC for now since the filter doesn't accept master data from VP9.
  147. return options.EnableVppTonemapping
  148. && string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  149. && IsColorDepth10(state)
  150. && string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  151. && _mediaEncoder.SupportsHwaccel("vaapi")
  152. && _mediaEncoder.SupportsFilter("tonemap_vaapi")
  153. && _mediaEncoder.SupportsHwaccel("qsv");
  154. }
  155. // Native VPP tonemapping may come to QSV in the future.
  156. return false;
  157. }
  158. /// <summary>
  159. /// Gets the name of the output video codec.
  160. /// </summary>
  161. /// <param name="state">Encording state.</param>
  162. /// <param name="encodingOptions">Encoding options.</param>
  163. /// <returns>Encoder string.</returns>
  164. public string GetVideoEncoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  165. {
  166. var codec = state.OutputVideoCodec;
  167. if (!string.IsNullOrEmpty(codec))
  168. {
  169. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  170. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
  171. {
  172. return GetH265Encoder(state, encodingOptions);
  173. }
  174. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  175. {
  176. return GetH264Encoder(state, encodingOptions);
  177. }
  178. if (string.Equals(codec, "vp8", StringComparison.OrdinalIgnoreCase)
  179. || string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  180. {
  181. return "libvpx";
  182. }
  183. if (string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  184. {
  185. return "libvpx-vp9";
  186. }
  187. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  188. {
  189. return "wmv2";
  190. }
  191. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  192. {
  193. return "libtheora";
  194. }
  195. return codec.ToLowerInvariant();
  196. }
  197. return "copy";
  198. }
  199. /// <summary>
  200. /// Gets the user agent param.
  201. /// </summary>
  202. /// <param name="state">The state.</param>
  203. /// <returns>System.String.</returns>
  204. public string GetUserAgentParam(EncodingJobInfo state)
  205. {
  206. if (state.RemoteHttpHeaders.TryGetValue("User-Agent", out string useragent))
  207. {
  208. return "-user_agent \"" + useragent + "\"";
  209. }
  210. return string.Empty;
  211. }
  212. public static string GetInputFormat(string container)
  213. {
  214. if (string.IsNullOrEmpty(container))
  215. {
  216. return null;
  217. }
  218. container = container.Replace("mkv", "matroska", StringComparison.OrdinalIgnoreCase);
  219. if (string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
  220. {
  221. return "mpegts";
  222. }
  223. // For these need to find out the ffmpeg names
  224. if (string.Equals(container, "m2ts", StringComparison.OrdinalIgnoreCase))
  225. {
  226. return null;
  227. }
  228. if (string.Equals(container, "wmv", StringComparison.OrdinalIgnoreCase))
  229. {
  230. return null;
  231. }
  232. if (string.Equals(container, "mts", StringComparison.OrdinalIgnoreCase))
  233. {
  234. return null;
  235. }
  236. if (string.Equals(container, "vob", StringComparison.OrdinalIgnoreCase))
  237. {
  238. return null;
  239. }
  240. if (string.Equals(container, "mpg", StringComparison.OrdinalIgnoreCase))
  241. {
  242. return null;
  243. }
  244. if (string.Equals(container, "mpeg", StringComparison.OrdinalIgnoreCase))
  245. {
  246. return null;
  247. }
  248. if (string.Equals(container, "rec", StringComparison.OrdinalIgnoreCase))
  249. {
  250. return null;
  251. }
  252. if (string.Equals(container, "dvr-ms", StringComparison.OrdinalIgnoreCase))
  253. {
  254. return null;
  255. }
  256. if (string.Equals(container, "ogm", StringComparison.OrdinalIgnoreCase))
  257. {
  258. return null;
  259. }
  260. if (string.Equals(container, "divx", StringComparison.OrdinalIgnoreCase))
  261. {
  262. return null;
  263. }
  264. if (string.Equals(container, "tp", StringComparison.OrdinalIgnoreCase))
  265. {
  266. return null;
  267. }
  268. if (string.Equals(container, "rmvb", StringComparison.OrdinalIgnoreCase))
  269. {
  270. return null;
  271. }
  272. if (string.Equals(container, "rtp", StringComparison.OrdinalIgnoreCase))
  273. {
  274. return null;
  275. }
  276. // Seeing reported failures here, not sure yet if this is related to specifying input format
  277. if (string.Equals(container, "m4v", StringComparison.OrdinalIgnoreCase))
  278. {
  279. return null;
  280. }
  281. // obviously don't do this for strm files
  282. if (string.Equals(container, "strm", StringComparison.OrdinalIgnoreCase))
  283. {
  284. return null;
  285. }
  286. // ISO files don't have an ffmpeg format
  287. if (string.Equals(container, "iso", StringComparison.OrdinalIgnoreCase))
  288. {
  289. return null;
  290. }
  291. return container;
  292. }
  293. /// <summary>
  294. /// Gets decoder from a codec.
  295. /// </summary>
  296. /// <param name="codec">Codec to use.</param>
  297. /// <returns>Decoder string.</returns>
  298. public string GetDecoderFromCodec(string codec)
  299. {
  300. // For these need to find out the ffmpeg names
  301. if (string.Equals(codec, "mp2", StringComparison.OrdinalIgnoreCase))
  302. {
  303. return null;
  304. }
  305. if (string.Equals(codec, "aac_latm", StringComparison.OrdinalIgnoreCase))
  306. {
  307. return null;
  308. }
  309. if (string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
  310. {
  311. return null;
  312. }
  313. if (_mediaEncoder.SupportsDecoder(codec))
  314. {
  315. return codec;
  316. }
  317. return null;
  318. }
  319. /// <summary>
  320. /// Infers the audio codec based on the url.
  321. /// </summary>
  322. /// <param name="container">Container to use.</param>
  323. /// <returns>Codec string.</returns>
  324. public string InferAudioCodec(string container)
  325. {
  326. var ext = "." + (container ?? string.Empty);
  327. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  328. {
  329. return "mp3";
  330. }
  331. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  332. {
  333. return "aac";
  334. }
  335. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  336. {
  337. return "wma";
  338. }
  339. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  340. {
  341. return "vorbis";
  342. }
  343. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  344. {
  345. return "vorbis";
  346. }
  347. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  348. {
  349. return "vorbis";
  350. }
  351. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  352. {
  353. return "vorbis";
  354. }
  355. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  356. {
  357. return "vorbis";
  358. }
  359. return "copy";
  360. }
  361. /// <summary>
  362. /// Infers the video codec.
  363. /// </summary>
  364. /// <param name="url">The URL.</param>
  365. /// <returns>System.Nullable{VideoCodecs}.</returns>
  366. public string InferVideoCodec(string url)
  367. {
  368. var ext = Path.GetExtension(url);
  369. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  370. {
  371. return "wmv";
  372. }
  373. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  374. {
  375. // TODO: this may not always mean VP8, as the codec ages
  376. return "vp8";
  377. }
  378. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  379. {
  380. return "theora";
  381. }
  382. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  383. {
  384. return "h264";
  385. }
  386. return "copy";
  387. }
  388. public int GetVideoProfileScore(string profile)
  389. {
  390. // strip spaces because they may be stripped out on the query string
  391. profile = profile.Replace(" ", string.Empty, StringComparison.Ordinal);
  392. return Array.FindIndex(_videoProfiles, x => string.Equals(x, profile, StringComparison.OrdinalIgnoreCase));
  393. }
  394. public string GetInputPathArgument(EncodingJobInfo state)
  395. {
  396. var mediaPath = state.MediaPath ?? string.Empty;
  397. return _mediaEncoder.GetInputArgument(mediaPath, state.MediaSource);
  398. }
  399. /// <summary>
  400. /// Gets the audio encoder.
  401. /// </summary>
  402. /// <param name="state">The state.</param>
  403. /// <returns>System.String.</returns>
  404. public string GetAudioEncoder(EncodingJobInfo state)
  405. {
  406. var codec = state.OutputAudioCodec;
  407. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  408. {
  409. // Use libfdk_aac for better audio quality if using custom build of FFmpeg which has fdk_aac support
  410. if (_mediaEncoder.SupportsEncoder("libfdk_aac"))
  411. {
  412. return "libfdk_aac";
  413. }
  414. return "aac";
  415. }
  416. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  417. {
  418. return "libmp3lame";
  419. }
  420. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  421. {
  422. return "libvorbis";
  423. }
  424. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  425. {
  426. return "wmav2";
  427. }
  428. if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
  429. {
  430. return "libopus";
  431. }
  432. if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase))
  433. {
  434. // flac is experimental in mp4 muxer
  435. return "flac -strict -2";
  436. }
  437. return codec.ToLowerInvariant();
  438. }
  439. /// <summary>
  440. /// Gets the input argument.
  441. /// </summary>
  442. /// <param name="state">Encoding state.</param>
  443. /// <param name="options">Encoding options.</param>
  444. /// <returns>Input arguments.</returns>
  445. public string GetInputArgument(EncodingJobInfo state, EncodingOptions options)
  446. {
  447. var arg = new StringBuilder();
  448. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
  449. var outputVideoCodec = GetVideoEncoder(state, options) ?? string.Empty;
  450. var isWindows = OperatingSystem.IsWindows();
  451. var isLinux = OperatingSystem.IsLinux();
  452. var isMacOS = OperatingSystem.IsMacOS();
  453. #pragma warning disable CA1508 // Defaults to string.Empty
  454. var isSwDecoder = string.IsNullOrEmpty(videoDecoder);
  455. #pragma warning restore CA1508
  456. var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1;
  457. var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  458. var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  459. var isQsvDecoder = videoDecoder.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
  460. var isQsvEncoder = outputVideoCodec.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
  461. var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  462. var isCuvidHevcDecoder = videoDecoder.Contains("hevc_cuvid", StringComparison.OrdinalIgnoreCase);
  463. var isCuvidVp9Decoder = videoDecoder.Contains("vp9_cuvid", StringComparison.OrdinalIgnoreCase);
  464. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  465. var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
  466. var isCudaTonemappingSupported = IsCudaTonemappingSupported(state, options);
  467. if (!IsCopyCodec(outputVideoCodec))
  468. {
  469. if (state.IsVideoRequest
  470. && _mediaEncoder.SupportsHwaccel("vaapi")
  471. && string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  472. {
  473. if (isVaapiDecoder)
  474. {
  475. if (isOpenclTonemappingSupported && !isVppTonemappingSupported)
  476. {
  477. arg.Append("-init_hw_device vaapi=va:")
  478. .Append(options.VaapiDevice)
  479. .Append(" -init_hw_device opencl=ocl@va ")
  480. .Append("-hwaccel_device va ")
  481. .Append("-hwaccel_output_format vaapi ")
  482. .Append("-filter_hw_device ocl ");
  483. }
  484. else
  485. {
  486. arg.Append("-hwaccel_output_format vaapi ")
  487. .Append("-vaapi_device ")
  488. .Append(options.VaapiDevice)
  489. .Append(' ');
  490. }
  491. }
  492. else if (!isVaapiDecoder && isVaapiEncoder)
  493. {
  494. arg.Append("-vaapi_device ")
  495. .Append(options.VaapiDevice)
  496. .Append(' ');
  497. }
  498. arg.Append("-autorotate 0 ");
  499. }
  500. if (state.IsVideoRequest
  501. && string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  502. {
  503. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  504. if (isQsvEncoder)
  505. {
  506. if (isQsvDecoder)
  507. {
  508. if (isLinux)
  509. {
  510. if (hasGraphicalSubs)
  511. {
  512. arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
  513. }
  514. else
  515. {
  516. arg.Append("-hwaccel qsv ");
  517. }
  518. }
  519. if (isWindows)
  520. {
  521. arg.Append("-hwaccel qsv ");
  522. }
  523. }
  524. // While using SW decoder
  525. else if (isSwDecoder)
  526. {
  527. arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
  528. }
  529. // Hybrid VPP tonemapping with VAAPI
  530. else if (isVaapiDecoder && isVppTonemappingSupported)
  531. {
  532. arg.Append("-init_hw_device vaapi=va:")
  533. .Append(options.VaapiDevice)
  534. .Append(" -init_hw_device qsv@va ")
  535. .Append("-hwaccel_output_format vaapi ");
  536. }
  537. arg.Append("-autorotate 0 ");
  538. }
  539. }
  540. if (state.IsVideoRequest
  541. && string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)
  542. && isNvdecDecoder)
  543. {
  544. // Fix for 'No decoder surfaces left' error. https://trac.ffmpeg.org/ticket/7562
  545. arg.Append("-hwaccel_output_format cuda -extra_hw_frames 3 -autorotate 0 ");
  546. }
  547. if (state.IsVideoRequest
  548. && string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)
  549. && (isNvdecDecoder || isCuvidHevcDecoder || isCuvidVp9Decoder || isSwDecoder))
  550. {
  551. if (!isCudaTonemappingSupported && isOpenclTonemappingSupported)
  552. {
  553. arg.Append("-init_hw_device opencl=ocl:")
  554. .Append(options.OpenclDevice)
  555. .Append(" -filter_hw_device ocl ");
  556. }
  557. }
  558. if (state.IsVideoRequest
  559. && string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase)
  560. && (isD3d11vaDecoder || isSwDecoder))
  561. {
  562. if (isOpenclTonemappingSupported)
  563. {
  564. arg.Append("-init_hw_device opencl=ocl:")
  565. .Append(options.OpenclDevice)
  566. .Append(" -filter_hw_device ocl ");
  567. }
  568. }
  569. if (state.IsVideoRequest
  570. && string.Equals(options.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  571. {
  572. arg.Append("-hwaccel videotoolbox ");
  573. }
  574. }
  575. arg.Append("-i ")
  576. .Append(GetInputPathArgument(state));
  577. if (state.SubtitleStream != null
  578. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode
  579. && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  580. {
  581. var subtitlePath = state.SubtitleStream.Path;
  582. if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
  583. {
  584. var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
  585. if (File.Exists(idxFile))
  586. {
  587. subtitlePath = idxFile;
  588. }
  589. }
  590. arg.Append(" -i \"").Append(subtitlePath).Append('\"');
  591. }
  592. return arg.ToString();
  593. }
  594. /// <summary>
  595. /// Determines whether the specified stream is H264.
  596. /// </summary>
  597. /// <param name="stream">The stream.</param>
  598. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  599. public static bool IsH264(MediaStream stream)
  600. {
  601. var codec = stream.Codec ?? string.Empty;
  602. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1
  603. || codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  604. }
  605. public static bool IsH265(MediaStream stream)
  606. {
  607. var codec = stream.Codec ?? string.Empty;
  608. return codec.IndexOf("265", StringComparison.OrdinalIgnoreCase) != -1
  609. || codec.IndexOf("hevc", StringComparison.OrdinalIgnoreCase) != -1;
  610. }
  611. public static bool IsAAC(MediaStream stream)
  612. {
  613. var codec = stream.Codec ?? string.Empty;
  614. return codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1;
  615. }
  616. public static string GetBitStreamArgs(MediaStream stream)
  617. {
  618. // TODO This is auto inserted into the mpegts mux so it might not be needed.
  619. // https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb
  620. if (IsH264(stream))
  621. {
  622. return "-bsf:v h264_mp4toannexb";
  623. }
  624. else if (IsH265(stream))
  625. {
  626. return "-bsf:v hevc_mp4toannexb";
  627. }
  628. else if (IsAAC(stream))
  629. {
  630. // Convert adts header(mpegts) to asc header(mp4).
  631. return "-bsf:a aac_adtstoasc";
  632. }
  633. else
  634. {
  635. return null;
  636. }
  637. }
  638. public static string GetAudioBitStreamArguments(EncodingJobInfo state, string segmentContainer, string mediaSourceContainer)
  639. {
  640. var bitStreamArgs = string.Empty;
  641. var segmentFormat = GetSegmentFileExtension(segmentContainer).TrimStart('.');
  642. // Apply aac_adtstoasc bitstream filter when media source is in mpegts.
  643. if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)
  644. && (string.Equals(mediaSourceContainer, "mpegts", StringComparison.OrdinalIgnoreCase)
  645. || string.Equals(mediaSourceContainer, "hls", StringComparison.OrdinalIgnoreCase)))
  646. {
  647. bitStreamArgs = GetBitStreamArgs(state.AudioStream);
  648. bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs;
  649. }
  650. return bitStreamArgs;
  651. }
  652. public static string GetSegmentFileExtension(string segmentContainer)
  653. {
  654. if (!string.IsNullOrWhiteSpace(segmentContainer))
  655. {
  656. return "." + segmentContainer;
  657. }
  658. return ".ts";
  659. }
  660. public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec)
  661. {
  662. if (state.OutputVideoBitrate == null)
  663. {
  664. return string.Empty;
  665. }
  666. int bitrate = state.OutputVideoBitrate.Value;
  667. // Currently use the same buffer size for all encoders
  668. int bufsize = bitrate * 2;
  669. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)
  670. || string.Equals(videoCodec, "libvpx-vp9", StringComparison.OrdinalIgnoreCase))
  671. {
  672. // When crf is used with vpx, b:v becomes a max rate
  673. // https://trac.ffmpeg.org/wiki/Encode/VP8
  674. // https://trac.ffmpeg.org/wiki/Encode/VP9
  675. return FormattableString.Invariant($" -maxrate:v {bitrate} -bufsize:v {bufsize} -b:v {bitrate}");
  676. }
  677. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  678. {
  679. return FormattableString.Invariant($" -b:v {bitrate}");
  680. }
  681. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase)
  682. || string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  683. {
  684. return FormattableString.Invariant($" -maxrate {bitrate} -bufsize {bufsize}");
  685. }
  686. return FormattableString.Invariant($" -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}");
  687. }
  688. public static string NormalizeTranscodingLevel(EncodingJobInfo state, string level)
  689. {
  690. if (double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out double requestLevel))
  691. {
  692. if (string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)
  693. || string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase))
  694. {
  695. // Transcode to level 5.0 and lower for maximum compatibility.
  696. // Level 5.0 is suitable for up to 4k 30fps hevc encoding, otherwise let the encoder to handle it.
  697. // https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding_tiers_and_levels
  698. // MaxLumaSampleRate = 3840*2160*30 = 248832000 < 267386880.
  699. if (requestLevel >= 150)
  700. {
  701. return "150";
  702. }
  703. }
  704. else if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  705. {
  706. // Clients may direct play higher than level 41, but there's no reason to transcode higher.
  707. if (requestLevel >= 41)
  708. {
  709. return "41";
  710. }
  711. }
  712. }
  713. return level;
  714. }
  715. /// <summary>
  716. /// Gets the text subtitle param.
  717. /// </summary>
  718. /// <param name="state">The state.</param>
  719. /// <returns>System.String.</returns>
  720. public string GetTextSubtitleParam(EncodingJobInfo state)
  721. {
  722. var seconds = Math.Round(TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds);
  723. // hls always copies timestamps
  724. var setPtsParam = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive
  725. ? string.Empty
  726. : string.Format(CultureInfo.InvariantCulture, ",setpts=PTS -{0}/TB", seconds);
  727. // TODO
  728. // var fallbackFontPath = Path.Combine(_appPaths.ProgramDataPath, "fonts", "DroidSansFallback.ttf");
  729. // string fallbackFontParam = string.Empty;
  730. // if (!File.Exists(fallbackFontPath))
  731. // {
  732. // _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath));
  733. // using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf"))
  734. // {
  735. // using (var fileStream = new FileStream(fallbackFontPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  736. // {
  737. // stream.CopyTo(fileStream);
  738. // }
  739. // }
  740. // }
  741. // fallbackFontParam = string.Format(CultureInfo.InvariantCulture, ":force_style='FontName=Droid Sans Fallback':fontsdir='{0}'", _mediaEncoder.EscapeSubtitleFilterPath(_fileSystem.GetDirectoryName(fallbackFontPath)));
  742. if (state.SubtitleStream.IsExternal)
  743. {
  744. var subtitlePath = state.SubtitleStream.Path;
  745. var charsetParam = string.Empty;
  746. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  747. {
  748. var charenc = _subtitleEncoder.GetSubtitleFileCharacterSet(
  749. subtitlePath,
  750. state.SubtitleStream.Language,
  751. state.MediaSource.Protocol,
  752. CancellationToken.None).GetAwaiter().GetResult();
  753. if (!string.IsNullOrEmpty(charenc))
  754. {
  755. charsetParam = ":charenc=" + charenc;
  756. }
  757. }
  758. // TODO: Perhaps also use original_size=1920x800 ??
  759. return string.Format(
  760. CultureInfo.InvariantCulture,
  761. "subtitles=filename='{0}'{1}{2}",
  762. _mediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  763. charsetParam,
  764. // fallbackFontParam,
  765. setPtsParam);
  766. }
  767. var mediaPath = state.MediaPath ?? string.Empty;
  768. return string.Format(
  769. CultureInfo.InvariantCulture,
  770. "subtitles='{0}:si={1}'{2}",
  771. _mediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  772. state.InternalSubtitleStreamOffset.ToString(CultureInfo.InvariantCulture),
  773. // fallbackFontParam,
  774. setPtsParam);
  775. }
  776. public double? GetFramerateParam(EncodingJobInfo state)
  777. {
  778. var request = state.BaseRequest;
  779. if (request.Framerate.HasValue)
  780. {
  781. return request.Framerate.Value;
  782. }
  783. var maxrate = request.MaxFramerate;
  784. if (maxrate.HasValue && state.VideoStream != null)
  785. {
  786. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  787. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  788. {
  789. return maxrate;
  790. }
  791. }
  792. return null;
  793. }
  794. public string GetHlsVideoKeyFrameArguments(
  795. EncodingJobInfo state,
  796. string codec,
  797. int segmentLength,
  798. bool isEventPlaylist,
  799. int? startNumber)
  800. {
  801. var args = string.Empty;
  802. var gopArg = string.Empty;
  803. var keyFrameArg = string.Empty;
  804. if (isEventPlaylist)
  805. {
  806. keyFrameArg = string.Format(
  807. CultureInfo.InvariantCulture,
  808. " -force_key_frames:0 \"expr:gte(t,n_forced*{0})\"",
  809. segmentLength);
  810. }
  811. else if (startNumber.HasValue)
  812. {
  813. keyFrameArg = string.Format(
  814. CultureInfo.InvariantCulture,
  815. " -force_key_frames:0 \"expr:gte(t,{0}+n_forced*{1})\"",
  816. startNumber.Value * segmentLength,
  817. segmentLength);
  818. }
  819. var framerate = state.VideoStream?.RealFrameRate;
  820. if (framerate.HasValue)
  821. {
  822. // This is to make sure keyframe interval is limited to our segment,
  823. // as forcing keyframes is not enough.
  824. // Example: we encoded half of desired length, then codec detected
  825. // scene cut and inserted a keyframe; next forced keyframe would
  826. // be created outside of segment, which breaks seeking.
  827. // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe.
  828. gopArg = string.Format(
  829. CultureInfo.InvariantCulture,
  830. " -g:v:0 {0} -keyint_min:v:0 {0} -sc_threshold:v:0 0",
  831. Math.Ceiling(segmentLength * framerate.Value));
  832. }
  833. // Unable to force key frames using these encoders, set key frames by GOP.
  834. if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  835. || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  836. || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase)
  837. || string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)
  838. || string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
  839. || string.Equals(codec, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  840. {
  841. args += gopArg;
  842. }
  843. else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase)
  844. || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)
  845. || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  846. || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
  847. {
  848. args += " " + keyFrameArg;
  849. }
  850. else
  851. {
  852. args += " " + keyFrameArg + gopArg;
  853. }
  854. return args;
  855. }
  856. /// <summary>
  857. /// Gets the video bitrate to specify on the command line.
  858. /// </summary>
  859. /// <param name="state">Encoding state.</param>
  860. /// <param name="videoEncoder">Video encoder to use.</param>
  861. /// <param name="encodingOptions">Encoding options.</param>
  862. /// <param name="defaultPreset">Default present to use for encoding.</param>
  863. /// <returns>Video bitrate.</returns>
  864. public string GetVideoQualityParam(EncodingJobInfo state, string videoEncoder, EncodingOptions encodingOptions, string defaultPreset)
  865. {
  866. var param = string.Empty;
  867. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  868. && !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  869. && !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  870. && !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  871. && !string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  872. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase)
  873. && !string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)
  874. && !string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)
  875. && !string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
  876. && !string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  877. {
  878. param += " -pix_fmt yuv420p";
  879. }
  880. if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  881. || string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  882. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
  883. || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  884. {
  885. var videoStream = state.VideoStream;
  886. var isColorDepth10 = IsColorDepth10(state);
  887. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions) ?? string.Empty;
  888. var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  889. if (!isNvdecDecoder)
  890. {
  891. if (isColorDepth10
  892. && _mediaEncoder.SupportsHwaccel("opencl")
  893. && encodingOptions.EnableTonemapping
  894. && !string.IsNullOrEmpty(videoStream.VideoRange)
  895. && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase))
  896. {
  897. param += " -pix_fmt nv12";
  898. }
  899. else
  900. {
  901. param += " -pix_fmt yuv420p";
  902. }
  903. }
  904. }
  905. if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  906. {
  907. param += " -pix_fmt nv21";
  908. }
  909. var isVc1 = state.VideoStream != null &&
  910. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  911. var isLibX265 = string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase);
  912. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) || isLibX265)
  913. {
  914. if (!string.IsNullOrEmpty(encodingOptions.EncoderPreset))
  915. {
  916. param += " -preset " + encodingOptions.EncoderPreset;
  917. }
  918. else
  919. {
  920. param += " -preset " + defaultPreset;
  921. }
  922. int encodeCrf = encodingOptions.H264Crf;
  923. if (isLibX265)
  924. {
  925. encodeCrf = encodingOptions.H265Crf;
  926. }
  927. if (encodeCrf >= 0 && encodeCrf <= 51)
  928. {
  929. param += " -crf " + encodeCrf.ToString(CultureInfo.InvariantCulture);
  930. }
  931. else
  932. {
  933. string defaultCrf = "23";
  934. if (isLibX265)
  935. {
  936. defaultCrf = "28";
  937. }
  938. param += " -crf " + defaultCrf;
  939. }
  940. }
  941. else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) // h264 (h264_qsv)
  942. || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_qsv)
  943. {
  944. string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" };
  945. if (valid_h264_qsv.Contains(encodingOptions.EncoderPreset, StringComparer.OrdinalIgnoreCase))
  946. {
  947. param += " -preset " + encodingOptions.EncoderPreset;
  948. }
  949. else
  950. {
  951. param += " -preset 7";
  952. }
  953. param += " -look_ahead 0";
  954. }
  955. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc)
  956. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_nvenc)
  957. {
  958. switch (encodingOptions.EncoderPreset)
  959. {
  960. case "veryslow":
  961. param += " -preset slow"; // lossless is only supported on maxwell and newer(2014+)
  962. break;
  963. case "slow":
  964. case "slower":
  965. param += " -preset slow";
  966. break;
  967. case "medium":
  968. param += " -preset medium";
  969. break;
  970. case "fast":
  971. case "faster":
  972. case "veryfast":
  973. case "superfast":
  974. case "ultrafast":
  975. param += " -preset fast";
  976. break;
  977. default:
  978. param += " -preset default";
  979. break;
  980. }
  981. }
  982. else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) // h264 (h264_amf)
  983. || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_amf)
  984. {
  985. switch (encodingOptions.EncoderPreset)
  986. {
  987. case "veryslow":
  988. case "slow":
  989. case "slower":
  990. param += " -quality quality";
  991. break;
  992. case "medium":
  993. param += " -quality balanced";
  994. break;
  995. case "fast":
  996. case "faster":
  997. case "veryfast":
  998. case "superfast":
  999. case "ultrafast":
  1000. param += " -quality speed";
  1001. break;
  1002. default:
  1003. param += " -quality speed";
  1004. break;
  1005. }
  1006. var videoStream = state.VideoStream;
  1007. var isColorDepth10 = IsColorDepth10(state);
  1008. if (isColorDepth10
  1009. && _mediaEncoder.SupportsHwaccel("opencl")
  1010. && encodingOptions.EnableTonemapping
  1011. && !string.IsNullOrEmpty(videoStream.VideoRange)
  1012. && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase))
  1013. {
  1014. // Enhance workload when tone mapping with AMF on some APUs
  1015. param += " -preanalysis true";
  1016. }
  1017. if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  1018. {
  1019. param += " -header_insertion_mode gop -gops_per_idr 1";
  1020. }
  1021. }
  1022. else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase)) // vp8
  1023. {
  1024. // Values 0-3, 0 being highest quality but slower
  1025. var profileScore = 0;
  1026. string crf;
  1027. var qmin = "0";
  1028. var qmax = "50";
  1029. crf = "10";
  1030. if (isVc1)
  1031. {
  1032. profileScore++;
  1033. }
  1034. // Max of 2
  1035. profileScore = Math.Min(profileScore, 2);
  1036. // http://www.webmproject.org/docs/encoder-parameters/
  1037. param += string.Format(
  1038. CultureInfo.InvariantCulture,
  1039. " -speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  1040. profileScore.ToString(CultureInfo.InvariantCulture),
  1041. crf,
  1042. qmin,
  1043. qmax);
  1044. }
  1045. else if (string.Equals(videoEncoder, "libvpx-vp9", StringComparison.OrdinalIgnoreCase)) // vp9
  1046. {
  1047. // When `-deadline` is set to `good` or `best`, `-cpu-used` ranges from 0-5.
  1048. // When `-deadline` is set to `realtime`, `-cpu-used` ranges from 0-15.
  1049. // Resources:
  1050. // * https://trac.ffmpeg.org/wiki/Encode/VP9
  1051. // * https://superuser.com/questions/1586934
  1052. // * https://developers.google.com/media/vp9
  1053. param += encodingOptions.EncoderPreset switch
  1054. {
  1055. "veryslow" => " -deadline best -cpu-used 0",
  1056. "slower" => " -deadline best -cpu-used 2",
  1057. "slow" => " -deadline best -cpu-used 3",
  1058. "medium" => " -deadline good -cpu-used 0",
  1059. "fast" => " -deadline good -cpu-used 1",
  1060. "faster" => " -deadline good -cpu-used 2",
  1061. "veryfast" => " -deadline good -cpu-used 3",
  1062. "superfast" => " -deadline good -cpu-used 4",
  1063. "ultrafast" => " -deadline good -cpu-used 5",
  1064. _ => " -deadline good -cpu-used 1"
  1065. };
  1066. // TODO: until VP9 gets its own CRF setting, base CRF on H.265.
  1067. int h265Crf = encodingOptions.H265Crf;
  1068. int defaultVp9Crf = 31;
  1069. if (h265Crf >= 0 && h265Crf <= 51)
  1070. {
  1071. // This conversion factor is chosen to match the default CRF for H.265 to the
  1072. // recommended 1080p CRF from Google. The factor also maps the logarithmic CRF
  1073. // scale of x265 [0, 51] to that of VP9 [0, 63] relatively well.
  1074. // Resources:
  1075. // * https://developers.google.com/media/vp9/settings/vod
  1076. const float H265ToVp9CrfConversionFactor = 1.12F;
  1077. var vp9Crf = Convert.ToInt32(h265Crf * H265ToVp9CrfConversionFactor);
  1078. // Encoder allows for CRF values in the range [0, 63].
  1079. vp9Crf = Math.Clamp(vp9Crf, 0, 63);
  1080. param += FormattableString.Invariant($" -crf {vp9Crf}");
  1081. }
  1082. else
  1083. {
  1084. param += FormattableString.Invariant($" -crf {defaultVp9Crf}");
  1085. }
  1086. param += " -row-mt 1 -profile 1";
  1087. }
  1088. else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
  1089. {
  1090. param += " -mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  1091. }
  1092. else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase)) // asf/wmv
  1093. {
  1094. param += " -qmin 2";
  1095. }
  1096. else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  1097. {
  1098. param += " -mbd 2";
  1099. }
  1100. param += GetVideoBitrateParam(state, videoEncoder);
  1101. var framerate = GetFramerateParam(state);
  1102. if (framerate.HasValue)
  1103. {
  1104. param += string.Format(CultureInfo.InvariantCulture, " -r {0}", framerate.Value.ToString(CultureInfo.InvariantCulture));
  1105. }
  1106. var targetVideoCodec = state.ActualOutputVideoCodec;
  1107. if (string.Equals(targetVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  1108. || string.Equals(targetVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
  1109. {
  1110. targetVideoCodec = "hevc";
  1111. }
  1112. var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault() ?? string.Empty;
  1113. profile = Regex.Replace(profile, @"\s+", string.Empty);
  1114. // We only transcode to HEVC 8-bit for now, force Main Profile.
  1115. if (profile.Contains("main10", StringComparison.OrdinalIgnoreCase)
  1116. || profile.Contains("mainstill", StringComparison.OrdinalIgnoreCase))
  1117. {
  1118. profile = "main";
  1119. }
  1120. // Extended Profile is not supported by any known h264 encoders, force Main Profile.
  1121. if (profile.Contains("extended", StringComparison.OrdinalIgnoreCase))
  1122. {
  1123. profile = "main";
  1124. }
  1125. // Only libx264 support encoding H264 High 10 Profile, otherwise force High Profile.
  1126. if (!string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  1127. && profile.Contains("high10", StringComparison.OrdinalIgnoreCase))
  1128. {
  1129. profile = "high";
  1130. }
  1131. // h264_vaapi does not support Baseline profile, force Constrained Baseline in this case,
  1132. // which is compatible (and ugly).
  1133. if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1134. && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
  1135. {
  1136. profile = "constrained_baseline";
  1137. }
  1138. // libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case.
  1139. if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  1140. || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1141. || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  1142. && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
  1143. {
  1144. profile = "baseline";
  1145. }
  1146. // libx264, h264_qsv, h264_nvenc and h264_vaapi does not support Constrained High profile, force High in this case.
  1147. if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  1148. || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1149. || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  1150. || string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1151. && profile.Contains("high", StringComparison.OrdinalIgnoreCase))
  1152. {
  1153. profile = "high";
  1154. }
  1155. if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1156. && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
  1157. {
  1158. profile = "constrained_baseline";
  1159. }
  1160. if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1161. && profile.Contains("constrainedhigh", StringComparison.OrdinalIgnoreCase))
  1162. {
  1163. profile = "constrained_high";
  1164. }
  1165. // Currently hevc_amf only support encoding HEVC Main Profile, otherwise force Main Profile.
  1166. if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)
  1167. && profile.Contains("main10", StringComparison.OrdinalIgnoreCase))
  1168. {
  1169. profile = "main";
  1170. }
  1171. if (!string.IsNullOrEmpty(profile))
  1172. {
  1173. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  1174. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  1175. {
  1176. // not supported by h264_omx
  1177. param += " -profile:v:0 " + profile;
  1178. }
  1179. }
  1180. var level = state.GetRequestedLevel(targetVideoCodec);
  1181. if (!string.IsNullOrEmpty(level))
  1182. {
  1183. level = NormalizeTranscodingLevel(state, level);
  1184. // libx264, QSV, AMF, VAAPI can adjust the given level to match the output.
  1185. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1186. || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  1187. {
  1188. param += " -level " + level;
  1189. }
  1190. else if (string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
  1191. {
  1192. // hevc_qsv use -level 51 instead of -level 153.
  1193. if (double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out double hevcLevel))
  1194. {
  1195. param += " -level " + (hevcLevel / 3);
  1196. }
  1197. }
  1198. else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1199. || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  1200. {
  1201. param += " -level " + level;
  1202. }
  1203. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  1204. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
  1205. {
  1206. // level option may cause NVENC to fail.
  1207. // NVENC cannot adjust the given level, just throw an error.
  1208. }
  1209. else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  1210. || !string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  1211. {
  1212. param += " -level " + level;
  1213. }
  1214. }
  1215. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  1216. {
  1217. param += " -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none";
  1218. }
  1219. if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  1220. {
  1221. // libx265 only accept level option in -x265-params.
  1222. // level option may cause libx265 to fail.
  1223. // libx265 cannot adjust the given level, just throw an error.
  1224. // TODO: set fine tuned params.
  1225. param += " -x265-params:0 no-info=1";
  1226. }
  1227. return param;
  1228. }
  1229. public bool CanStreamCopyVideo(EncodingJobInfo state, MediaStream videoStream)
  1230. {
  1231. var request = state.BaseRequest;
  1232. if (!request.AllowVideoStreamCopy)
  1233. {
  1234. return false;
  1235. }
  1236. if (videoStream.IsInterlaced
  1237. && state.DeInterlace(videoStream.Codec, false))
  1238. {
  1239. return false;
  1240. }
  1241. if (videoStream.IsAnamorphic ?? false)
  1242. {
  1243. if (request.RequireNonAnamorphic)
  1244. {
  1245. return false;
  1246. }
  1247. }
  1248. // Can't stream copy if we're burning in subtitles
  1249. if (request.SubtitleStreamIndex.HasValue
  1250. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  1251. {
  1252. return false;
  1253. }
  1254. if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
  1255. && videoStream.IsAVC.HasValue
  1256. && !videoStream.IsAVC.Value
  1257. && request.RequireAvc)
  1258. {
  1259. return false;
  1260. }
  1261. // Source and target codecs must match
  1262. if (string.IsNullOrEmpty(videoStream.Codec)
  1263. || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
  1264. {
  1265. return false;
  1266. }
  1267. var requestedProfiles = state.GetRequestedProfiles(videoStream.Codec);
  1268. // If client is requesting a specific video profile, it must match the source
  1269. if (requestedProfiles.Length > 0)
  1270. {
  1271. if (string.IsNullOrEmpty(videoStream.Profile))
  1272. {
  1273. // return false;
  1274. }
  1275. var requestedProfile = requestedProfiles[0];
  1276. // strip spaces because they may be stripped out on the query string as well
  1277. if (!string.IsNullOrEmpty(videoStream.Profile)
  1278. && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", string.Empty, StringComparison.Ordinal), StringComparer.OrdinalIgnoreCase))
  1279. {
  1280. var currentScore = GetVideoProfileScore(videoStream.Profile);
  1281. var requestedScore = GetVideoProfileScore(requestedProfile);
  1282. if (currentScore == -1 || currentScore > requestedScore)
  1283. {
  1284. return false;
  1285. }
  1286. }
  1287. }
  1288. // Video width must fall within requested value
  1289. if (request.MaxWidth.HasValue
  1290. && (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value))
  1291. {
  1292. return false;
  1293. }
  1294. // Video height must fall within requested value
  1295. if (request.MaxHeight.HasValue
  1296. && (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value))
  1297. {
  1298. return false;
  1299. }
  1300. // Video framerate must fall within requested value
  1301. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  1302. if (requestedFramerate.HasValue)
  1303. {
  1304. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  1305. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  1306. {
  1307. return false;
  1308. }
  1309. }
  1310. // Video bitrate must fall within requested value
  1311. if (request.VideoBitRate.HasValue
  1312. && (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value))
  1313. {
  1314. return false;
  1315. }
  1316. var maxBitDepth = state.GetRequestedVideoBitDepth(videoStream.Codec);
  1317. if (maxBitDepth.HasValue)
  1318. {
  1319. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > maxBitDepth.Value)
  1320. {
  1321. return false;
  1322. }
  1323. }
  1324. var maxRefFrames = state.GetRequestedMaxRefFrames(videoStream.Codec);
  1325. if (maxRefFrames.HasValue
  1326. && videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > maxRefFrames.Value)
  1327. {
  1328. return false;
  1329. }
  1330. // If a specific level was requested, the source must match or be less than
  1331. var level = state.GetRequestedLevel(videoStream.Codec);
  1332. if (!string.IsNullOrEmpty(level)
  1333. && double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out var requestLevel))
  1334. {
  1335. if (!videoStream.Level.HasValue)
  1336. {
  1337. // return false;
  1338. }
  1339. if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
  1340. {
  1341. return false;
  1342. }
  1343. }
  1344. if (string.Equals(state.InputContainer, "avi", StringComparison.OrdinalIgnoreCase)
  1345. && string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase)
  1346. && !(videoStream.IsAVC ?? false))
  1347. {
  1348. // see Coach S01E01 - Kelly and the Professor(0).avi
  1349. return false;
  1350. }
  1351. return request.EnableAutoStreamCopy;
  1352. }
  1353. public bool CanStreamCopyAudio(EncodingJobInfo state, MediaStream audioStream, IEnumerable<string> supportedAudioCodecs)
  1354. {
  1355. var request = state.BaseRequest;
  1356. if (!request.AllowAudioStreamCopy)
  1357. {
  1358. return false;
  1359. }
  1360. var maxBitDepth = state.GetRequestedAudioBitDepth(audioStream.Codec);
  1361. if (maxBitDepth.HasValue
  1362. && audioStream.BitDepth.HasValue
  1363. && audioStream.BitDepth.Value > maxBitDepth.Value)
  1364. {
  1365. return false;
  1366. }
  1367. // Source and target codecs must match
  1368. if (string.IsNullOrEmpty(audioStream.Codec)
  1369. || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  1370. {
  1371. return false;
  1372. }
  1373. // Channels must fall within requested value
  1374. var channels = state.GetRequestedAudioChannels(audioStream.Codec);
  1375. if (channels.HasValue)
  1376. {
  1377. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  1378. {
  1379. return false;
  1380. }
  1381. if (audioStream.Channels.Value > channels.Value)
  1382. {
  1383. return false;
  1384. }
  1385. }
  1386. // Sample rate must fall within requested value
  1387. if (request.AudioSampleRate.HasValue)
  1388. {
  1389. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  1390. {
  1391. return false;
  1392. }
  1393. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  1394. {
  1395. return false;
  1396. }
  1397. }
  1398. // Video bitrate must fall within requested value
  1399. if (request.AudioBitRate.HasValue)
  1400. {
  1401. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  1402. {
  1403. return false;
  1404. }
  1405. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  1406. {
  1407. return false;
  1408. }
  1409. }
  1410. return request.EnableAutoStreamCopy;
  1411. }
  1412. public int? GetVideoBitrateParamValue(BaseEncodingJobOptions request, MediaStream videoStream, string outputVideoCodec)
  1413. {
  1414. var bitrate = request.VideoBitRate;
  1415. if (videoStream != null)
  1416. {
  1417. var isUpscaling = request.Height.HasValue
  1418. && videoStream.Height.HasValue
  1419. && request.Height.Value > videoStream.Height.Value
  1420. && request.Width.HasValue
  1421. && videoStream.Width.HasValue
  1422. && request.Width.Value > videoStream.Width.Value;
  1423. // Don't allow bitrate increases unless upscaling
  1424. if (!isUpscaling && bitrate.HasValue && videoStream.BitRate.HasValue)
  1425. {
  1426. bitrate = GetMinBitrate(videoStream.BitRate.Value, bitrate.Value);
  1427. }
  1428. if (bitrate.HasValue)
  1429. {
  1430. var inputVideoCodec = videoStream.Codec;
  1431. bitrate = ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec);
  1432. // If a max bitrate was requested, don't let the scaled bitrate exceed it
  1433. if (request.VideoBitRate.HasValue)
  1434. {
  1435. bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value);
  1436. }
  1437. }
  1438. }
  1439. return bitrate;
  1440. }
  1441. private int GetMinBitrate(int sourceBitrate, int requestedBitrate)
  1442. {
  1443. // these values were chosen from testing to improve low bitrate streams
  1444. if (sourceBitrate <= 2000000)
  1445. {
  1446. sourceBitrate = Convert.ToInt32(sourceBitrate * 2.5);
  1447. }
  1448. else if (sourceBitrate <= 3000000)
  1449. {
  1450. sourceBitrate *= 2;
  1451. }
  1452. var bitrate = Math.Min(sourceBitrate, requestedBitrate);
  1453. return bitrate;
  1454. }
  1455. private static double GetVideoBitrateScaleFactor(string codec)
  1456. {
  1457. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  1458. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  1459. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  1460. {
  1461. return .6;
  1462. }
  1463. return 1;
  1464. }
  1465. private static int ScaleBitrate(int bitrate, string inputVideoCodec, string outputVideoCodec)
  1466. {
  1467. var inputScaleFactor = GetVideoBitrateScaleFactor(inputVideoCodec);
  1468. var outputScaleFactor = GetVideoBitrateScaleFactor(outputVideoCodec);
  1469. var scaleFactor = outputScaleFactor / inputScaleFactor;
  1470. if (bitrate <= 500000)
  1471. {
  1472. scaleFactor = Math.Max(scaleFactor, 4);
  1473. }
  1474. else if (bitrate <= 1000000)
  1475. {
  1476. scaleFactor = Math.Max(scaleFactor, 3);
  1477. }
  1478. else if (bitrate <= 2000000)
  1479. {
  1480. scaleFactor = Math.Max(scaleFactor, 2.5);
  1481. }
  1482. else if (bitrate <= 3000000)
  1483. {
  1484. scaleFactor = Math.Max(scaleFactor, 2);
  1485. }
  1486. return Convert.ToInt32(scaleFactor * bitrate);
  1487. }
  1488. public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream)
  1489. {
  1490. return GetAudioBitrateParam(request.AudioBitRate, request.AudioCodec, audioStream);
  1491. }
  1492. public int? GetAudioBitrateParam(int? audioBitRate, string audioCodec, MediaStream audioStream)
  1493. {
  1494. if (audioStream == null)
  1495. {
  1496. return null;
  1497. }
  1498. if (audioBitRate.HasValue && string.IsNullOrEmpty(audioCodec))
  1499. {
  1500. return Math.Min(384000, audioBitRate.Value);
  1501. }
  1502. if (audioBitRate.HasValue && !string.IsNullOrEmpty(audioCodec))
  1503. {
  1504. if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)
  1505. || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)
  1506. || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)
  1507. || string.Equals(audioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
  1508. {
  1509. if ((audioStream.Channels ?? 0) >= 6)
  1510. {
  1511. return Math.Min(640000, audioBitRate.Value);
  1512. }
  1513. return Math.Min(384000, audioBitRate.Value);
  1514. }
  1515. if (string.Equals(audioCodec, "flac", StringComparison.OrdinalIgnoreCase)
  1516. || string.Equals(audioCodec, "alac", StringComparison.OrdinalIgnoreCase))
  1517. {
  1518. if ((audioStream.Channels ?? 0) >= 6)
  1519. {
  1520. return Math.Min(3584000, audioBitRate.Value);
  1521. }
  1522. return Math.Min(1536000, audioBitRate.Value);
  1523. }
  1524. }
  1525. // Empty bitrate area is not allow on iOS
  1526. // Default audio bitrate to 128K if it is not being requested
  1527. // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options
  1528. return 128000;
  1529. }
  1530. public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions)
  1531. {
  1532. var channels = state.OutputAudioChannels;
  1533. var filters = new List<string>();
  1534. // Boost volume to 200% when downsampling from 6ch to 2ch
  1535. if (channels.HasValue
  1536. && channels.Value <= 2
  1537. && state.AudioStream != null
  1538. && state.AudioStream.Channels.HasValue
  1539. && state.AudioStream.Channels.Value > 5
  1540. && !encodingOptions.DownMixAudioBoost.Equals(1))
  1541. {
  1542. filters.Add("volume=" + encodingOptions.DownMixAudioBoost.ToString(CultureInfo.InvariantCulture));
  1543. }
  1544. var isCopyingTimestamps = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive;
  1545. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode && !isCopyingTimestamps)
  1546. {
  1547. var seconds = TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds;
  1548. filters.Add(
  1549. string.Format(
  1550. CultureInfo.InvariantCulture,
  1551. "asetpts=PTS-{0}/TB",
  1552. Math.Round(seconds)));
  1553. }
  1554. if (filters.Count > 0)
  1555. {
  1556. return " -af \"" + string.Join(',', filters) + "\"";
  1557. }
  1558. return string.Empty;
  1559. }
  1560. /// <summary>
  1561. /// Gets the number of audio channels to specify on the command line.
  1562. /// </summary>
  1563. /// <param name="state">The state.</param>
  1564. /// <param name="audioStream">The audio stream.</param>
  1565. /// <param name="outputAudioCodec">The output audio codec.</param>
  1566. /// <returns>System.Nullable{System.Int32}.</returns>
  1567. public int? GetNumAudioChannelsParam(EncodingJobInfo state, MediaStream audioStream, string outputAudioCodec)
  1568. {
  1569. if (audioStream == null)
  1570. {
  1571. return null;
  1572. }
  1573. var request = state.BaseRequest;
  1574. var inputChannels = audioStream.Channels;
  1575. if (inputChannels <= 0)
  1576. {
  1577. inputChannels = null;
  1578. }
  1579. var codec = outputAudioCodec ?? string.Empty;
  1580. int? transcoderChannelLimit;
  1581. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  1582. {
  1583. // wmav2 currently only supports two channel output
  1584. transcoderChannelLimit = 2;
  1585. }
  1586. else if (codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  1587. {
  1588. // libmp3lame currently only supports two channel output
  1589. transcoderChannelLimit = 2;
  1590. }
  1591. else if (codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1)
  1592. {
  1593. // aac is able to handle 8ch(7.1 layout)
  1594. transcoderChannelLimit = 8;
  1595. }
  1596. else
  1597. {
  1598. // If we don't have any media info then limit it to 6 to prevent encoding errors due to asking for too many channels
  1599. transcoderChannelLimit = 6;
  1600. }
  1601. var isTranscodingAudio = !IsCopyCodec(codec);
  1602. int? resultChannels = state.GetRequestedAudioChannels(codec);
  1603. if (isTranscodingAudio)
  1604. {
  1605. resultChannels = GetMinValue(request.TranscodingMaxAudioChannels, resultChannels);
  1606. }
  1607. if (inputChannels.HasValue)
  1608. {
  1609. resultChannels = resultChannels.HasValue
  1610. ? Math.Min(resultChannels.Value, inputChannels.Value)
  1611. : inputChannels.Value;
  1612. }
  1613. if (isTranscodingAudio && transcoderChannelLimit.HasValue)
  1614. {
  1615. resultChannels = resultChannels.HasValue
  1616. ? Math.Min(resultChannels.Value, transcoderChannelLimit.Value)
  1617. : transcoderChannelLimit.Value;
  1618. }
  1619. // Avoid transcoding to audio channels other than 1ch, 2ch, 6ch (5.1 layout) and 8ch (7.1 layout).
  1620. // https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices
  1621. if (isTranscodingAudio
  1622. && state.TranscodingType != TranscodingJobType.Progressive
  1623. && resultChannels.HasValue
  1624. && ((resultChannels.Value > 2 && resultChannels.Value < 6) || resultChannels.Value == 7))
  1625. {
  1626. resultChannels = 2;
  1627. }
  1628. return resultChannels;
  1629. }
  1630. private int? GetMinValue(int? val1, int? val2)
  1631. {
  1632. if (!val1.HasValue)
  1633. {
  1634. return val2;
  1635. }
  1636. if (!val2.HasValue)
  1637. {
  1638. return val1;
  1639. }
  1640. return Math.Min(val1.Value, val2.Value);
  1641. }
  1642. /// <summary>
  1643. /// Enforces the resolution limit.
  1644. /// </summary>
  1645. /// <param name="state">The state.</param>
  1646. public void EnforceResolutionLimit(EncodingJobInfo state)
  1647. {
  1648. var videoRequest = state.BaseRequest;
  1649. // Switch the incoming params to be ceilings rather than fixed values
  1650. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1651. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1652. videoRequest.Width = null;
  1653. videoRequest.Height = null;
  1654. }
  1655. /// <summary>
  1656. /// Gets the fast seek command line parameter.
  1657. /// </summary>
  1658. /// <param name="request">The request.</param>
  1659. /// <returns>System.String.</returns>
  1660. /// <value>The fast seek command line parameter.</value>
  1661. public string GetFastSeekCommandLineParameter(BaseEncodingJobOptions request)
  1662. {
  1663. var time = request.StartTimeTicks ?? 0;
  1664. if (time > 0)
  1665. {
  1666. return string.Format(CultureInfo.InvariantCulture, "-ss {0}", _mediaEncoder.GetTimeParameter(time));
  1667. }
  1668. return string.Empty;
  1669. }
  1670. /// <summary>
  1671. /// Gets the map args.
  1672. /// </summary>
  1673. /// <param name="state">The state.</param>
  1674. /// <returns>System.String.</returns>
  1675. public string GetMapArgs(EncodingJobInfo state)
  1676. {
  1677. // If we don't have known media info
  1678. // If input is video, use -sn to drop subtitles
  1679. // Otherwise just return empty
  1680. if (state.VideoStream == null && state.AudioStream == null)
  1681. {
  1682. return state.IsInputVideo ? "-sn" : string.Empty;
  1683. }
  1684. // We have media info, but we don't know the stream indexes
  1685. if (state.VideoStream != null && state.VideoStream.Index == -1)
  1686. {
  1687. return "-sn";
  1688. }
  1689. // We have media info, but we don't know the stream indexes
  1690. if (state.AudioStream != null && state.AudioStream.Index == -1)
  1691. {
  1692. return state.IsInputVideo ? "-sn" : string.Empty;
  1693. }
  1694. var args = string.Empty;
  1695. if (state.VideoStream != null)
  1696. {
  1697. args += string.Format(
  1698. CultureInfo.InvariantCulture,
  1699. "-map 0:{0}",
  1700. state.VideoStream.Index);
  1701. }
  1702. else
  1703. {
  1704. // No known video stream
  1705. args += "-vn";
  1706. }
  1707. if (state.AudioStream != null)
  1708. {
  1709. args += string.Format(
  1710. CultureInfo.InvariantCulture,
  1711. " -map 0:{0}",
  1712. state.AudioStream.Index);
  1713. }
  1714. else
  1715. {
  1716. args += " -map -0:a";
  1717. }
  1718. var subtitleMethod = state.SubtitleDeliveryMethod;
  1719. if (state.SubtitleStream == null || subtitleMethod == SubtitleDeliveryMethod.Hls)
  1720. {
  1721. args += " -map -0:s";
  1722. }
  1723. else if (subtitleMethod == SubtitleDeliveryMethod.Embed)
  1724. {
  1725. args += string.Format(
  1726. CultureInfo.InvariantCulture,
  1727. " -map 0:{0}",
  1728. state.SubtitleStream.Index);
  1729. }
  1730. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  1731. {
  1732. args += " -map 1:0 -sn";
  1733. }
  1734. return args;
  1735. }
  1736. /// <summary>
  1737. /// Determines which stream will be used for playback.
  1738. /// </summary>
  1739. /// <param name="allStream">All stream.</param>
  1740. /// <param name="desiredIndex">Index of the desired.</param>
  1741. /// <param name="type">The type.</param>
  1742. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  1743. /// <returns>MediaStream.</returns>
  1744. public MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  1745. {
  1746. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  1747. if (desiredIndex.HasValue)
  1748. {
  1749. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  1750. if (stream != null)
  1751. {
  1752. return stream;
  1753. }
  1754. }
  1755. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  1756. {
  1757. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  1758. streams.FirstOrDefault();
  1759. }
  1760. // Just return the first one
  1761. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  1762. }
  1763. /// <summary>
  1764. /// Gets the graphical subtitle parameter.
  1765. /// </summary>
  1766. /// <param name="state">Encoding state.</param>
  1767. /// <param name="options">Encoding options.</param>
  1768. /// <param name="outputVideoCodec">Video codec to use.</param>
  1769. /// <returns>Graphical subtitle parameter.</returns>
  1770. public string GetGraphicalSubtitleParam(
  1771. EncodingJobInfo state,
  1772. EncodingOptions options,
  1773. string outputVideoCodec)
  1774. {
  1775. outputVideoCodec ??= string.Empty;
  1776. var outputSizeParam = ReadOnlySpan<char>.Empty;
  1777. var request = state.BaseRequest;
  1778. outputSizeParam = GetOutputSizeParamInternal(state, options, outputVideoCodec);
  1779. var videoSizeParam = string.Empty;
  1780. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
  1781. var isLinux = OperatingSystem.IsLinux();
  1782. var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  1783. var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  1784. var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  1785. var isQsvH264Encoder = outputVideoCodec.Contains("h264_qsv", StringComparison.OrdinalIgnoreCase);
  1786. var isQsvHevcEncoder = outputVideoCodec.Contains("hevc_qsv", StringComparison.OrdinalIgnoreCase);
  1787. var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  1788. var isNvencEncoder = outputVideoCodec.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
  1789. var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder);
  1790. var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder);
  1791. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  1792. var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
  1793. var mediaEncoderVersion = _mediaEncoder.GetMediaEncoderVersion();
  1794. var isCudaOverlaySupported = _mediaEncoder.SupportsFilter("overlay_cuda") && mediaEncoderVersion != null && mediaEncoderVersion >= _minVersionForCudaOverlay;
  1795. var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat);
  1796. // Tonemapping and burn-in graphical subtitles requires overlay_vaapi.
  1797. // But it's still in ffmpeg mailing list. Disable it for now.
  1798. if (isTonemappingSupportedOnVaapi && isOpenclTonemappingSupported && !isVppTonemappingSupported)
  1799. {
  1800. return GetOutputSizeParam(state, options, outputVideoCodec);
  1801. }
  1802. // Setup subtitle scaling
  1803. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  1804. {
  1805. // Adjust the size of graphical subtitles to fit the video stream.
  1806. var videoStream = state.VideoStream;
  1807. var inputWidth = videoStream.Width;
  1808. var inputHeight = videoStream.Height;
  1809. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  1810. if (width.HasValue && height.HasValue)
  1811. {
  1812. videoSizeParam = string.Format(
  1813. CultureInfo.InvariantCulture,
  1814. "scale={0}x{1}",
  1815. width.Value,
  1816. height.Value);
  1817. }
  1818. if (!string.IsNullOrEmpty(videoSizeParam)
  1819. && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  1820. {
  1821. // upload graphical subtitle to QSV
  1822. if (isLinux && (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1823. || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)))
  1824. {
  1825. videoSizeParam += ",hwupload=extra_hw_frames=64";
  1826. }
  1827. }
  1828. if (!string.IsNullOrEmpty(videoSizeParam))
  1829. {
  1830. // upload graphical subtitle to cuda
  1831. if (isNvdecDecoder && isNvencEncoder && isCudaOverlaySupported && isCudaFormatConversionSupported)
  1832. {
  1833. videoSizeParam += ",hwupload_cuda";
  1834. }
  1835. }
  1836. }
  1837. var mapPrefix = state.SubtitleStream.IsExternal ?
  1838. 1 :
  1839. 0;
  1840. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  1841. ? 0
  1842. : state.SubtitleStream.Index;
  1843. // Setup default filtergraph utilizing FFMpeg overlay() and FFMpeg scale() (see the return of this function for index reference)
  1844. // Always put the scaler before the overlay for better performance
  1845. var retStr = outputSizeParam.IsEmpty
  1846. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay\""
  1847. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"";
  1848. // When the input may or may not be hardware VAAPI decodable
  1849. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1850. || string.Equals(outputVideoCodec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
  1851. {
  1852. /*
  1853. [base]: HW scaling video to OutputSize
  1854. [sub]: SW scaling subtitle to FixedOutputSize
  1855. [base][sub]: SW overlay
  1856. */
  1857. retStr = outputSizeParam.IsEmpty
  1858. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]hwdownload[base];[base][sub]overlay,format=nv12,hwupload\""
  1859. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload[base];[base][sub]overlay,format=nv12,hwupload\"";
  1860. }
  1861. // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first
  1862. else if (_mediaEncoder.SupportsHwaccel("vaapi") && videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1
  1863. && (string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase)
  1864. || string.Equals(outputVideoCodec, "libx265", StringComparison.OrdinalIgnoreCase)))
  1865. {
  1866. /*
  1867. [base]: SW scaling video to OutputSize
  1868. [sub]: SW scaling subtitle to FixedOutputSize
  1869. [base][sub]: SW overlay
  1870. */
  1871. retStr = outputSizeParam.IsEmpty
  1872. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay\""
  1873. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"";
  1874. }
  1875. else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1876. || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
  1877. {
  1878. /*
  1879. QSV in FFMpeg can now setup hardware overlay for transcodes.
  1880. For software decoding and hardware encoding option, frames must be hwuploaded into hardware
  1881. with fixed frame size.
  1882. Currently only supports linux.
  1883. */
  1884. if (isTonemappingSupportedOnQsv && isVppTonemappingSupported)
  1885. {
  1886. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload,format=nv12[base];[base][sub]overlay\"";
  1887. }
  1888. else if (isLinux)
  1889. {
  1890. retStr = outputSizeParam.IsEmpty
  1891. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay_qsv\""
  1892. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay_qsv\"";
  1893. }
  1894. }
  1895. else if (isNvdecDecoder && isNvencEncoder)
  1896. {
  1897. if (isCudaOverlaySupported && isCudaFormatConversionSupported)
  1898. {
  1899. retStr = outputSizeParam.IsEmpty
  1900. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]scale_cuda=format=yuv420p[base];[base][sub]overlay_cuda\""
  1901. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay_cuda\"";
  1902. }
  1903. else
  1904. {
  1905. retStr = outputSizeParam.IsEmpty
  1906. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay,format=nv12|yuv420p,hwupload_cuda\""
  1907. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay,format=nv12|yuv420p,hwupload_cuda\"";
  1908. }
  1909. }
  1910. return string.Format(
  1911. CultureInfo.InvariantCulture,
  1912. retStr,
  1913. mapPrefix,
  1914. subtitleStreamIndex,
  1915. state.VideoStream.Index,
  1916. outputSizeParam.ToString(),
  1917. videoSizeParam);
  1918. }
  1919. public static (int? width, int? height) GetFixedOutputSize(
  1920. int? videoWidth,
  1921. int? videoHeight,
  1922. int? requestedWidth,
  1923. int? requestedHeight,
  1924. int? requestedMaxWidth,
  1925. int? requestedMaxHeight)
  1926. {
  1927. if (!videoWidth.HasValue && !requestedWidth.HasValue)
  1928. {
  1929. return (null, null);
  1930. }
  1931. if (!videoHeight.HasValue && !requestedHeight.HasValue)
  1932. {
  1933. return (null, null);
  1934. }
  1935. decimal inputWidth = Convert.ToDecimal(videoWidth ?? requestedWidth, CultureInfo.InvariantCulture);
  1936. decimal inputHeight = Convert.ToDecimal(videoHeight ?? requestedHeight, CultureInfo.InvariantCulture);
  1937. decimal outputWidth = requestedWidth.HasValue ? Convert.ToDecimal(requestedWidth.Value) : inputWidth;
  1938. decimal outputHeight = requestedHeight.HasValue ? Convert.ToDecimal(requestedHeight.Value) : inputHeight;
  1939. decimal maximumWidth = requestedMaxWidth.HasValue ? Convert.ToDecimal(requestedMaxWidth.Value) : outputWidth;
  1940. decimal maximumHeight = requestedMaxHeight.HasValue ? Convert.ToDecimal(requestedMaxHeight.Value) : outputHeight;
  1941. if (outputWidth > maximumWidth || outputHeight > maximumHeight)
  1942. {
  1943. var scale = Math.Min(maximumWidth / outputWidth, maximumHeight / outputHeight);
  1944. outputWidth = Math.Min(maximumWidth, Math.Truncate(outputWidth * scale));
  1945. outputHeight = Math.Min(maximumHeight, Math.Truncate(outputHeight * scale));
  1946. }
  1947. outputWidth = 2 * Math.Truncate(outputWidth / 2);
  1948. outputHeight = 2 * Math.Truncate(outputHeight / 2);
  1949. return (Convert.ToInt32(outputWidth), Convert.ToInt32(outputHeight));
  1950. }
  1951. public List<string> GetScalingFilters(
  1952. EncodingJobInfo state,
  1953. EncodingOptions options,
  1954. int? videoWidth,
  1955. int? videoHeight,
  1956. Video3DFormat? threedFormat,
  1957. string videoDecoder,
  1958. string videoEncoder,
  1959. int? requestedWidth,
  1960. int? requestedHeight,
  1961. int? requestedMaxWidth,
  1962. int? requestedMaxHeight)
  1963. {
  1964. var filters = new List<string>();
  1965. var (width, height) = GetFixedOutputSize(
  1966. videoWidth,
  1967. videoHeight,
  1968. requestedWidth,
  1969. requestedHeight,
  1970. requestedMaxWidth,
  1971. requestedMaxHeight);
  1972. if ((string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1973. || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1974. || string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)
  1975. || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
  1976. && width.HasValue
  1977. && height.HasValue)
  1978. {
  1979. // Given the input dimensions (inputWidth, inputHeight), determine the output dimensions
  1980. // (outputWidth, outputHeight). The user may request precise output dimensions or maximum
  1981. // output dimensions. Output dimensions are guaranteed to be even.
  1982. var outputWidth = width.Value;
  1983. var outputHeight = height.Value;
  1984. var qsv_or_vaapi = string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1985. || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase);
  1986. var isDeintEnabled = state.DeInterlace("h264", true)
  1987. || state.DeInterlace("avc", true)
  1988. || state.DeInterlace("h265", true)
  1989. || state.DeInterlace("hevc", true);
  1990. var isVaapiDecoder = videoDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  1991. var isVaapiH264Encoder = videoEncoder.Contains("h264_vaapi", StringComparison.OrdinalIgnoreCase);
  1992. var isVaapiHevcEncoder = videoEncoder.Contains("hevc_vaapi", StringComparison.OrdinalIgnoreCase);
  1993. var isQsvH264Encoder = videoEncoder.Contains("h264_qsv", StringComparison.OrdinalIgnoreCase);
  1994. var isQsvHevcEncoder = videoEncoder.Contains("hevc_qsv", StringComparison.OrdinalIgnoreCase);
  1995. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  1996. var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
  1997. var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder);
  1998. var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder);
  1999. var isP010PixFmtRequired = (isTonemappingSupportedOnVaapi && (isOpenclTonemappingSupported || isVppTonemappingSupported))
  2000. || (isTonemappingSupportedOnQsv && isVppTonemappingSupported);
  2001. var outputPixFmt = "format=nv12";
  2002. if (isP010PixFmtRequired)
  2003. {
  2004. outputPixFmt = "format=p010";
  2005. }
  2006. if (isTonemappingSupportedOnQsv && isVppTonemappingSupported)
  2007. {
  2008. qsv_or_vaapi = false;
  2009. }
  2010. if (!videoWidth.HasValue
  2011. || outputWidth != videoWidth.Value
  2012. || !videoHeight.HasValue
  2013. || outputHeight != videoHeight.Value)
  2014. {
  2015. // Force nv12 pixel format to enable 10-bit to 8-bit colour conversion.
  2016. // use vpp_qsv filter to avoid green bar when the fixed output size is requested.
  2017. filters.Add(
  2018. string.Format(
  2019. CultureInfo.InvariantCulture,
  2020. "{0}=w={1}:h={2}{3}{4}",
  2021. qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi",
  2022. outputWidth,
  2023. outputHeight,
  2024. ":" + outputPixFmt,
  2025. (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty));
  2026. }
  2027. // Assert 10-bit is P010 so as we can avoid the extra scaler to get a bit more fps on high res HDR videos.
  2028. else if (!isP010PixFmtRequired)
  2029. {
  2030. filters.Add(
  2031. string.Format(
  2032. CultureInfo.InvariantCulture,
  2033. "{0}={1}{2}",
  2034. qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi",
  2035. outputPixFmt,
  2036. (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty));
  2037. }
  2038. }
  2039. else if ((videoDecoder ?? string.Empty).Contains("cuda", StringComparison.OrdinalIgnoreCase)
  2040. && width.HasValue
  2041. && height.HasValue)
  2042. {
  2043. var outputWidth = width.Value;
  2044. var outputHeight = height.Value;
  2045. var isNvencEncoder = videoEncoder.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
  2046. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  2047. var isCudaTonemappingSupported = IsCudaTonemappingSupported(state, options);
  2048. var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase);
  2049. var mediaEncoderVersion = _mediaEncoder.GetMediaEncoderVersion();
  2050. var isCudaOverlaySupported = _mediaEncoder.SupportsFilter("overlay_cuda") && mediaEncoderVersion != null && mediaEncoderVersion >= _minVersionForCudaOverlay;
  2051. var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat);
  2052. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2053. var outputPixFmt = string.Empty;
  2054. if (isCudaFormatConversionSupported)
  2055. {
  2056. outputPixFmt = (hasGraphicalSubs && isCudaOverlaySupported && isNvencEncoder)
  2057. ? "format=yuv420p"
  2058. : "format=nv12";
  2059. if ((isOpenclTonemappingSupported || isCudaTonemappingSupported)
  2060. && isTonemappingSupportedOnNvenc)
  2061. {
  2062. outputPixFmt = "format=p010";
  2063. }
  2064. }
  2065. if (!videoWidth.HasValue
  2066. || outputWidth != videoWidth.Value
  2067. || !videoHeight.HasValue
  2068. || outputHeight != videoHeight.Value)
  2069. {
  2070. filters.Add(
  2071. string.Format(
  2072. CultureInfo.InvariantCulture,
  2073. "scale_cuda=w={0}:h={1}{2}",
  2074. outputWidth,
  2075. outputHeight,
  2076. isCudaFormatConversionSupported ? (":" + outputPixFmt) : string.Empty));
  2077. }
  2078. else if (isCudaFormatConversionSupported)
  2079. {
  2080. filters.Add(
  2081. string.Format(
  2082. CultureInfo.InvariantCulture,
  2083. "scale_cuda={0}",
  2084. outputPixFmt));
  2085. }
  2086. }
  2087. else if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1
  2088. && width.HasValue
  2089. && height.HasValue)
  2090. {
  2091. // Nothing to do, it's handled as an input resize filter
  2092. }
  2093. else
  2094. {
  2095. var isExynosV4L2 = string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase);
  2096. // If fixed dimensions were supplied
  2097. if (requestedWidth.HasValue && requestedHeight.HasValue)
  2098. {
  2099. if (isExynosV4L2)
  2100. {
  2101. var widthParam = requestedWidth.Value.ToString(CultureInfo.InvariantCulture);
  2102. var heightParam = requestedHeight.Value.ToString(CultureInfo.InvariantCulture);
  2103. filters.Add(
  2104. string.Format(
  2105. CultureInfo.InvariantCulture,
  2106. "scale=trunc({0}/64)*64:trunc({1}/2)*2",
  2107. widthParam,
  2108. heightParam));
  2109. }
  2110. else
  2111. {
  2112. filters.Add(GetFixedSizeScalingFilter(threedFormat, requestedWidth.Value, requestedHeight.Value));
  2113. }
  2114. }
  2115. // 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
  2116. else if (requestedMaxWidth.HasValue && requestedMaxHeight.HasValue)
  2117. {
  2118. var maxWidthParam = requestedMaxWidth.Value.ToString(CultureInfo.InvariantCulture);
  2119. var maxHeightParam = requestedMaxHeight.Value.ToString(CultureInfo.InvariantCulture);
  2120. if (isExynosV4L2)
  2121. {
  2122. filters.Add(
  2123. string.Format(
  2124. CultureInfo.InvariantCulture,
  2125. "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",
  2126. maxWidthParam,
  2127. maxHeightParam));
  2128. }
  2129. else
  2130. {
  2131. filters.Add(
  2132. string.Format(
  2133. CultureInfo.InvariantCulture,
  2134. "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",
  2135. maxWidthParam,
  2136. maxHeightParam));
  2137. }
  2138. }
  2139. // If a fixed width was requested
  2140. else if (requestedWidth.HasValue)
  2141. {
  2142. if (threedFormat.HasValue)
  2143. {
  2144. // This method can handle 0 being passed in for the requested height
  2145. filters.Add(GetFixedSizeScalingFilter(threedFormat, requestedWidth.Value, 0));
  2146. }
  2147. else
  2148. {
  2149. var widthParam = requestedWidth.Value.ToString(CultureInfo.InvariantCulture);
  2150. filters.Add(
  2151. string.Format(
  2152. CultureInfo.InvariantCulture,
  2153. "scale={0}:trunc(ow/a/2)*2",
  2154. widthParam));
  2155. }
  2156. }
  2157. // If a fixed height was requested
  2158. else if (requestedHeight.HasValue)
  2159. {
  2160. var heightParam = requestedHeight.Value.ToString(CultureInfo.InvariantCulture);
  2161. if (isExynosV4L2)
  2162. {
  2163. filters.Add(
  2164. string.Format(
  2165. CultureInfo.InvariantCulture,
  2166. "scale=trunc(oh*a/64)*64:{0}",
  2167. heightParam));
  2168. }
  2169. else
  2170. {
  2171. filters.Add(
  2172. string.Format(
  2173. CultureInfo.InvariantCulture,
  2174. "scale=trunc(oh*a/2)*2:{0}",
  2175. heightParam));
  2176. }
  2177. }
  2178. // If a max width was requested
  2179. else if (requestedMaxWidth.HasValue)
  2180. {
  2181. var maxWidthParam = requestedMaxWidth.Value.ToString(CultureInfo.InvariantCulture);
  2182. if (isExynosV4L2)
  2183. {
  2184. filters.Add(
  2185. string.Format(
  2186. CultureInfo.InvariantCulture,
  2187. "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/64)*64:trunc(ow/dar/2)*2",
  2188. maxWidthParam));
  2189. }
  2190. else
  2191. {
  2192. filters.Add(
  2193. string.Format(
  2194. CultureInfo.InvariantCulture,
  2195. "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2",
  2196. maxWidthParam));
  2197. }
  2198. }
  2199. // If a max height was requested
  2200. else if (requestedMaxHeight.HasValue)
  2201. {
  2202. var maxHeightParam = requestedMaxHeight.Value.ToString(CultureInfo.InvariantCulture);
  2203. if (isExynosV4L2)
  2204. {
  2205. filters.Add(
  2206. string.Format(
  2207. CultureInfo.InvariantCulture,
  2208. "scale=trunc(oh*a/64)*64:min(max(iw/dar\\,ih)\\,{0})",
  2209. maxHeightParam));
  2210. }
  2211. else
  2212. {
  2213. filters.Add(
  2214. string.Format(
  2215. CultureInfo.InvariantCulture,
  2216. "scale=trunc(oh*a/2)*2:min(max(iw/dar\\,ih)\\,{0})",
  2217. maxHeightParam));
  2218. }
  2219. }
  2220. }
  2221. return filters;
  2222. }
  2223. private string GetFixedSizeScalingFilter(Video3DFormat? threedFormat, int requestedWidth, int requestedHeight)
  2224. {
  2225. var widthParam = requestedWidth.ToString(CultureInfo.InvariantCulture);
  2226. var heightParam = requestedHeight.ToString(CultureInfo.InvariantCulture);
  2227. string filter = null;
  2228. if (threedFormat.HasValue)
  2229. {
  2230. switch (threedFormat.Value)
  2231. {
  2232. case Video3DFormat.HalfSideBySide:
  2233. 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";
  2234. // 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.
  2235. break;
  2236. case Video3DFormat.FullSideBySide:
  2237. 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";
  2238. // fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to requestedWidth.
  2239. break;
  2240. case Video3DFormat.HalfTopAndBottom:
  2241. 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";
  2242. // 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
  2243. break;
  2244. case Video3DFormat.FullTopAndBottom:
  2245. 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";
  2246. // ftab crop height in half, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
  2247. break;
  2248. default:
  2249. break;
  2250. }
  2251. }
  2252. // default
  2253. if (filter == null)
  2254. {
  2255. if (requestedHeight > 0)
  2256. {
  2257. filter = "scale=trunc({0}/2)*2:trunc({1}/2)*2";
  2258. }
  2259. else
  2260. {
  2261. filter = "scale={0}:trunc({0}/dar/2)*2";
  2262. }
  2263. }
  2264. return string.Format(CultureInfo.InvariantCulture, filter, widthParam, heightParam);
  2265. }
  2266. /// <summary>
  2267. /// Gets the output size parameter.
  2268. /// </summary>
  2269. /// <param name="state">Encoding state.</param>
  2270. /// <param name="options">Encoding options.</param>
  2271. /// <param name="outputVideoCodec">Video codec to use.</param>
  2272. /// <returns>The output size parameter.</returns>
  2273. public string GetOutputSizeParam(
  2274. EncodingJobInfo state,
  2275. EncodingOptions options,
  2276. string outputVideoCodec)
  2277. {
  2278. string filters = GetOutputSizeParamInternal(state, options, outputVideoCodec);
  2279. return string.IsNullOrEmpty(filters) ? string.Empty : " -vf \"" + filters + "\"";
  2280. }
  2281. /// <summary>
  2282. /// Gets the output size parameter.
  2283. /// If we're going to put a fixed size on the command line, this will calculate it.
  2284. /// </summary>
  2285. /// <param name="state">Encoding state.</param>
  2286. /// <param name="options">Encoding options.</param>
  2287. /// <param name="outputVideoCodec">Video codec to use.</param>
  2288. /// <returns>The output size parameter.</returns>
  2289. public string GetOutputSizeParamInternal(
  2290. EncodingJobInfo state,
  2291. EncodingOptions options,
  2292. string outputVideoCodec)
  2293. {
  2294. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  2295. var request = state.BaseRequest;
  2296. var videoStream = state.VideoStream;
  2297. var filters = new List<string>();
  2298. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
  2299. var inputWidth = videoStream?.Width;
  2300. var inputHeight = videoStream?.Height;
  2301. var threeDFormat = state.MediaSource.Video3DFormat;
  2302. var isSwDecoder = string.IsNullOrEmpty(videoDecoder);
  2303. var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1;
  2304. var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  2305. var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  2306. var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  2307. var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  2308. var isQsvH264Encoder = outputVideoCodec.IndexOf("h264_qsv", StringComparison.OrdinalIgnoreCase) != -1;
  2309. var isQsvHevcEncoder = outputVideoCodec.IndexOf("hevc_qsv", StringComparison.OrdinalIgnoreCase) != -1;
  2310. var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  2311. var isNvencEncoder = outputVideoCodec.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
  2312. var isCuvidH264Decoder = videoDecoder.Contains("h264_cuvid", StringComparison.OrdinalIgnoreCase);
  2313. var isCuvidHevcDecoder = videoDecoder.Contains("hevc_cuvid", StringComparison.OrdinalIgnoreCase);
  2314. var isCuvidVp9Decoder = videoDecoder.Contains("vp9_cuvid", StringComparison.OrdinalIgnoreCase);
  2315. var isLibX264Encoder = outputVideoCodec.IndexOf("libx264", StringComparison.OrdinalIgnoreCase) != -1;
  2316. var isLibX265Encoder = outputVideoCodec.IndexOf("libx265", StringComparison.OrdinalIgnoreCase) != -1;
  2317. var isLinux = OperatingSystem.IsLinux();
  2318. var isColorDepth10 = IsColorDepth10(state);
  2319. var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && (isNvdecDecoder || isCuvidHevcDecoder || isCuvidVp9Decoder || isSwDecoder);
  2320. var isTonemappingSupportedOnAmf = string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && (isD3d11vaDecoder || isSwDecoder);
  2321. var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder);
  2322. var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder);
  2323. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  2324. var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
  2325. var isCudaTonemappingSupported = IsCudaTonemappingSupported(state, options);
  2326. var mediaEncoderVersion = _mediaEncoder.GetMediaEncoderVersion();
  2327. var isCudaOverlaySupported = _mediaEncoder.SupportsFilter("overlay_cuda") && mediaEncoderVersion != null && mediaEncoderVersion >= _minVersionForCudaOverlay;
  2328. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2329. var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2330. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2331. // 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
  2332. var doubleRateDeinterlace = options.DeinterlaceDoubleRate && (videoStream?.AverageFrameRate ?? 60) <= 30;
  2333. var isScalingInAdvance = false;
  2334. var isCudaDeintInAdvance = false;
  2335. var isHwuploadCudaRequired = false;
  2336. var isNoTonemapFilterApplied = true;
  2337. var isDeinterlaceH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
  2338. var isDeinterlaceHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
  2339. // Add OpenCL tonemapping filter for NVENC/AMF/VAAPI.
  2340. if ((isTonemappingSupportedOnNvenc && !isCudaTonemappingSupported) || isTonemappingSupportedOnAmf || (isTonemappingSupportedOnVaapi && !isVppTonemappingSupported))
  2341. {
  2342. // NVIDIA Pascal and Turing or higher are recommended.
  2343. // AMD Polaris and Vega or higher are recommended.
  2344. // Intel Kaby Lake or newer is required.
  2345. if (isOpenclTonemappingSupported)
  2346. {
  2347. isNoTonemapFilterApplied = false;
  2348. var inputHdrParams = GetInputHdrParams(videoStream.ColorTransfer);
  2349. if (!string.IsNullOrEmpty(inputHdrParams))
  2350. {
  2351. filters.Add(inputHdrParams);
  2352. }
  2353. var parameters = "tonemap_opencl=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:desat={1}:threshold={2}:peak={3}";
  2354. if (options.TonemappingParam != 0)
  2355. {
  2356. parameters += ":param={4}";
  2357. }
  2358. if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
  2359. {
  2360. parameters += ":range={5}";
  2361. }
  2362. if (isSwDecoder || isD3d11vaDecoder)
  2363. {
  2364. isScalingInAdvance = true;
  2365. // Add zscale filter before tone mapping filter for performance.
  2366. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  2367. if (width.HasValue && height.HasValue)
  2368. {
  2369. filters.Add(
  2370. string.Format(
  2371. CultureInfo.InvariantCulture,
  2372. "zscale=s={0}x{1}",
  2373. width.Value,
  2374. height.Value));
  2375. }
  2376. // Convert to hardware pixel format p010 when using SW decoder.
  2377. filters.Add("format=p010");
  2378. }
  2379. if ((isDeinterlaceH264 || isDeinterlaceHevc) && isNvdecDecoder)
  2380. {
  2381. isCudaDeintInAdvance = true;
  2382. filters.Add(
  2383. string.Format(
  2384. CultureInfo.InvariantCulture,
  2385. "yadif_cuda={0}:-1:0",
  2386. doubleRateDeinterlace ? "1" : "0"));
  2387. }
  2388. if (isVaapiDecoder || isNvdecDecoder)
  2389. {
  2390. isScalingInAdvance = true;
  2391. filters.AddRange(
  2392. GetScalingFilters(
  2393. state,
  2394. options,
  2395. inputWidth,
  2396. inputHeight,
  2397. threeDFormat,
  2398. videoDecoder,
  2399. outputVideoCodec,
  2400. request.Width,
  2401. request.Height,
  2402. request.MaxWidth,
  2403. request.MaxHeight));
  2404. }
  2405. // hwmap the HDR data to opencl device by cl-va p010 interop.
  2406. if (isVaapiDecoder)
  2407. {
  2408. filters.Add("hwmap");
  2409. }
  2410. // convert cuda device data to p010 host data.
  2411. if (isNvdecDecoder)
  2412. {
  2413. filters.Add("hwdownload,format=p010");
  2414. }
  2415. if (isNvdecDecoder
  2416. || isCuvidHevcDecoder
  2417. || isCuvidVp9Decoder
  2418. || isSwDecoder
  2419. || isD3d11vaDecoder)
  2420. {
  2421. // Upload the HDR10 or HLG data to the OpenCL device,
  2422. // use tonemap_opencl filter for tone mapping,
  2423. // and then download the SDR data to memory.
  2424. filters.Add("hwupload");
  2425. }
  2426. // Fallback to hable if bt2390 is chosen but not supported in tonemap_opencl.
  2427. var isBt2390SupportedInOpenclTonemap = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.TonemapOpenclBt2390);
  2428. if (string.Equals(options.TonemappingAlgorithm, "bt2390", StringComparison.OrdinalIgnoreCase)
  2429. && !isBt2390SupportedInOpenclTonemap)
  2430. {
  2431. options.TonemappingAlgorithm = "hable";
  2432. }
  2433. filters.Add(
  2434. string.Format(
  2435. CultureInfo.InvariantCulture,
  2436. parameters,
  2437. options.TonemappingAlgorithm,
  2438. options.TonemappingDesat,
  2439. options.TonemappingThreshold,
  2440. options.TonemappingPeak,
  2441. options.TonemappingParam,
  2442. options.TonemappingRange));
  2443. if (isNvdecDecoder
  2444. || isCuvidHevcDecoder
  2445. || isCuvidVp9Decoder
  2446. || isSwDecoder
  2447. || isD3d11vaDecoder)
  2448. {
  2449. filters.Add("hwdownload");
  2450. filters.Add("format=nv12");
  2451. }
  2452. if (isNvdecDecoder && isNvencEncoder)
  2453. {
  2454. isHwuploadCudaRequired = true;
  2455. }
  2456. if (isVaapiDecoder)
  2457. {
  2458. // Reverse the data route from opencl to vaapi.
  2459. filters.Add("hwmap=derive_device=vaapi:reverse=1");
  2460. }
  2461. var outputSdrParams = GetOutputSdrParams(options.TonemappingRange);
  2462. if (!string.IsNullOrEmpty(outputSdrParams))
  2463. {
  2464. filters.Add(outputSdrParams);
  2465. }
  2466. }
  2467. }
  2468. // When the input may or may not be hardware VAAPI decodable.
  2469. if ((isVaapiH264Encoder || isVaapiHevcEncoder)
  2470. && !(isTonemappingSupportedOnVaapi && (isOpenclTonemappingSupported || isVppTonemappingSupported)))
  2471. {
  2472. filters.Add("format=nv12|vaapi");
  2473. filters.Add("hwupload");
  2474. }
  2475. // When burning in graphical subtitles using overlay_qsv, upload videostream to the same qsv context.
  2476. else if (isLinux && hasGraphicalSubs && (isQsvH264Encoder || isQsvHevcEncoder)
  2477. && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  2478. {
  2479. filters.Add("hwupload=extra_hw_frames=64");
  2480. }
  2481. // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first.
  2482. else if ((IsVaapiSupported(state) && isVaapiDecoder) && (isLibX264Encoder || isLibX265Encoder)
  2483. && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  2484. {
  2485. var codec = videoStream.Codec;
  2486. // Assert 10-bit hardware VAAPI decodable
  2487. if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  2488. || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  2489. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  2490. {
  2491. /*
  2492. Download data from GPU to CPU as p010le format.
  2493. Colorspace conversion is unnecessary here as libx264 will handle it.
  2494. If this step is missing, it will fail on AMD but not on intel.
  2495. */
  2496. filters.Add("hwdownload");
  2497. filters.Add("format=p010le");
  2498. }
  2499. // Assert 8-bit hardware VAAPI decodable
  2500. else if (!isColorDepth10)
  2501. {
  2502. filters.Add("hwdownload");
  2503. filters.Add("format=nv12");
  2504. }
  2505. }
  2506. // Add hardware deinterlace filter before scaling filter.
  2507. if (isDeinterlaceH264 || isDeinterlaceHevc)
  2508. {
  2509. if (isVaapiEncoder
  2510. || (isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  2511. {
  2512. filters.Add(
  2513. string.Format(
  2514. CultureInfo.InvariantCulture,
  2515. "deinterlace_vaapi=rate={0}",
  2516. doubleRateDeinterlace ? "field" : "frame"));
  2517. }
  2518. else if (isNvdecDecoder && !isCudaDeintInAdvance)
  2519. {
  2520. filters.Add(
  2521. string.Format(
  2522. CultureInfo.InvariantCulture,
  2523. "yadif_cuda={0}:-1:0",
  2524. doubleRateDeinterlace ? "1" : "0"));
  2525. }
  2526. }
  2527. // Add software deinterlace filter before scaling filter.
  2528. if ((isDeinterlaceH264 || isDeinterlaceHevc)
  2529. && !isVaapiH264Encoder
  2530. && !isVaapiHevcEncoder
  2531. && !isQsvH264Encoder
  2532. && !isQsvHevcEncoder
  2533. && !isNvdecDecoder
  2534. && !isCuvidH264Decoder)
  2535. {
  2536. if (string.Equals(options.DeinterlaceMethod, "bwdif", StringComparison.OrdinalIgnoreCase))
  2537. {
  2538. filters.Add(
  2539. string.Format(
  2540. CultureInfo.InvariantCulture,
  2541. "bwdif={0}:-1:0",
  2542. doubleRateDeinterlace ? "1" : "0"));
  2543. }
  2544. else
  2545. {
  2546. filters.Add(
  2547. string.Format(
  2548. CultureInfo.InvariantCulture,
  2549. "yadif={0}:-1:0",
  2550. doubleRateDeinterlace ? "1" : "0"));
  2551. }
  2552. }
  2553. // Add scaling filter: scale_*=format=nv12 or scale_*=w=*:h=*:format=nv12 or scale=expr
  2554. if (!isScalingInAdvance)
  2555. {
  2556. filters.AddRange(
  2557. GetScalingFilters(
  2558. state,
  2559. options,
  2560. inputWidth,
  2561. inputHeight,
  2562. threeDFormat,
  2563. videoDecoder,
  2564. outputVideoCodec,
  2565. request.Width,
  2566. request.Height,
  2567. request.MaxWidth,
  2568. request.MaxHeight));
  2569. }
  2570. // Add Cuda tonemapping filter.
  2571. if (isNvdecDecoder && isCudaTonemappingSupported)
  2572. {
  2573. isNoTonemapFilterApplied = false;
  2574. var inputHdrParams = GetInputHdrParams(videoStream.ColorTransfer);
  2575. if (!string.IsNullOrEmpty(inputHdrParams))
  2576. {
  2577. filters.Add(inputHdrParams);
  2578. }
  2579. var parameters = (hasGraphicalSubs && isCudaOverlaySupported && isNvencEncoder)
  2580. ? "tonemap_cuda=format=yuv420p:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:peak={1}:desat={2}"
  2581. : "tonemap_cuda=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:peak={1}:desat={2}";
  2582. if (options.TonemappingParam != 0)
  2583. {
  2584. parameters += ":param={3}";
  2585. }
  2586. if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
  2587. {
  2588. parameters += ":range={4}";
  2589. }
  2590. filters.Add(
  2591. string.Format(
  2592. CultureInfo.InvariantCulture,
  2593. parameters,
  2594. options.TonemappingAlgorithm,
  2595. options.TonemappingPeak,
  2596. options.TonemappingDesat,
  2597. options.TonemappingParam,
  2598. options.TonemappingRange));
  2599. if (isLibX264Encoder
  2600. || isLibX265Encoder
  2601. || hasTextSubs
  2602. || (hasGraphicalSubs && !isCudaOverlaySupported && isNvencEncoder))
  2603. {
  2604. if (isNvencEncoder)
  2605. {
  2606. isHwuploadCudaRequired = true;
  2607. }
  2608. filters.Add("hwdownload");
  2609. filters.Add("format=nv12");
  2610. }
  2611. var outputSdrParams = GetOutputSdrParams(options.TonemappingRange);
  2612. if (!string.IsNullOrEmpty(outputSdrParams))
  2613. {
  2614. filters.Add(outputSdrParams);
  2615. }
  2616. }
  2617. // Add VPP tonemapping filter for VAAPI.
  2618. // Full hardware based video post processing, faster than OpenCL but lacks fine tuning options.
  2619. if ((isTonemappingSupportedOnVaapi || isTonemappingSupportedOnQsv)
  2620. && isVppTonemappingSupported)
  2621. {
  2622. filters.Add("tonemap_vaapi=format=nv12:transfer=bt709:matrix=bt709:primaries=bt709");
  2623. }
  2624. // Another case is when using Nvenc decoder.
  2625. if (isNvdecDecoder && !isOpenclTonemappingSupported && !isCudaTonemappingSupported)
  2626. {
  2627. var codec = videoStream.Codec;
  2628. var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat);
  2629. // Assert 10-bit hardware decodable
  2630. if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  2631. || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  2632. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  2633. {
  2634. if (isCudaFormatConversionSupported)
  2635. {
  2636. if (isLibX264Encoder
  2637. || isLibX265Encoder
  2638. || hasTextSubs
  2639. || (hasGraphicalSubs && !isCudaOverlaySupported && isNvencEncoder))
  2640. {
  2641. if (isNvencEncoder)
  2642. {
  2643. isHwuploadCudaRequired = true;
  2644. }
  2645. filters.Add("hwdownload");
  2646. filters.Add("format=nv12");
  2647. }
  2648. }
  2649. else
  2650. {
  2651. // Download data from GPU to CPU as p010 format.
  2652. filters.Add("hwdownload");
  2653. filters.Add("format=p010");
  2654. // Cuda lacks of a pixel format converter.
  2655. if (isNvencEncoder)
  2656. {
  2657. isHwuploadCudaRequired = true;
  2658. filters.Add("format=yuv420p");
  2659. }
  2660. }
  2661. }
  2662. // Assert 8-bit hardware decodable
  2663. else if (!isColorDepth10
  2664. && (isLibX264Encoder
  2665. || isLibX265Encoder
  2666. || hasTextSubs
  2667. || (hasGraphicalSubs && !isCudaOverlaySupported && isNvencEncoder)))
  2668. {
  2669. if (isNvencEncoder)
  2670. {
  2671. isHwuploadCudaRequired = true;
  2672. }
  2673. filters.Add("hwdownload");
  2674. filters.Add("format=nv12");
  2675. }
  2676. }
  2677. // Add parameters to use VAAPI with burn-in text subtitles (GH issue #642)
  2678. if (isVaapiH264Encoder
  2679. || isVaapiHevcEncoder
  2680. || (isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  2681. {
  2682. if (hasTextSubs)
  2683. {
  2684. // Convert hw context from ocl to va.
  2685. // For tonemapping and text subs burn-in.
  2686. if (isTonemappingSupportedOnVaapi && isOpenclTonemappingSupported && !isVppTonemappingSupported)
  2687. {
  2688. filters.Add("scale_vaapi");
  2689. }
  2690. // Test passed on Intel and AMD gfx
  2691. filters.Add("hwmap=mode=read+write");
  2692. filters.Add("format=nv12");
  2693. }
  2694. }
  2695. if (hasTextSubs)
  2696. {
  2697. var subParam = GetTextSubtitleParam(state);
  2698. filters.Add(subParam);
  2699. // Ensure proper filters are passed to ffmpeg in case of hardware acceleration via VA-API
  2700. // Reference: https://trac.ffmpeg.org/wiki/Hardware/VAAPI
  2701. if (isVaapiH264Encoder || isVaapiHevcEncoder)
  2702. {
  2703. filters.Add("hwmap");
  2704. }
  2705. if (isTonemappingSupportedOnQsv && isVppTonemappingSupported)
  2706. {
  2707. filters.Add("hwmap,format=vaapi");
  2708. }
  2709. if (isNvdecDecoder && isNvencEncoder)
  2710. {
  2711. isHwuploadCudaRequired = true;
  2712. }
  2713. }
  2714. // Interop the VAAPI data to QSV for hybrid tonemapping
  2715. if (isTonemappingSupportedOnQsv && isVppTonemappingSupported && !hasGraphicalSubs)
  2716. {
  2717. filters.Add("hwmap=derive_device=qsv,scale_qsv");
  2718. }
  2719. if (isHwuploadCudaRequired && !hasGraphicalSubs)
  2720. {
  2721. filters.Add("hwupload_cuda");
  2722. }
  2723. // If no tonemap filter is applied,
  2724. // tag the video range as SDR to prevent the encoder from encoding HDR video.
  2725. if (isNoTonemapFilterApplied)
  2726. {
  2727. var outputSdrParams = GetOutputSdrParams(null);
  2728. if (!string.IsNullOrEmpty(outputSdrParams))
  2729. {
  2730. filters.Add(outputSdrParams);
  2731. }
  2732. }
  2733. var output = string.Empty;
  2734. if (filters.Count > 0)
  2735. {
  2736. output += string.Format(
  2737. CultureInfo.InvariantCulture,
  2738. "{0}",
  2739. string.Join(',', filters));
  2740. }
  2741. return output;
  2742. }
  2743. public static string GetInputHdrParams(string colorTransfer)
  2744. {
  2745. if (string.Equals(colorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
  2746. {
  2747. // HLG
  2748. return "setparams=color_primaries=bt2020:color_trc=arib-std-b67:colorspace=bt2020nc";
  2749. }
  2750. else
  2751. {
  2752. // HDR10
  2753. return "setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc";
  2754. }
  2755. }
  2756. public static string GetOutputSdrParams(string tonemappingRange)
  2757. {
  2758. // SDR
  2759. if (string.Equals(tonemappingRange, "tv", StringComparison.OrdinalIgnoreCase))
  2760. {
  2761. return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=tv";
  2762. }
  2763. if (string.Equals(tonemappingRange, "pc", StringComparison.OrdinalIgnoreCase))
  2764. {
  2765. return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=pc";
  2766. }
  2767. return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709";
  2768. }
  2769. /// <summary>
  2770. /// Gets the number of threads.
  2771. /// </summary>
  2772. /// <param name="state">Encoding state.</param>
  2773. /// <param name="encodingOptions">Encoding options.</param>
  2774. /// <param name="outputVideoCodec">Video codec to use.</param>
  2775. /// <returns>Number of threads.</returns>
  2776. #nullable enable
  2777. public static int GetNumberOfThreads(EncodingJobInfo? state, EncodingOptions encodingOptions, string? outputVideoCodec)
  2778. {
  2779. // VP8 and VP9 encoders must have their thread counts set.
  2780. bool mustSetThreadCount = string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)
  2781. || string.Equals(outputVideoCodec, "libvpx-vp9", StringComparison.OrdinalIgnoreCase);
  2782. var threads = state?.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount;
  2783. if (threads <= 0)
  2784. {
  2785. // Automatically set thread count
  2786. return mustSetThreadCount ? Math.Max(Environment.ProcessorCount - 1, 1) : 0;
  2787. }
  2788. else if (threads >= Environment.ProcessorCount)
  2789. {
  2790. return Environment.ProcessorCount;
  2791. }
  2792. return threads;
  2793. }
  2794. #nullable disable
  2795. public void TryStreamCopy(EncodingJobInfo state)
  2796. {
  2797. if (state.VideoStream != null && CanStreamCopyVideo(state, state.VideoStream))
  2798. {
  2799. state.OutputVideoCodec = "copy";
  2800. }
  2801. else
  2802. {
  2803. var user = state.User;
  2804. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  2805. if (user != null && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
  2806. {
  2807. state.OutputVideoCodec = "copy";
  2808. }
  2809. }
  2810. if (state.AudioStream != null
  2811. && CanStreamCopyAudio(state, state.AudioStream, state.SupportedAudioCodecs))
  2812. {
  2813. state.OutputAudioCodec = "copy";
  2814. }
  2815. else
  2816. {
  2817. var user = state.User;
  2818. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  2819. if (user != null && !user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding))
  2820. {
  2821. state.OutputAudioCodec = "copy";
  2822. }
  2823. }
  2824. }
  2825. public string GetInputModifier(EncodingJobInfo state, EncodingOptions encodingOptions)
  2826. {
  2827. var inputModifier = string.Empty;
  2828. var probeSizeArgument = string.Empty;
  2829. string analyzeDurationArgument;
  2830. if (state.MediaSource.AnalyzeDurationMs.HasValue)
  2831. {
  2832. analyzeDurationArgument = "-analyzeduration " + (state.MediaSource.AnalyzeDurationMs.Value * 1000).ToString(CultureInfo.InvariantCulture);
  2833. }
  2834. else
  2835. {
  2836. analyzeDurationArgument = string.Empty;
  2837. }
  2838. if (!string.IsNullOrEmpty(probeSizeArgument))
  2839. {
  2840. inputModifier += " " + probeSizeArgument;
  2841. }
  2842. if (!string.IsNullOrEmpty(analyzeDurationArgument))
  2843. {
  2844. inputModifier += " " + analyzeDurationArgument;
  2845. }
  2846. inputModifier = inputModifier.Trim();
  2847. var userAgentParam = GetUserAgentParam(state);
  2848. if (!string.IsNullOrEmpty(userAgentParam))
  2849. {
  2850. inputModifier += " " + userAgentParam;
  2851. }
  2852. inputModifier = inputModifier.Trim();
  2853. inputModifier += " " + GetFastSeekCommandLineParameter(state.BaseRequest);
  2854. inputModifier = inputModifier.Trim();
  2855. if (state.InputProtocol == MediaProtocol.Rtsp)
  2856. {
  2857. inputModifier += " -rtsp_transport tcp -rtsp_transport udp -rtsp_flags prefer_tcp";
  2858. }
  2859. if (!string.IsNullOrEmpty(state.InputAudioSync))
  2860. {
  2861. inputModifier += " -async " + state.InputAudioSync;
  2862. }
  2863. if (!string.IsNullOrEmpty(state.InputVideoSync))
  2864. {
  2865. inputModifier += " -vsync " + state.InputVideoSync;
  2866. }
  2867. if (state.ReadInputAtNativeFramerate && state.InputProtocol != MediaProtocol.Rtsp)
  2868. {
  2869. inputModifier += " -re";
  2870. }
  2871. var flags = new List<string>();
  2872. if (state.IgnoreInputDts)
  2873. {
  2874. flags.Add("+igndts");
  2875. }
  2876. if (state.IgnoreInputIndex)
  2877. {
  2878. flags.Add("+ignidx");
  2879. }
  2880. if (state.GenPtsInput || IsCopyCodec(state.OutputVideoCodec))
  2881. {
  2882. flags.Add("+genpts");
  2883. }
  2884. if (state.DiscardCorruptFramesInput)
  2885. {
  2886. flags.Add("+discardcorrupt");
  2887. }
  2888. if (state.EnableFastSeekInput)
  2889. {
  2890. flags.Add("+fastseek");
  2891. }
  2892. if (flags.Count > 0)
  2893. {
  2894. inputModifier += " -fflags " + string.Join(string.Empty, flags);
  2895. }
  2896. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
  2897. if (!string.IsNullOrEmpty(videoDecoder))
  2898. {
  2899. inputModifier += " " + videoDecoder;
  2900. if (!IsCopyCodec(state.OutputVideoCodec)
  2901. && videoDecoder.Contains("cuvid", StringComparison.OrdinalIgnoreCase))
  2902. {
  2903. var videoStream = state.VideoStream;
  2904. var inputWidth = videoStream?.Width;
  2905. var inputHeight = videoStream?.Height;
  2906. var request = state.BaseRequest;
  2907. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  2908. if (videoDecoder.Contains("cuvid", StringComparison.OrdinalIgnoreCase)
  2909. && width.HasValue
  2910. && height.HasValue)
  2911. {
  2912. if (width.HasValue && height.HasValue)
  2913. {
  2914. inputModifier += string.Format(
  2915. CultureInfo.InvariantCulture,
  2916. " -resize {0}x{1}",
  2917. width.Value,
  2918. height.Value);
  2919. }
  2920. if (state.DeInterlace("h264", true))
  2921. {
  2922. inputModifier += " -deint 1";
  2923. if (!encodingOptions.DeinterlaceDoubleRate || (videoStream?.AverageFrameRate ?? 60) > 30)
  2924. {
  2925. inputModifier += " -drop_second_field 1";
  2926. }
  2927. }
  2928. }
  2929. }
  2930. }
  2931. if (state.IsVideoRequest)
  2932. {
  2933. var outputVideoCodec = GetVideoEncoder(state, encodingOptions);
  2934. // Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking
  2935. if (!string.Equals(state.InputContainer, "wtv", StringComparison.OrdinalIgnoreCase)
  2936. && state.TranscodingType != TranscodingJobType.Progressive
  2937. && !state.EnableBreakOnNonKeyFrames(outputVideoCodec)
  2938. && (state.BaseRequest.StartTimeTicks ?? 0) > 0)
  2939. {
  2940. inputModifier += " -noaccurate_seek";
  2941. }
  2942. if (!string.IsNullOrEmpty(state.InputContainer) && state.VideoType == VideoType.VideoFile && string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
  2943. {
  2944. var inputFormat = GetInputFormat(state.InputContainer);
  2945. if (!string.IsNullOrEmpty(inputFormat))
  2946. {
  2947. inputModifier += " -f " + inputFormat;
  2948. }
  2949. }
  2950. }
  2951. if (state.MediaSource.RequiresLooping)
  2952. {
  2953. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  2954. }
  2955. return inputModifier;
  2956. }
  2957. public void AttachMediaSourceInfo(
  2958. EncodingJobInfo state,
  2959. EncodingOptions encodingOptions,
  2960. MediaSourceInfo mediaSource,
  2961. string requestedUrl)
  2962. {
  2963. if (state == null)
  2964. {
  2965. throw new ArgumentNullException(nameof(state));
  2966. }
  2967. if (mediaSource == null)
  2968. {
  2969. throw new ArgumentNullException(nameof(mediaSource));
  2970. }
  2971. var path = mediaSource.Path;
  2972. var protocol = mediaSource.Protocol;
  2973. if (!string.IsNullOrEmpty(mediaSource.EncoderPath) && mediaSource.EncoderProtocol.HasValue)
  2974. {
  2975. path = mediaSource.EncoderPath;
  2976. protocol = mediaSource.EncoderProtocol.Value;
  2977. }
  2978. state.MediaPath = path;
  2979. state.InputProtocol = protocol;
  2980. state.InputContainer = mediaSource.Container;
  2981. state.RunTimeTicks = mediaSource.RunTimeTicks;
  2982. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  2983. state.IsoType = mediaSource.IsoType;
  2984. if (mediaSource.Timestamp.HasValue)
  2985. {
  2986. state.InputTimestamp = mediaSource.Timestamp.Value;
  2987. }
  2988. state.RunTimeTicks = mediaSource.RunTimeTicks;
  2989. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  2990. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  2991. if (state.ReadInputAtNativeFramerate
  2992. || (mediaSource.Protocol == MediaProtocol.File
  2993. && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase)))
  2994. {
  2995. state.InputVideoSync = "-1";
  2996. state.InputAudioSync = "1";
  2997. }
  2998. if (string.Equals(mediaSource.Container, "wma", StringComparison.OrdinalIgnoreCase)
  2999. || string.Equals(mediaSource.Container, "asf", StringComparison.OrdinalIgnoreCase))
  3000. {
  3001. // Seeing some stuttering when transcoding wma to audio-only HLS
  3002. state.InputAudioSync = "1";
  3003. }
  3004. var mediaStreams = mediaSource.MediaStreams;
  3005. if (state.IsVideoRequest)
  3006. {
  3007. var videoRequest = state.BaseRequest;
  3008. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  3009. {
  3010. if (string.IsNullOrEmpty(requestedUrl))
  3011. {
  3012. requestedUrl = "test." + videoRequest.Container;
  3013. }
  3014. videoRequest.VideoCodec = InferVideoCodec(requestedUrl);
  3015. }
  3016. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  3017. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  3018. state.SubtitleDeliveryMethod = videoRequest.SubtitleMethod;
  3019. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  3020. if (state.SubtitleStream != null && !state.SubtitleStream.IsExternal)
  3021. {
  3022. state.InternalSubtitleStreamOffset = mediaStreams.Where(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal).ToList().IndexOf(state.SubtitleStream);
  3023. }
  3024. EnforceResolutionLimit(state);
  3025. NormalizeSubtitleEmbed(state);
  3026. }
  3027. else
  3028. {
  3029. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  3030. }
  3031. state.MediaSource = mediaSource;
  3032. var request = state.BaseRequest;
  3033. var supportedAudioCodecs = state.SupportedAudioCodecs;
  3034. if (request != null && supportedAudioCodecs != null && supportedAudioCodecs.Length > 0)
  3035. {
  3036. var supportedAudioCodecsList = supportedAudioCodecs.ToList();
  3037. ShiftAudioCodecsIfNeeded(supportedAudioCodecsList, state.AudioStream);
  3038. state.SupportedAudioCodecs = supportedAudioCodecsList.ToArray();
  3039. request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => _mediaEncoder.CanEncodeToAudioCodec(i))
  3040. ?? state.SupportedAudioCodecs.FirstOrDefault();
  3041. }
  3042. var supportedVideoCodecs = state.SupportedVideoCodecs;
  3043. if (request != null && supportedVideoCodecs != null && supportedVideoCodecs.Length > 0)
  3044. {
  3045. var supportedVideoCodecsList = supportedVideoCodecs.ToList();
  3046. ShiftVideoCodecsIfNeeded(supportedVideoCodecsList, encodingOptions);
  3047. state.SupportedVideoCodecs = supportedVideoCodecsList.ToArray();
  3048. request.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
  3049. }
  3050. }
  3051. private void ShiftAudioCodecsIfNeeded(List<string> audioCodecs, MediaStream audioStream)
  3052. {
  3053. // No need to shift if there is only one supported audio codec.
  3054. if (audioCodecs.Count < 2)
  3055. {
  3056. return;
  3057. }
  3058. var inputChannels = audioStream == null ? 6 : audioStream.Channels ?? 6;
  3059. if (inputChannels >= 6)
  3060. {
  3061. return;
  3062. }
  3063. // Transcoding to 2ch ac3 almost always causes a playback failure
  3064. // 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
  3065. var shiftAudioCodecs = new[] { "ac3", "eac3" };
  3066. if (audioCodecs.All(i => shiftAudioCodecs.Contains(i, StringComparer.OrdinalIgnoreCase)))
  3067. {
  3068. return;
  3069. }
  3070. while (shiftAudioCodecs.Contains(audioCodecs[0], StringComparer.OrdinalIgnoreCase))
  3071. {
  3072. var removed = shiftAudioCodecs[0];
  3073. audioCodecs.RemoveAt(0);
  3074. audioCodecs.Add(removed);
  3075. }
  3076. }
  3077. private void ShiftVideoCodecsIfNeeded(List<string> videoCodecs, EncodingOptions encodingOptions)
  3078. {
  3079. // Shift hevc/h265 to the end of list if hevc encoding is not allowed.
  3080. if (encodingOptions.AllowHevcEncoding)
  3081. {
  3082. return;
  3083. }
  3084. // No need to shift if there is only one supported video codec.
  3085. if (videoCodecs.Count < 2)
  3086. {
  3087. return;
  3088. }
  3089. var shiftVideoCodecs = new[] { "hevc", "h265" };
  3090. if (videoCodecs.All(i => shiftVideoCodecs.Contains(i, StringComparer.OrdinalIgnoreCase)))
  3091. {
  3092. return;
  3093. }
  3094. while (shiftVideoCodecs.Contains(videoCodecs[0], StringComparer.OrdinalIgnoreCase))
  3095. {
  3096. var removed = shiftVideoCodecs[0];
  3097. videoCodecs.RemoveAt(0);
  3098. videoCodecs.Add(removed);
  3099. }
  3100. }
  3101. private void NormalizeSubtitleEmbed(EncodingJobInfo state)
  3102. {
  3103. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  3104. {
  3105. return;
  3106. }
  3107. // This is tricky to remux in, after converting to dvdsub it's not positioned correctly
  3108. // Therefore, let's just burn it in
  3109. if (string.Equals(state.SubtitleStream.Codec, "DVBSUB", StringComparison.OrdinalIgnoreCase))
  3110. {
  3111. state.SubtitleDeliveryMethod = SubtitleDeliveryMethod.Encode;
  3112. }
  3113. }
  3114. /// <summary>
  3115. /// Gets the ffmpeg option string for the hardware accelerated video decoder.
  3116. /// </summary>
  3117. /// <param name="state">The encoding job info.</param>
  3118. /// <param name="encodingOptions">The encoding options.</param>
  3119. /// <returns>The option string or null if none available.</returns>
  3120. protected string GetHardwareAcceleratedVideoDecoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  3121. {
  3122. var videoStream = state.VideoStream;
  3123. if (videoStream == null)
  3124. {
  3125. return null;
  3126. }
  3127. var videoType = state.MediaSource.VideoType ?? VideoType.VideoFile;
  3128. // Only use alternative encoders for video files.
  3129. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  3130. // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this.
  3131. if (videoType != VideoType.VideoFile)
  3132. {
  3133. return null;
  3134. }
  3135. if (IsCopyCodec(state.OutputVideoCodec))
  3136. {
  3137. return null;
  3138. }
  3139. if (!string.IsNullOrEmpty(videoStream.Codec) && !string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
  3140. {
  3141. var isColorDepth10 = IsColorDepth10(state);
  3142. // Only hevc and vp9 formats have 10-bit hardware decoder support now.
  3143. if (isColorDepth10 && !(string.Equals(videoStream.Codec, "hevc", StringComparison.OrdinalIgnoreCase)
  3144. || string.Equals(videoStream.Codec, "h265", StringComparison.OrdinalIgnoreCase)
  3145. || string.Equals(videoStream.Codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  3146. {
  3147. return null;
  3148. }
  3149. // Hybrid VPP tonemapping with VAAPI
  3150. if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase)
  3151. && IsVppTonemappingSupported(state, encodingOptions))
  3152. {
  3153. var outputVideoCodec = GetVideoEncoder(state, encodingOptions) ?? string.Empty;
  3154. var isQsvEncoder = outputVideoCodec.Contains("qsv", StringComparison.OrdinalIgnoreCase);
  3155. if (isQsvEncoder)
  3156. {
  3157. // Since tonemap_vaapi only support HEVC for now, no need to check the codec again.
  3158. return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10);
  3159. }
  3160. }
  3161. if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  3162. {
  3163. switch (videoStream.Codec.ToLowerInvariant())
  3164. {
  3165. case "avc":
  3166. case "h264":
  3167. return GetHwDecoderName(encodingOptions, "h264_qsv", "h264", isColorDepth10);
  3168. case "hevc":
  3169. case "h265":
  3170. return GetHwDecoderName(encodingOptions, "hevc_qsv", "hevc", isColorDepth10);
  3171. case "mpeg2video":
  3172. return GetHwDecoderName(encodingOptions, "mpeg2_qsv", "mpeg2video", isColorDepth10);
  3173. case "vc1":
  3174. return GetHwDecoderName(encodingOptions, "vc1_qsv", "vc1", isColorDepth10);
  3175. case "vp8":
  3176. return GetHwDecoderName(encodingOptions, "vp8_qsv", "vp8", isColorDepth10);
  3177. case "vp9":
  3178. return GetHwDecoderName(encodingOptions, "vp9_qsv", "vp9", isColorDepth10);
  3179. }
  3180. }
  3181. else if (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  3182. {
  3183. switch (videoStream.Codec.ToLowerInvariant())
  3184. {
  3185. case "avc":
  3186. case "h264":
  3187. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3188. ? GetHwaccelType(state, encodingOptions, "h264", isColorDepth10)
  3189. : GetHwDecoderName(encodingOptions, "h264_cuvid", "h264", isColorDepth10);
  3190. case "hevc":
  3191. case "h265":
  3192. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3193. ? GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10)
  3194. : GetHwDecoderName(encodingOptions, "hevc_cuvid", "hevc", isColorDepth10);
  3195. case "mpeg2video":
  3196. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3197. ? GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10)
  3198. : GetHwDecoderName(encodingOptions, "mpeg2_cuvid", "mpeg2video", isColorDepth10);
  3199. case "vc1":
  3200. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3201. ? GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10)
  3202. : GetHwDecoderName(encodingOptions, "vc1_cuvid", "vc1", isColorDepth10);
  3203. case "mpeg4":
  3204. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3205. ? GetHwaccelType(state, encodingOptions, "mpeg4", isColorDepth10)
  3206. : GetHwDecoderName(encodingOptions, "mpeg4_cuvid", "mpeg4", isColorDepth10);
  3207. case "vp8":
  3208. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3209. ? GetHwaccelType(state, encodingOptions, "vp8", isColorDepth10)
  3210. : GetHwDecoderName(encodingOptions, "vp8_cuvid", "vp8", isColorDepth10);
  3211. case "vp9":
  3212. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3213. ? GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10)
  3214. : GetHwDecoderName(encodingOptions, "vp9_cuvid", "vp9", isColorDepth10);
  3215. }
  3216. }
  3217. else if (string.Equals(encodingOptions.HardwareAccelerationType, "mediacodec", StringComparison.OrdinalIgnoreCase))
  3218. {
  3219. switch (videoStream.Codec.ToLowerInvariant())
  3220. {
  3221. case "avc":
  3222. case "h264":
  3223. return GetHwDecoderName(encodingOptions, "h264_mediacodec", "h264", isColorDepth10);
  3224. case "hevc":
  3225. case "h265":
  3226. return GetHwDecoderName(encodingOptions, "hevc_mediacodec", "hevc", isColorDepth10);
  3227. case "mpeg2video":
  3228. return GetHwDecoderName(encodingOptions, "mpeg2_mediacodec", "mpeg2video", isColorDepth10);
  3229. case "mpeg4":
  3230. return GetHwDecoderName(encodingOptions, "mpeg4_mediacodec", "mpeg4", isColorDepth10);
  3231. case "vp8":
  3232. return GetHwDecoderName(encodingOptions, "vp8_mediacodec", "vp8", isColorDepth10);
  3233. case "vp9":
  3234. return GetHwDecoderName(encodingOptions, "vp9_mediacodec", "vp9", isColorDepth10);
  3235. }
  3236. }
  3237. else if (string.Equals(encodingOptions.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase))
  3238. {
  3239. switch (videoStream.Codec.ToLowerInvariant())
  3240. {
  3241. case "avc":
  3242. case "h264":
  3243. return GetHwDecoderName(encodingOptions, "h264_mmal", "h264", isColorDepth10);
  3244. case "mpeg2video":
  3245. return GetHwDecoderName(encodingOptions, "mpeg2_mmal", "mpeg2video", isColorDepth10);
  3246. case "mpeg4":
  3247. return GetHwDecoderName(encodingOptions, "mpeg4_mmal", "mpeg4", isColorDepth10);
  3248. case "vc1":
  3249. return GetHwDecoderName(encodingOptions, "vc1_mmal", "vc1", isColorDepth10);
  3250. }
  3251. }
  3252. else if (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  3253. {
  3254. switch (videoStream.Codec.ToLowerInvariant())
  3255. {
  3256. case "avc":
  3257. case "h264":
  3258. return GetHwaccelType(state, encodingOptions, "h264", isColorDepth10);
  3259. case "hevc":
  3260. case "h265":
  3261. return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10);
  3262. case "mpeg2video":
  3263. return GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10);
  3264. case "vc1":
  3265. return GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10);
  3266. case "mpeg4":
  3267. return GetHwaccelType(state, encodingOptions, "mpeg4", isColorDepth10);
  3268. case "vp9":
  3269. return GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10);
  3270. }
  3271. }
  3272. else if (string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  3273. {
  3274. switch (videoStream.Codec.ToLowerInvariant())
  3275. {
  3276. case "avc":
  3277. case "h264":
  3278. return GetHwaccelType(state, encodingOptions, "h264", isColorDepth10);
  3279. case "hevc":
  3280. case "h265":
  3281. return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10);
  3282. case "mpeg2video":
  3283. return GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10);
  3284. case "vc1":
  3285. return GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10);
  3286. case "vp8":
  3287. return GetHwaccelType(state, encodingOptions, "vp8", isColorDepth10);
  3288. case "vp9":
  3289. return GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10);
  3290. }
  3291. }
  3292. else if (string.Equals(encodingOptions.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  3293. {
  3294. switch (videoStream.Codec.ToLowerInvariant())
  3295. {
  3296. case "avc":
  3297. case "h264":
  3298. return GetHwDecoderName(encodingOptions, "h264_opencl", "h264", isColorDepth10);
  3299. case "hevc":
  3300. case "h265":
  3301. return GetHwDecoderName(encodingOptions, "hevc_opencl", "hevc", isColorDepth10);
  3302. case "mpeg2video":
  3303. return GetHwDecoderName(encodingOptions, "mpeg2_opencl", "mpeg2video", isColorDepth10);
  3304. case "mpeg4":
  3305. return GetHwDecoderName(encodingOptions, "mpeg4_opencl", "mpeg4", isColorDepth10);
  3306. case "vc1":
  3307. return GetHwDecoderName(encodingOptions, "vc1_opencl", "vc1", isColorDepth10);
  3308. case "vp8":
  3309. return GetHwDecoderName(encodingOptions, "vp8_opencl", "vp8", isColorDepth10);
  3310. case "vp9":
  3311. return GetHwDecoderName(encodingOptions, "vp9_opencl", "vp9", isColorDepth10);
  3312. }
  3313. }
  3314. }
  3315. var whichCodec = videoStream.Codec?.ToLowerInvariant();
  3316. switch (whichCodec)
  3317. {
  3318. case "avc":
  3319. whichCodec = "h264";
  3320. break;
  3321. case "h265":
  3322. whichCodec = "hevc";
  3323. break;
  3324. }
  3325. // Avoid a second attempt if no hardware acceleration is being used
  3326. encodingOptions.HardwareDecodingCodecs = encodingOptions.HardwareDecodingCodecs.Where(val => val != whichCodec).ToArray();
  3327. // leave blank so ffmpeg will decide
  3328. return null;
  3329. }
  3330. /// <summary>
  3331. /// Gets a hw decoder name.
  3332. /// </summary>
  3333. /// <param name="options">Encoding options.</param>
  3334. /// <param name="decoder">Decoder to use.</param>
  3335. /// <param name="videoCodec">Video codec to use.</param>
  3336. /// <param name="isColorDepth10">Specifies if color depth 10.</param>
  3337. /// <returns>Hardware decoder name.</returns>
  3338. public string GetHwDecoderName(EncodingOptions options, string decoder, string videoCodec, bool isColorDepth10)
  3339. {
  3340. var isCodecAvailable = _mediaEncoder.SupportsDecoder(decoder) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase);
  3341. if (isColorDepth10 && isCodecAvailable)
  3342. {
  3343. if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc)
  3344. || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9))
  3345. {
  3346. return null;
  3347. }
  3348. }
  3349. return isCodecAvailable ? ("-c:v " + decoder) : null;
  3350. }
  3351. /// <summary>
  3352. /// Gets a hwaccel type to use as a hardware decoder(dxva/vaapi) depending on the system.
  3353. /// </summary>
  3354. /// <param name="state">Encoding state.</param>
  3355. /// <param name="options">Encoding options.</param>
  3356. /// <param name="videoCodec">Video codec to use.</param>
  3357. /// <param name="isColorDepth10">Specifies if color depth 10.</param>
  3358. /// <returns>Hardware accelerator type.</returns>
  3359. public string GetHwaccelType(EncodingJobInfo state, EncodingOptions options, string videoCodec, bool isColorDepth10)
  3360. {
  3361. var isWindows = OperatingSystem.IsWindows();
  3362. var isLinux = OperatingSystem.IsLinux();
  3363. var isWindows8orLater = Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1);
  3364. var isDxvaSupported = _mediaEncoder.SupportsHwaccel("dxva2") || _mediaEncoder.SupportsHwaccel("d3d11va");
  3365. var isCodecAvailable = options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase);
  3366. if (isColorDepth10 && isCodecAvailable)
  3367. {
  3368. if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc)
  3369. || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9))
  3370. {
  3371. return null;
  3372. }
  3373. }
  3374. if (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  3375. {
  3376. // Currently there is no AMF decoder on Linux, only have h264 encoder.
  3377. if (isDxvaSupported && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  3378. {
  3379. if (isWindows && isWindows8orLater)
  3380. {
  3381. return "-hwaccel d3d11va";
  3382. }
  3383. if (isWindows && !isWindows8orLater)
  3384. {
  3385. return "-hwaccel dxva2";
  3386. }
  3387. }
  3388. }
  3389. if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)
  3390. || (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase)
  3391. && IsVppTonemappingSupported(state, options)))
  3392. {
  3393. if (IsVaapiSupported(state) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  3394. {
  3395. if (isLinux)
  3396. {
  3397. return "-hwaccel vaapi";
  3398. }
  3399. }
  3400. }
  3401. if (string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  3402. {
  3403. if (options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  3404. {
  3405. return "-hwaccel cuda";
  3406. }
  3407. }
  3408. return null;
  3409. }
  3410. public string GetSubtitleEmbedArguments(EncodingJobInfo state)
  3411. {
  3412. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  3413. {
  3414. return string.Empty;
  3415. }
  3416. var format = state.SupportedSubtitleCodecs.FirstOrDefault();
  3417. string codec;
  3418. if (string.IsNullOrEmpty(format) || string.Equals(format, state.SubtitleStream.Codec, StringComparison.OrdinalIgnoreCase))
  3419. {
  3420. codec = "copy";
  3421. }
  3422. else
  3423. {
  3424. codec = format;
  3425. }
  3426. return " -codec:s:0 " + codec + " -disposition:s:0 default";
  3427. }
  3428. public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath, string defaultPreset)
  3429. {
  3430. // Get the output codec name
  3431. var videoCodec = GetVideoEncoder(state, encodingOptions);
  3432. var format = string.Empty;
  3433. var keyFrame = string.Empty;
  3434. if (string.Equals(Path.GetExtension(outputPath), ".mp4", StringComparison.OrdinalIgnoreCase)
  3435. && state.BaseRequest.Context == EncodingContext.Streaming)
  3436. {
  3437. // Comparison: https://github.com/jansmolders86/mediacenterjs/blob/master/lib/transcoding/desktop.js
  3438. format = " -f mp4 -movflags frag_keyframe+empty_moov";
  3439. }
  3440. var threads = GetNumberOfThreads(state, encodingOptions, videoCodec);
  3441. var inputModifier = GetInputModifier(state, encodingOptions);
  3442. return string.Format(
  3443. CultureInfo.InvariantCulture,
  3444. "{0} {1}{2} {3} {4} -map_metadata -1 -map_chapters -1 -threads {5} {6}{7}{8} -y \"{9}\"",
  3445. inputModifier,
  3446. GetInputArgument(state, encodingOptions),
  3447. keyFrame,
  3448. GetMapArgs(state),
  3449. GetProgressiveVideoArguments(state, encodingOptions, videoCodec, defaultPreset),
  3450. threads,
  3451. GetProgressiveVideoAudioArguments(state, encodingOptions),
  3452. GetSubtitleEmbedArguments(state),
  3453. format,
  3454. outputPath).Trim();
  3455. }
  3456. public string GetOutputFFlags(EncodingJobInfo state)
  3457. {
  3458. var flags = new List<string>();
  3459. if (state.GenPtsOutput)
  3460. {
  3461. flags.Add("+genpts");
  3462. }
  3463. if (flags.Count > 0)
  3464. {
  3465. return " -fflags " + string.Join(string.Empty, flags);
  3466. }
  3467. return string.Empty;
  3468. }
  3469. public string GetProgressiveVideoArguments(EncodingJobInfo state, EncodingOptions encodingOptions, string videoCodec, string defaultPreset)
  3470. {
  3471. var args = "-codec:v:0 " + videoCodec;
  3472. if (state.BaseRequest.EnableMpegtsM2TsMode)
  3473. {
  3474. args += " -mpegts_m2ts_mode 1";
  3475. }
  3476. if (IsCopyCodec(videoCodec))
  3477. {
  3478. if (state.VideoStream != null
  3479. && string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase)
  3480. && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
  3481. {
  3482. string bitStreamArgs = GetBitStreamArgs(state.VideoStream);
  3483. if (!string.IsNullOrEmpty(bitStreamArgs))
  3484. {
  3485. args += " " + bitStreamArgs;
  3486. }
  3487. }
  3488. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  3489. {
  3490. args += " -copyts -avoid_negative_ts disabled -start_at_zero";
  3491. }
  3492. if (!state.RunTimeTicks.HasValue)
  3493. {
  3494. args += " -fflags +genpts";
  3495. }
  3496. }
  3497. else
  3498. {
  3499. var keyFrameArg = string.Format(
  3500. CultureInfo.InvariantCulture,
  3501. " -force_key_frames \"expr:gte(t,n_forced*{0})\"",
  3502. 5);
  3503. args += keyFrameArg;
  3504. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  3505. var hasCopyTs = false;
  3506. // Add resolution params, if specified
  3507. if (!hasGraphicalSubs)
  3508. {
  3509. var outputSizeParam = GetOutputSizeParam(state, encodingOptions, videoCodec);
  3510. args += outputSizeParam;
  3511. hasCopyTs = outputSizeParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  3512. }
  3513. // This is for graphical subs
  3514. if (hasGraphicalSubs)
  3515. {
  3516. var graphicalSubtitleParam = GetGraphicalSubtitleParam(state, encodingOptions, videoCodec);
  3517. args += graphicalSubtitleParam;
  3518. hasCopyTs = graphicalSubtitleParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  3519. }
  3520. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  3521. {
  3522. if (!hasCopyTs)
  3523. {
  3524. args += " -copyts";
  3525. }
  3526. args += " -avoid_negative_ts disabled";
  3527. if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
  3528. {
  3529. args += " -start_at_zero";
  3530. }
  3531. }
  3532. var qualityParam = GetVideoQualityParam(state, videoCodec, encodingOptions, defaultPreset);
  3533. if (!string.IsNullOrEmpty(qualityParam))
  3534. {
  3535. args += " " + qualityParam.Trim();
  3536. }
  3537. }
  3538. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  3539. {
  3540. args += " -vsync " + state.OutputVideoSync;
  3541. }
  3542. args += GetOutputFFlags(state);
  3543. return args;
  3544. }
  3545. public string GetProgressiveVideoAudioArguments(EncodingJobInfo state, EncodingOptions encodingOptions)
  3546. {
  3547. // If the video doesn't have an audio stream, return a default.
  3548. if (state.AudioStream == null && state.VideoStream != null)
  3549. {
  3550. return string.Empty;
  3551. }
  3552. // Get the output codec name
  3553. var codec = GetAudioEncoder(state);
  3554. var args = "-codec:a:0 " + codec;
  3555. if (IsCopyCodec(codec))
  3556. {
  3557. return args;
  3558. }
  3559. // Add the number of audio channels
  3560. var channels = state.OutputAudioChannels;
  3561. if (channels.HasValue)
  3562. {
  3563. args += " -ac " + channels.Value;
  3564. }
  3565. var bitrate = state.OutputAudioBitrate;
  3566. if (bitrate.HasValue)
  3567. {
  3568. args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
  3569. }
  3570. if (state.OutputAudioSampleRate.HasValue)
  3571. {
  3572. args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
  3573. }
  3574. args += GetAudioFilterParam(state, encodingOptions);
  3575. return args;
  3576. }
  3577. public string GetProgressiveAudioFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath)
  3578. {
  3579. var audioTranscodeParams = new List<string>();
  3580. var bitrate = state.OutputAudioBitrate;
  3581. if (bitrate.HasValue)
  3582. {
  3583. audioTranscodeParams.Add("-ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture));
  3584. }
  3585. if (state.OutputAudioChannels.HasValue)
  3586. {
  3587. audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture));
  3588. }
  3589. // opus will fail on 44100
  3590. if (!string.Equals(state.OutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase))
  3591. {
  3592. if (state.OutputAudioSampleRate.HasValue)
  3593. {
  3594. audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture));
  3595. }
  3596. }
  3597. var threads = GetNumberOfThreads(state, encodingOptions, null);
  3598. var inputModifier = GetInputModifier(state, encodingOptions);
  3599. return string.Format(
  3600. CultureInfo.InvariantCulture,
  3601. "{0} {1}{7}{8} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1{6} -y \"{5}\"",
  3602. inputModifier,
  3603. GetInputArgument(state, encodingOptions),
  3604. threads,
  3605. " -vn",
  3606. string.Join(' ', audioTranscodeParams),
  3607. outputPath,
  3608. string.Empty,
  3609. string.Empty,
  3610. string.Empty).Trim();
  3611. }
  3612. public static bool IsCopyCodec(string codec)
  3613. {
  3614. return string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase);
  3615. }
  3616. public static bool IsColorDepth10(EncodingJobInfo state)
  3617. {
  3618. var result = false;
  3619. var videoStream = state.VideoStream;
  3620. if (videoStream != null)
  3621. {
  3622. if (videoStream.BitDepth.HasValue)
  3623. {
  3624. return videoStream.BitDepth.Value == 10;
  3625. }
  3626. if (!string.IsNullOrEmpty(videoStream.PixelFormat))
  3627. {
  3628. result = videoStream.PixelFormat.Contains("p10", StringComparison.OrdinalIgnoreCase);
  3629. if (result)
  3630. {
  3631. return true;
  3632. }
  3633. }
  3634. if (!string.IsNullOrEmpty(videoStream.Profile))
  3635. {
  3636. result = videoStream.Profile.Contains("Main 10", StringComparison.OrdinalIgnoreCase)
  3637. || videoStream.Profile.Contains("High 10", StringComparison.OrdinalIgnoreCase)
  3638. || videoStream.Profile.Contains("Profile 2", StringComparison.OrdinalIgnoreCase);
  3639. if (result)
  3640. {
  3641. return true;
  3642. }
  3643. }
  3644. }
  3645. return result;
  3646. }
  3647. }
  3648. }