EncodingHelper.cs 163 KB

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