EncodingHelper.cs 126 KB

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