EncodingHelper.cs 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165
  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 MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Extensions;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.Dlna;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.MediaInfo;
  16. using Microsoft.Extensions.Configuration;
  17. namespace MediaBrowser.Controller.MediaEncoding
  18. {
  19. public class EncodingHelper
  20. {
  21. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  22. private readonly IMediaEncoder _mediaEncoder;
  23. private readonly IFileSystem _fileSystem;
  24. private readonly ISubtitleEncoder _subtitleEncoder;
  25. private readonly IConfiguration _configuration;
  26. private static readonly string[] _videoProfiles = new[]
  27. {
  28. "ConstrainedBaseline",
  29. "Baseline",
  30. "Extended",
  31. "Main",
  32. "High",
  33. "ProgressiveHigh",
  34. "ConstrainedHigh"
  35. };
  36. public EncodingHelper(
  37. IMediaEncoder mediaEncoder,
  38. IFileSystem fileSystem,
  39. ISubtitleEncoder subtitleEncoder,
  40. IConfiguration configuration)
  41. {
  42. _mediaEncoder = mediaEncoder;
  43. _fileSystem = fileSystem;
  44. _subtitleEncoder = subtitleEncoder;
  45. _configuration = configuration;
  46. }
  47. public string GetH264Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  48. => GetH264OrH265Encoder("libx264", "h264", state, encodingOptions);
  49. public string GetH265Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  50. => GetH264OrH265Encoder("libx265", "hevc", state, encodingOptions);
  51. private string GetH264OrH265Encoder(string defaultEncoder, string hwEncoder, EncodingJobInfo state, EncodingOptions encodingOptions)
  52. {
  53. // Only use alternative encoders for video files.
  54. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  55. // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
  56. if (state.VideoType == VideoType.VideoFile)
  57. {
  58. var hwType = encodingOptions.HardwareAccelerationType;
  59. var codecMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
  60. {
  61. {"qsv", hwEncoder + "_qsv"},
  62. {hwEncoder + "_qsv", hwEncoder + "_qsv"},
  63. {"nvenc", hwEncoder + "_nvenc"},
  64. {"amf", hwEncoder + "_amf"},
  65. {"omx", hwEncoder + "_omx"},
  66. {hwEncoder + "_v4l2m2m", hwEncoder + "_v4l2m2m"},
  67. {"mediacodec", hwEncoder + "_mediacodec"},
  68. {"vaapi", hwEncoder + "_vaapi"},
  69. {"videotoolbox", hwEncoder + "_videotoolbox"}
  70. };
  71. if (!string.IsNullOrEmpty(hwType)
  72. && encodingOptions.EnableHardwareEncoding
  73. && codecMap.ContainsKey(hwType))
  74. {
  75. var preferredEncoder = codecMap[hwType];
  76. if (_mediaEncoder.SupportsEncoder(preferredEncoder))
  77. {
  78. return preferredEncoder;
  79. }
  80. }
  81. }
  82. return defaultEncoder;
  83. }
  84. private bool IsVaapiSupported(EncodingJobInfo state)
  85. {
  86. var videoStream = state.VideoStream;
  87. // vaapi will throw an error with this input
  88. // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
  89. if (string.Equals(videoStream?.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  90. {
  91. return false;
  92. }
  93. return _mediaEncoder.SupportsHwaccel("vaapi");
  94. }
  95. /// <summary>
  96. /// Gets the name of the output video codec
  97. /// </summary>
  98. public string GetVideoEncoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  99. {
  100. var codec = state.OutputVideoCodec;
  101. if (!string.IsNullOrEmpty(codec))
  102. {
  103. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  104. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
  105. {
  106. return GetH265Encoder(state, encodingOptions);
  107. }
  108. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  109. {
  110. return GetH264Encoder(state, encodingOptions);
  111. }
  112. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  113. {
  114. return "libvpx";
  115. }
  116. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  117. {
  118. return "wmv2";
  119. }
  120. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  121. {
  122. return "libtheora";
  123. }
  124. return codec.ToLowerInvariant();
  125. }
  126. return "copy";
  127. }
  128. /// <summary>
  129. /// Gets the user agent param.
  130. /// </summary>
  131. /// <param name="state">The state.</param>
  132. /// <returns>System.String.</returns>
  133. public string GetUserAgentParam(EncodingJobInfo state)
  134. {
  135. if (state.RemoteHttpHeaders.TryGetValue("User-Agent", out string useragent))
  136. {
  137. return "-user_agent \"" + useragent + "\"";
  138. }
  139. return string.Empty;
  140. }
  141. public static string GetInputFormat(string container)
  142. {
  143. if (string.IsNullOrEmpty(container))
  144. {
  145. return null;
  146. }
  147. container = container.Replace("mkv", "matroska", StringComparison.OrdinalIgnoreCase);
  148. if (string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
  149. {
  150. return "mpegts";
  151. }
  152. // For these need to find out the ffmpeg names
  153. if (string.Equals(container, "m2ts", StringComparison.OrdinalIgnoreCase))
  154. {
  155. return null;
  156. }
  157. if (string.Equals(container, "wmv", StringComparison.OrdinalIgnoreCase))
  158. {
  159. return null;
  160. }
  161. if (string.Equals(container, "mts", StringComparison.OrdinalIgnoreCase))
  162. {
  163. return null;
  164. }
  165. if (string.Equals(container, "vob", StringComparison.OrdinalIgnoreCase))
  166. {
  167. return null;
  168. }
  169. if (string.Equals(container, "mpg", StringComparison.OrdinalIgnoreCase))
  170. {
  171. return null;
  172. }
  173. if (string.Equals(container, "mpeg", StringComparison.OrdinalIgnoreCase))
  174. {
  175. return null;
  176. }
  177. if (string.Equals(container, "rec", StringComparison.OrdinalIgnoreCase))
  178. {
  179. return null;
  180. }
  181. if (string.Equals(container, "dvr-ms", StringComparison.OrdinalIgnoreCase))
  182. {
  183. return null;
  184. }
  185. if (string.Equals(container, "ogm", StringComparison.OrdinalIgnoreCase))
  186. {
  187. return null;
  188. }
  189. if (string.Equals(container, "divx", StringComparison.OrdinalIgnoreCase))
  190. {
  191. return null;
  192. }
  193. if (string.Equals(container, "tp", StringComparison.OrdinalIgnoreCase))
  194. {
  195. return null;
  196. }
  197. if (string.Equals(container, "rmvb", StringComparison.OrdinalIgnoreCase))
  198. {
  199. return null;
  200. }
  201. if (string.Equals(container, "rtp", StringComparison.OrdinalIgnoreCase))
  202. {
  203. return null;
  204. }
  205. // Seeing reported failures here, not sure yet if this is related to specfying input format
  206. if (string.Equals(container, "m4v", StringComparison.OrdinalIgnoreCase))
  207. {
  208. return null;
  209. }
  210. // obviously don't do this for strm files
  211. if (string.Equals(container, "strm", StringComparison.OrdinalIgnoreCase))
  212. {
  213. return null;
  214. }
  215. return container;
  216. }
  217. public string GetDecoderFromCodec(string codec)
  218. {
  219. // For these need to find out the ffmpeg names
  220. if (string.Equals(codec, "mp2", StringComparison.OrdinalIgnoreCase))
  221. {
  222. return null;
  223. }
  224. if (string.Equals(codec, "aac_latm", StringComparison.OrdinalIgnoreCase))
  225. {
  226. return null;
  227. }
  228. if (string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
  229. {
  230. return null;
  231. }
  232. if (_mediaEncoder.SupportsDecoder(codec))
  233. {
  234. return codec;
  235. }
  236. return null;
  237. }
  238. /// <summary>
  239. /// Infers the audio codec based on the url
  240. /// </summary>
  241. public string InferAudioCodec(string container)
  242. {
  243. var ext = "." + (container ?? string.Empty);
  244. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  245. {
  246. return "mp3";
  247. }
  248. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  249. {
  250. return "aac";
  251. }
  252. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  253. {
  254. return "wma";
  255. }
  256. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  257. {
  258. return "vorbis";
  259. }
  260. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  261. {
  262. return "vorbis";
  263. }
  264. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  265. {
  266. return "vorbis";
  267. }
  268. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  269. {
  270. return "vorbis";
  271. }
  272. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  273. {
  274. return "vorbis";
  275. }
  276. return "copy";
  277. }
  278. /// <summary>
  279. /// Infers the video codec.
  280. /// </summary>
  281. /// <param name="url">The URL.</param>
  282. /// <returns>System.Nullable{VideoCodecs}.</returns>
  283. public string InferVideoCodec(string url)
  284. {
  285. var ext = Path.GetExtension(url);
  286. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  287. {
  288. return "wmv";
  289. }
  290. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  291. {
  292. return "vpx";
  293. }
  294. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  295. {
  296. return "theora";
  297. }
  298. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  299. {
  300. return "h264";
  301. }
  302. return "copy";
  303. }
  304. public int GetVideoProfileScore(string profile)
  305. {
  306. // strip spaces because they may be stripped out on the query string
  307. profile = profile.Replace(" ", "");
  308. return Array.FindIndex(_videoProfiles, x => string.Equals(x, profile, StringComparison.OrdinalIgnoreCase));
  309. }
  310. public string GetInputPathArgument(EncodingJobInfo state)
  311. {
  312. var protocol = state.InputProtocol;
  313. var mediaPath = state.MediaPath ?? string.Empty;
  314. string[] inputPath;
  315. if (state.IsInputVideo
  316. && !(state.VideoType == VideoType.Iso && state.IsoMount == null))
  317. {
  318. inputPath = MediaEncoderHelpers.GetInputArgument(
  319. _fileSystem,
  320. mediaPath,
  321. state.IsoMount,
  322. state.PlayableStreamFileNames);
  323. }
  324. else
  325. {
  326. inputPath = new[] { mediaPath };
  327. }
  328. return _mediaEncoder.GetInputArgument(inputPath, protocol);
  329. }
  330. /// <summary>
  331. /// Gets the audio encoder.
  332. /// </summary>
  333. /// <param name="state">The state.</param>
  334. /// <returns>System.String.</returns>
  335. public string GetAudioEncoder(EncodingJobInfo state)
  336. {
  337. var codec = state.OutputAudioCodec;
  338. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  339. {
  340. // Use libfdk_aac for better audio quality if using custom build of FFmpeg which has fdk_aac support
  341. if (_mediaEncoder.SupportsEncoder("libfdk_aac"))
  342. {
  343. return "libfdk_aac";
  344. }
  345. return "aac";
  346. }
  347. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  348. {
  349. return "libmp3lame";
  350. }
  351. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  352. {
  353. return "libvorbis";
  354. }
  355. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  356. {
  357. return "wmav2";
  358. }
  359. if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
  360. {
  361. return "libopus";
  362. }
  363. return codec.ToLowerInvariant();
  364. }
  365. /// <summary>
  366. /// Gets the input argument.
  367. /// </summary>
  368. public string GetInputArgument(EncodingJobInfo state, EncodingOptions encodingOptions)
  369. {
  370. var arg = new StringBuilder();
  371. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
  372. var outputVideoCodec = GetVideoEncoder(state, encodingOptions);
  373. bool isVaapiDecoder = (videoDecoder ?? string.Empty).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  374. bool isVaapiEncoder = (outputVideoCodec ?? string.Empty).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  375. bool isQsvDecoder = (videoDecoder ?? string.Empty).IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
  376. bool isQsvEncoder = (outputVideoCodec ?? string.Empty).IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
  377. if (state.IsVideoRequest
  378. && string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  379. {
  380. if (isVaapiDecoder)
  381. {
  382. arg.Append("-hwaccel_output_format vaapi ")
  383. .Append("-vaapi_device ")
  384. .Append(encodingOptions.VaapiDevice)
  385. .Append(" ");
  386. }
  387. // While using SW decoder and VAAPI encoder
  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 videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
  399. var outputVideoCodec = GetVideoEncoder(state, encodingOptions);
  400. var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  401. if (!hasTextSubs)
  402. {
  403. if (isQsvEncoder)
  404. {
  405. if (isQsvDecoder)
  406. {
  407. arg.Append("-hwaccel qsv ");
  408. }
  409. // While using SW decoder
  410. else
  411. {
  412. arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
  413. }
  414. }
  415. }
  416. }
  417. arg.Append("-i ")
  418. .Append(GetInputPathArgument(state));
  419. if (state.SubtitleStream != null
  420. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode
  421. && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  422. {
  423. var subtitlePath = state.SubtitleStream.Path;
  424. if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
  425. {
  426. var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
  427. if (File.Exists(idxFile))
  428. {
  429. subtitlePath = idxFile;
  430. }
  431. }
  432. arg.Append(" -i \"").Append(subtitlePath).Append('\"');
  433. }
  434. return arg.ToString();
  435. }
  436. /// <summary>
  437. /// Determines whether the specified stream is H264.
  438. /// </summary>
  439. /// <param name="stream">The stream.</param>
  440. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  441. public bool IsH264(MediaStream stream)
  442. {
  443. var codec = stream.Codec ?? string.Empty;
  444. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1
  445. || codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  446. }
  447. public bool IsH265(MediaStream stream)
  448. {
  449. var codec = stream.Codec ?? string.Empty;
  450. return codec.IndexOf("265", StringComparison.OrdinalIgnoreCase) != -1
  451. || codec.IndexOf("hevc", StringComparison.OrdinalIgnoreCase) != -1;
  452. }
  453. // TODO This is auto inserted into the mpegts mux so it might not be needed
  454. // https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb
  455. public string GetBitStreamArgs(MediaStream stream)
  456. {
  457. if (IsH264(stream))
  458. {
  459. return "-bsf:v h264_mp4toannexb";
  460. }
  461. else if (IsH265(stream))
  462. {
  463. return "-bsf:v hevc_mp4toannexb";
  464. }
  465. else
  466. {
  467. return null;
  468. }
  469. }
  470. public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec)
  471. {
  472. var bitrate = state.OutputVideoBitrate;
  473. if (bitrate.HasValue)
  474. {
  475. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  476. {
  477. // When crf is used with vpx, b:v becomes a max rate
  478. // https://trac.ffmpeg.org/wiki/Encode/VP9
  479. return string.Format(
  480. CultureInfo.InvariantCulture,
  481. " -maxrate:v {0} -bufsize:v {1} -b:v {0}",
  482. bitrate.Value,
  483. bitrate.Value * 2);
  484. }
  485. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  486. {
  487. return string.Format(
  488. CultureInfo.InvariantCulture,
  489. " -b:v {0}",
  490. bitrate.Value);
  491. }
  492. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase) ||
  493. string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  494. {
  495. // h264
  496. return string.Format(
  497. CultureInfo.InvariantCulture,
  498. " -maxrate {0} -bufsize {1}",
  499. bitrate.Value,
  500. bitrate.Value * 2);
  501. }
  502. // h264
  503. return string.Format(
  504. CultureInfo.InvariantCulture,
  505. " -b:v {0} -maxrate {0} -bufsize {1}",
  506. bitrate.Value,
  507. bitrate.Value * 2);
  508. }
  509. return string.Empty;
  510. }
  511. public string NormalizeTranscodingLevel(string videoCodec, string level)
  512. {
  513. // Clients may direct play higher than level 41, but there's no reason to transcode higher
  514. if (double.TryParse(level, NumberStyles.Any, _usCulture, out double requestLevel)
  515. && requestLevel > 41
  516. && (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)
  517. || string.Equals(videoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  518. || string.Equals(videoCodec, "hevc", StringComparison.OrdinalIgnoreCase)))
  519. {
  520. return "41";
  521. }
  522. return level;
  523. }
  524. /// <summary>
  525. /// Gets the text subtitle param.
  526. /// </summary>
  527. /// <param name="state">The state.</param>
  528. /// <returns>System.String.</returns>
  529. public string GetTextSubtitleParam(EncodingJobInfo state)
  530. {
  531. var seconds = Math.Round(TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds);
  532. // hls always copies timestamps
  533. var setPtsParam = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive
  534. ? string.Empty
  535. : string.Format(CultureInfo.InvariantCulture, ",setpts=PTS -{0}/TB", seconds);
  536. // TODO
  537. // var fallbackFontPath = Path.Combine(_appPaths.ProgramDataPath, "fonts", "DroidSansFallback.ttf");
  538. // string fallbackFontParam = string.Empty;
  539. // if (!File.Exists(fallbackFontPath))
  540. // {
  541. // _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath));
  542. // using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf"))
  543. // {
  544. // using (var fileStream = new FileStream(fallbackFontPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  545. // {
  546. // stream.CopyTo(fileStream);
  547. // }
  548. // }
  549. // }
  550. // fallbackFontParam = string.Format(":force_style='FontName=Droid Sans Fallback':fontsdir='{0}'", _mediaEncoder.EscapeSubtitleFilterPath(_fileSystem.GetDirectoryName(fallbackFontPath)));
  551. if (state.SubtitleStream.IsExternal)
  552. {
  553. var subtitlePath = state.SubtitleStream.Path;
  554. var charsetParam = string.Empty;
  555. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  556. {
  557. var charenc = _subtitleEncoder.GetSubtitleFileCharacterSet(
  558. subtitlePath,
  559. state.SubtitleStream.Language,
  560. state.MediaSource.Protocol,
  561. CancellationToken.None).GetAwaiter().GetResult();
  562. if (!string.IsNullOrEmpty(charenc))
  563. {
  564. charsetParam = ":charenc=" + charenc;
  565. }
  566. }
  567. // TODO: Perhaps also use original_size=1920x800 ??
  568. return string.Format(
  569. CultureInfo.InvariantCulture,
  570. "subtitles=filename='{0}'{1}{2}",
  571. _mediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  572. charsetParam,
  573. // fallbackFontParam,
  574. setPtsParam);
  575. }
  576. var mediaPath = state.MediaPath ?? string.Empty;
  577. return string.Format(
  578. CultureInfo.InvariantCulture,
  579. "subtitles='{0}:si={1}'{2}",
  580. _mediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  581. state.InternalSubtitleStreamOffset.ToString(_usCulture),
  582. // fallbackFontParam,
  583. setPtsParam);
  584. }
  585. public double? GetFramerateParam(EncodingJobInfo state)
  586. {
  587. var request = state.BaseRequest;
  588. if (request.Framerate.HasValue)
  589. {
  590. return request.Framerate.Value;
  591. }
  592. var maxrate = request.MaxFramerate;
  593. if (maxrate.HasValue && state.VideoStream != null)
  594. {
  595. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  596. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  597. {
  598. return maxrate;
  599. }
  600. }
  601. return null;
  602. }
  603. /// <summary>
  604. /// Gets the video bitrate to specify on the command line
  605. /// </summary>
  606. public string GetVideoQualityParam(EncodingJobInfo state, string videoEncoder, EncodingOptions encodingOptions, string defaultPreset)
  607. {
  608. var param = string.Empty;
  609. var isVc1 = state.VideoStream != null &&
  610. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  611. var isLibX265 = string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase);
  612. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) || isLibX265)
  613. {
  614. if (!string.IsNullOrEmpty(encodingOptions.EncoderPreset))
  615. {
  616. param += "-preset " + encodingOptions.EncoderPreset;
  617. }
  618. else
  619. {
  620. param += "-preset " + defaultPreset;
  621. }
  622. int encodeCrf = encodingOptions.H264Crf;
  623. if (isLibX265)
  624. {
  625. encodeCrf = encodingOptions.H265Crf;
  626. }
  627. if (encodeCrf >= 0 && encodeCrf <= 51)
  628. {
  629. param += " -crf " + encodeCrf.ToString(CultureInfo.InvariantCulture);
  630. }
  631. else
  632. {
  633. string defaultCrf = "23";
  634. if (isLibX265)
  635. {
  636. defaultCrf = "28";
  637. }
  638. param += " -crf " + defaultCrf;
  639. }
  640. }
  641. else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)) // h264 (h264_qsv)
  642. {
  643. string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" };
  644. if (valid_h264_qsv.Contains(encodingOptions.EncoderPreset, StringComparer.OrdinalIgnoreCase))
  645. {
  646. param += "-preset " + encodingOptions.EncoderPreset;
  647. }
  648. else
  649. {
  650. param += "-preset 7";
  651. }
  652. param += " -look_ahead 0";
  653. }
  654. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc)
  655. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
  656. {
  657. switch (encodingOptions.EncoderPreset)
  658. {
  659. case "veryslow":
  660. param += "-preset slow"; //lossless is only supported on maxwell and newer(2014+)
  661. break;
  662. case "slow":
  663. case "slower":
  664. param += "-preset slow";
  665. break;
  666. case "medium":
  667. param += "-preset medium";
  668. break;
  669. case "fast":
  670. case "faster":
  671. case "veryfast":
  672. case "superfast":
  673. case "ultrafast":
  674. param += "-preset fast";
  675. break;
  676. default:
  677. param += "-preset default";
  678. break;
  679. }
  680. }
  681. else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase)) // webm
  682. {
  683. // Values 0-3, 0 being highest quality but slower
  684. var profileScore = 0;
  685. string crf;
  686. var qmin = "0";
  687. var qmax = "50";
  688. crf = "10";
  689. if (isVc1)
  690. {
  691. profileScore++;
  692. }
  693. // Max of 2
  694. profileScore = Math.Min(profileScore, 2);
  695. // http://www.webmproject.org/docs/encoder-parameters/
  696. param += string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  697. profileScore.ToString(_usCulture),
  698. crf,
  699. qmin,
  700. qmax);
  701. }
  702. else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
  703. {
  704. param += "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  705. }
  706. else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase)) // asf/wmv
  707. {
  708. param += "-qmin 2";
  709. }
  710. else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  711. {
  712. param += "-mbd 2";
  713. }
  714. param += GetVideoBitrateParam(state, videoEncoder);
  715. var framerate = GetFramerateParam(state);
  716. if (framerate.HasValue)
  717. {
  718. param += string.Format(" -r {0}", framerate.Value.ToString(_usCulture));
  719. }
  720. var targetVideoCodec = state.ActualOutputVideoCodec;
  721. var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault();
  722. // vaapi does not support Baseline profile, force Constrained Baseline in this case,
  723. // which is compatible (and ugly)
  724. if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  725. && profile != null
  726. && profile.IndexOf("baseline", StringComparison.OrdinalIgnoreCase) != -1)
  727. {
  728. profile = "constrained_baseline";
  729. }
  730. if (!string.IsNullOrEmpty(profile))
  731. {
  732. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  733. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  734. {
  735. // not supported by h264_omx
  736. param += " -profile:v " + profile;
  737. }
  738. }
  739. var level = state.GetRequestedLevel(targetVideoCodec);
  740. if (!string.IsNullOrEmpty(level))
  741. {
  742. level = NormalizeTranscodingLevel(state.OutputVideoCodec, level);
  743. // h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
  744. // also needed for libx264 due to https://trac.ffmpeg.org/ticket/3307
  745. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  746. || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  747. || string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  748. {
  749. switch (level)
  750. {
  751. case "30":
  752. param += " -level 3.0";
  753. break;
  754. case "31":
  755. param += " -level 3.1";
  756. break;
  757. case "32":
  758. param += " -level 3.2";
  759. break;
  760. case "40":
  761. param += " -level 4.0";
  762. break;
  763. case "41":
  764. param += " -level 4.1";
  765. break;
  766. case "42":
  767. param += " -level 4.2";
  768. break;
  769. case "50":
  770. param += " -level 5.0";
  771. break;
  772. case "51":
  773. param += " -level 5.1";
  774. break;
  775. case "52":
  776. param += " -level 5.2";
  777. break;
  778. default:
  779. param += " -level " + level;
  780. break;
  781. }
  782. }
  783. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  784. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
  785. {
  786. // nvenc doesn't decode with param -level set ?!
  787. // TODO:
  788. }
  789. else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase))
  790. {
  791. param += " -level " + level;
  792. }
  793. }
  794. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  795. {
  796. param += " -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none";
  797. }
  798. if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  799. {
  800. // todo
  801. }
  802. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  803. && !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  804. && !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  805. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  806. {
  807. param = "-pix_fmt yuv420p " + param;
  808. }
  809. if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  810. {
  811. param = "-pix_fmt nv21 " + param;
  812. }
  813. return param;
  814. }
  815. public bool CanStreamCopyVideo(EncodingJobInfo state, MediaStream videoStream)
  816. {
  817. var request = state.BaseRequest;
  818. if (!request.AllowVideoStreamCopy)
  819. {
  820. return false;
  821. }
  822. if (videoStream.IsInterlaced
  823. && state.DeInterlace(videoStream.Codec, false))
  824. {
  825. return false;
  826. }
  827. if (videoStream.IsAnamorphic ?? false)
  828. {
  829. if (request.RequireNonAnamorphic)
  830. {
  831. return false;
  832. }
  833. }
  834. // Can't stream copy if we're burning in subtitles
  835. if (request.SubtitleStreamIndex.HasValue
  836. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  837. {
  838. return false;
  839. }
  840. if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
  841. && videoStream.IsAVC.HasValue
  842. && !videoStream.IsAVC.Value
  843. && request.RequireAvc)
  844. {
  845. return false;
  846. }
  847. // Source and target codecs must match
  848. if (string.IsNullOrEmpty(videoStream.Codec)
  849. || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
  850. {
  851. return false;
  852. }
  853. var requestedProfiles = state.GetRequestedProfiles(videoStream.Codec);
  854. // If client is requesting a specific video profile, it must match the source
  855. if (requestedProfiles.Length > 0)
  856. {
  857. if (string.IsNullOrEmpty(videoStream.Profile))
  858. {
  859. //return false;
  860. }
  861. var requestedProfile = requestedProfiles[0];
  862. // strip spaces because they may be stripped out on the query string as well
  863. if (!string.IsNullOrEmpty(videoStream.Profile) && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", ""), StringComparer.OrdinalIgnoreCase))
  864. {
  865. var currentScore = GetVideoProfileScore(videoStream.Profile);
  866. var requestedScore = GetVideoProfileScore(requestedProfile);
  867. if (currentScore == -1 || currentScore > requestedScore)
  868. {
  869. return false;
  870. }
  871. }
  872. }
  873. // Video width must fall within requested value
  874. if (request.MaxWidth.HasValue
  875. && (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value))
  876. {
  877. return false;
  878. }
  879. // Video height must fall within requested value
  880. if (request.MaxHeight.HasValue
  881. && (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value))
  882. {
  883. return false;
  884. }
  885. // Video framerate must fall within requested value
  886. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  887. if (requestedFramerate.HasValue)
  888. {
  889. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  890. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  891. {
  892. return false;
  893. }
  894. }
  895. // Video bitrate must fall within requested value
  896. if (request.VideoBitRate.HasValue
  897. && (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value))
  898. {
  899. return false;
  900. }
  901. var maxBitDepth = state.GetRequestedVideoBitDepth(videoStream.Codec);
  902. if (maxBitDepth.HasValue)
  903. {
  904. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > maxBitDepth.Value)
  905. {
  906. return false;
  907. }
  908. }
  909. var maxRefFrames = state.GetRequestedMaxRefFrames(videoStream.Codec);
  910. if (maxRefFrames.HasValue
  911. && videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > maxRefFrames.Value)
  912. {
  913. return false;
  914. }
  915. // If a specific level was requested, the source must match or be less than
  916. var level = state.GetRequestedLevel(videoStream.Codec);
  917. if (!string.IsNullOrEmpty(level)
  918. && double.TryParse(level, NumberStyles.Any, _usCulture, out var requestLevel))
  919. {
  920. if (!videoStream.Level.HasValue)
  921. {
  922. //return false;
  923. }
  924. if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
  925. {
  926. return false;
  927. }
  928. }
  929. if (string.Equals(state.InputContainer, "avi", StringComparison.OrdinalIgnoreCase)
  930. && string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase)
  931. && !(videoStream.IsAVC ?? false))
  932. {
  933. // see Coach S01E01 - Kelly and the Professor(0).avi
  934. return false;
  935. }
  936. return request.EnableAutoStreamCopy;
  937. }
  938. public bool CanStreamCopyAudio(EncodingJobInfo state, MediaStream audioStream, IEnumerable<string> supportedAudioCodecs)
  939. {
  940. var request = state.BaseRequest;
  941. if (!request.AllowAudioStreamCopy)
  942. {
  943. return false;
  944. }
  945. var maxBitDepth = state.GetRequestedAudioBitDepth(audioStream.Codec);
  946. if (maxBitDepth.HasValue
  947. && audioStream.BitDepth.HasValue
  948. && audioStream.BitDepth.Value > maxBitDepth.Value)
  949. {
  950. return false;
  951. }
  952. // Source and target codecs must match
  953. if (string.IsNullOrEmpty(audioStream.Codec)
  954. || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  955. {
  956. return false;
  957. }
  958. // Channels must fall within requested value
  959. var channels = state.GetRequestedAudioChannels(audioStream.Codec);
  960. if (channels.HasValue)
  961. {
  962. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  963. {
  964. return false;
  965. }
  966. if (audioStream.Channels.Value > channels.Value)
  967. {
  968. return false;
  969. }
  970. }
  971. // Sample rate must fall within requested value
  972. if (request.AudioSampleRate.HasValue)
  973. {
  974. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  975. {
  976. return false;
  977. }
  978. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  979. {
  980. return false;
  981. }
  982. }
  983. // Video bitrate must fall within requested value
  984. if (request.AudioBitRate.HasValue)
  985. {
  986. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  987. {
  988. return false;
  989. }
  990. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  991. {
  992. return false;
  993. }
  994. }
  995. return request.EnableAutoStreamCopy;
  996. }
  997. public int? GetVideoBitrateParamValue(BaseEncodingJobOptions request, MediaStream videoStream, string outputVideoCodec)
  998. {
  999. var bitrate = request.VideoBitRate;
  1000. if (videoStream != null)
  1001. {
  1002. var isUpscaling = request.Height.HasValue
  1003. && videoStream.Height.HasValue
  1004. && request.Height.Value > videoStream.Height.Value
  1005. && request.Width.HasValue
  1006. && videoStream.Width.HasValue
  1007. && request.Width.Value > videoStream.Width.Value;
  1008. // Don't allow bitrate increases unless upscaling
  1009. if (!isUpscaling && bitrate.HasValue && videoStream.BitRate.HasValue)
  1010. {
  1011. bitrate = GetMinBitrate(videoStream.BitRate.Value, bitrate.Value);
  1012. }
  1013. if (bitrate.HasValue)
  1014. {
  1015. var inputVideoCodec = videoStream.Codec;
  1016. bitrate = ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec);
  1017. // If a max bitrate was requested, don't let the scaled bitrate exceed it
  1018. if (request.VideoBitRate.HasValue)
  1019. {
  1020. bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value);
  1021. }
  1022. }
  1023. }
  1024. return bitrate;
  1025. }
  1026. private int GetMinBitrate(int sourceBitrate, int requestedBitrate)
  1027. {
  1028. // these values were chosen from testing to improve low bitrate streams
  1029. if (sourceBitrate <= 2000000)
  1030. {
  1031. sourceBitrate = Convert.ToInt32(sourceBitrate * 2.5);
  1032. }
  1033. else if (sourceBitrate <= 3000000)
  1034. {
  1035. sourceBitrate *= 2;
  1036. }
  1037. var bitrate = Math.Min(sourceBitrate, requestedBitrate);
  1038. return bitrate;
  1039. }
  1040. private static double GetVideoBitrateScaleFactor(string codec)
  1041. {
  1042. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  1043. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  1044. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  1045. {
  1046. return .5;
  1047. }
  1048. return 1;
  1049. }
  1050. private static int ScaleBitrate(int bitrate, string inputVideoCodec, string outputVideoCodec)
  1051. {
  1052. var inputScaleFactor = GetVideoBitrateScaleFactor(inputVideoCodec);
  1053. var outputScaleFactor = GetVideoBitrateScaleFactor(outputVideoCodec);
  1054. var scaleFactor = outputScaleFactor / inputScaleFactor;
  1055. if (bitrate <= 500000)
  1056. {
  1057. scaleFactor = Math.Max(scaleFactor, 4);
  1058. }
  1059. else if (bitrate <= 1000000)
  1060. {
  1061. scaleFactor = Math.Max(scaleFactor, 3);
  1062. }
  1063. else if (bitrate <= 2000000)
  1064. {
  1065. scaleFactor = Math.Max(scaleFactor, 2.5);
  1066. }
  1067. else if (bitrate <= 3000000)
  1068. {
  1069. scaleFactor = Math.Max(scaleFactor, 2);
  1070. }
  1071. return Convert.ToInt32(scaleFactor * bitrate);
  1072. }
  1073. public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream)
  1074. {
  1075. if (request.AudioBitRate.HasValue)
  1076. {
  1077. // Don't encode any higher than this
  1078. return Math.Min(384000, request.AudioBitRate.Value);
  1079. }
  1080. return null;
  1081. }
  1082. public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions, bool isHls)
  1083. {
  1084. var channels = state.OutputAudioChannels;
  1085. var filters = new List<string>();
  1086. // Boost volume to 200% when downsampling from 6ch to 2ch
  1087. if (channels.HasValue
  1088. && channels.Value <= 2
  1089. && state.AudioStream != null
  1090. && state.AudioStream.Channels.HasValue
  1091. && state.AudioStream.Channels.Value > 5
  1092. && !encodingOptions.DownMixAudioBoost.Equals(1))
  1093. {
  1094. filters.Add("volume=" + encodingOptions.DownMixAudioBoost.ToString(_usCulture));
  1095. }
  1096. var isCopyingTimestamps = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive;
  1097. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode && !isCopyingTimestamps)
  1098. {
  1099. var seconds = TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds;
  1100. filters.Add(
  1101. string.Format(
  1102. CultureInfo.InvariantCulture,
  1103. "asetpts=PTS-{0}/TB",
  1104. Math.Round(seconds)));
  1105. }
  1106. if (filters.Count > 0)
  1107. {
  1108. return "-af \"" + string.Join(",", filters) + "\"";
  1109. }
  1110. return string.Empty;
  1111. }
  1112. /// <summary>
  1113. /// Gets the number of audio channels to specify on the command line
  1114. /// </summary>
  1115. /// <param name="state">The state.</param>
  1116. /// <param name="audioStream">The audio stream.</param>
  1117. /// <param name="outputAudioCodec">The output audio codec.</param>
  1118. /// <returns>System.Nullable{System.Int32}.</returns>
  1119. public int? GetNumAudioChannelsParam(EncodingJobInfo state, MediaStream audioStream, string outputAudioCodec)
  1120. {
  1121. var request = state.BaseRequest;
  1122. var inputChannels = audioStream?.Channels;
  1123. if (inputChannels <= 0)
  1124. {
  1125. inputChannels = null;
  1126. }
  1127. var codec = outputAudioCodec ?? string.Empty;
  1128. int? transcoderChannelLimit;
  1129. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  1130. {
  1131. // wmav2 currently only supports two channel output
  1132. transcoderChannelLimit = 2;
  1133. }
  1134. else if (codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  1135. {
  1136. // libmp3lame currently only supports two channel output
  1137. transcoderChannelLimit = 2;
  1138. }
  1139. else
  1140. {
  1141. // If we don't have any media info then limit it to 6 to prevent encoding errors due to asking for too many channels
  1142. transcoderChannelLimit = 6;
  1143. }
  1144. var isTranscodingAudio = !string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase);
  1145. int? resultChannels = state.GetRequestedAudioChannels(codec);
  1146. if (isTranscodingAudio)
  1147. {
  1148. resultChannels = GetMinValue(request.TranscodingMaxAudioChannels, resultChannels);
  1149. }
  1150. if (inputChannels.HasValue)
  1151. {
  1152. resultChannels = resultChannels.HasValue
  1153. ? Math.Min(resultChannels.Value, inputChannels.Value)
  1154. : inputChannels.Value;
  1155. }
  1156. if (isTranscodingAudio && transcoderChannelLimit.HasValue)
  1157. {
  1158. resultChannels = resultChannels.HasValue
  1159. ? Math.Min(resultChannels.Value, transcoderChannelLimit.Value)
  1160. : transcoderChannelLimit.Value;
  1161. }
  1162. return resultChannels;
  1163. }
  1164. private int? GetMinValue(int? val1, int? val2)
  1165. {
  1166. if (!val1.HasValue)
  1167. {
  1168. return val2;
  1169. }
  1170. if (!val2.HasValue)
  1171. {
  1172. return val1;
  1173. }
  1174. return Math.Min(val1.Value, val2.Value);
  1175. }
  1176. /// <summary>
  1177. /// Enforces the resolution limit.
  1178. /// </summary>
  1179. /// <param name="state">The state.</param>
  1180. public void EnforceResolutionLimit(EncodingJobInfo state)
  1181. {
  1182. var videoRequest = state.BaseRequest;
  1183. // Switch the incoming params to be ceilings rather than fixed values
  1184. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1185. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1186. videoRequest.Width = null;
  1187. videoRequest.Height = null;
  1188. }
  1189. /// <summary>
  1190. /// Gets the fast seek command line parameter.
  1191. /// </summary>
  1192. /// <param name="request">The request.</param>
  1193. /// <returns>System.String.</returns>
  1194. /// <value>The fast seek command line parameter.</value>
  1195. public string GetFastSeekCommandLineParameter(BaseEncodingJobOptions request)
  1196. {
  1197. var time = request.StartTimeTicks ?? 0;
  1198. if (time > 0)
  1199. {
  1200. return string.Format("-ss {0}", _mediaEncoder.GetTimeParameter(time));
  1201. }
  1202. return string.Empty;
  1203. }
  1204. /// <summary>
  1205. /// Gets the map args.
  1206. /// </summary>
  1207. /// <param name="state">The state.</param>
  1208. /// <returns>System.String.</returns>
  1209. public string GetMapArgs(EncodingJobInfo state)
  1210. {
  1211. // If we don't have known media info
  1212. // If input is video, use -sn to drop subtitles
  1213. // Otherwise just return empty
  1214. if (state.VideoStream == null && state.AudioStream == null)
  1215. {
  1216. return state.IsInputVideo ? "-sn" : string.Empty;
  1217. }
  1218. // We have media info, but we don't know the stream indexes
  1219. if (state.VideoStream != null && state.VideoStream.Index == -1)
  1220. {
  1221. return "-sn";
  1222. }
  1223. // We have media info, but we don't know the stream indexes
  1224. if (state.AudioStream != null && state.AudioStream.Index == -1)
  1225. {
  1226. return state.IsInputVideo ? "-sn" : string.Empty;
  1227. }
  1228. var args = string.Empty;
  1229. if (state.VideoStream != null)
  1230. {
  1231. args += string.Format(
  1232. CultureInfo.InvariantCulture,
  1233. "-map 0:{0}",
  1234. state.VideoStream.Index);
  1235. }
  1236. else
  1237. {
  1238. // No known video stream
  1239. args += "-vn";
  1240. }
  1241. if (state.AudioStream != null)
  1242. {
  1243. args += string.Format(
  1244. CultureInfo.InvariantCulture,
  1245. " -map 0:{0}",
  1246. state.AudioStream.Index);
  1247. }
  1248. else
  1249. {
  1250. args += " -map -0:a";
  1251. }
  1252. var subtitleMethod = state.SubtitleDeliveryMethod;
  1253. if (state.SubtitleStream == null || subtitleMethod == SubtitleDeliveryMethod.Hls)
  1254. {
  1255. args += " -map -0:s";
  1256. }
  1257. else if (subtitleMethod == SubtitleDeliveryMethod.Embed)
  1258. {
  1259. args += string.Format(
  1260. CultureInfo.InvariantCulture,
  1261. " -map 0:{0}",
  1262. state.SubtitleStream.Index);
  1263. }
  1264. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  1265. {
  1266. args += " -map 1:0 -sn";
  1267. }
  1268. return args;
  1269. }
  1270. /// <summary>
  1271. /// Determines which stream will be used for playback
  1272. /// </summary>
  1273. /// <param name="allStream">All stream.</param>
  1274. /// <param name="desiredIndex">Index of the desired.</param>
  1275. /// <param name="type">The type.</param>
  1276. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  1277. /// <returns>MediaStream.</returns>
  1278. public MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  1279. {
  1280. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  1281. if (desiredIndex.HasValue)
  1282. {
  1283. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  1284. if (stream != null)
  1285. {
  1286. return stream;
  1287. }
  1288. }
  1289. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  1290. {
  1291. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  1292. streams.FirstOrDefault();
  1293. }
  1294. // Just return the first one
  1295. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  1296. }
  1297. /// <summary>
  1298. /// Gets the graphical subtitle param.
  1299. /// </summary>
  1300. public string GetGraphicalSubtitleParam(
  1301. EncodingJobInfo state,
  1302. EncodingOptions options,
  1303. string outputVideoCodec)
  1304. {
  1305. var outputSizeParam = string.Empty;
  1306. var request = state.BaseRequest;
  1307. // Add resolution params, if specified
  1308. if (request.Width.HasValue
  1309. || request.Height.HasValue
  1310. || request.MaxHeight.HasValue
  1311. || request.MaxWidth.HasValue)
  1312. {
  1313. outputSizeParam = GetOutputSizeParam(state, options, outputVideoCodec).TrimEnd('"');
  1314. var index = outputSizeParam.IndexOf("hwdownload", StringComparison.OrdinalIgnoreCase);
  1315. if (index != -1)
  1316. {
  1317. outputSizeParam = "," + outputSizeParam.Substring(index);
  1318. }
  1319. else
  1320. {
  1321. index = outputSizeParam.IndexOf("format", StringComparison.OrdinalIgnoreCase);
  1322. if (index != -1)
  1323. {
  1324. outputSizeParam = "," + outputSizeParam.Substring(index);
  1325. }
  1326. else
  1327. {
  1328. index = outputSizeParam.IndexOf("yadif", StringComparison.OrdinalIgnoreCase);
  1329. if (index != -1)
  1330. {
  1331. outputSizeParam = "," + outputSizeParam.Substring(index);
  1332. }
  1333. else
  1334. {
  1335. index = outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase);
  1336. if (index != -1)
  1337. {
  1338. outputSizeParam = "," + outputSizeParam.Substring(index);
  1339. }
  1340. }
  1341. }
  1342. }
  1343. }
  1344. var videoSizeParam = string.Empty;
  1345. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options);
  1346. // Setup subtitle scaling
  1347. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  1348. {
  1349. videoSizeParam = string.Format(
  1350. CultureInfo.InvariantCulture,
  1351. "scale={0}:{1}",
  1352. state.VideoStream.Width.Value,
  1353. state.VideoStream.Height.Value);
  1354. // For QSV, feed it into hardware encoder now
  1355. if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1356. {
  1357. videoSizeParam += ",hwupload=extra_hw_frames=64";
  1358. }
  1359. // For VAAPI and CUVID decoder
  1360. // these encoders cannot automatically adjust the size of graphical subtitles to fit the output video,
  1361. // thus needs to be manually adjusted.
  1362. if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1
  1363. || (IsVaapiSupported(state) && string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)
  1364. && ((videoDecoder ?? string.Empty).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1
  1365. || (outputVideoCodec ?? string.Empty).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1)))
  1366. {
  1367. var videoStream = state.VideoStream;
  1368. var inputWidth = videoStream?.Width;
  1369. var inputHeight = videoStream?.Height;
  1370. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  1371. if (width.HasValue && height.HasValue)
  1372. {
  1373. videoSizeParam = string.Format(
  1374. CultureInfo.InvariantCulture,
  1375. "scale={0}:{1}",
  1376. width.Value,
  1377. height.Value);
  1378. }
  1379. }
  1380. }
  1381. var mapPrefix = state.SubtitleStream.IsExternal ?
  1382. 1 :
  1383. 0;
  1384. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  1385. ? 0
  1386. : state.SubtitleStream.Index;
  1387. // Setup default filtergraph utilizing FFMpeg overlay() and FFMpeg scale() (see the return of this function for index reference)
  1388. var retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay{3}\"";
  1389. // When the input may or may not be hardware VAAPI decodable
  1390. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1391. {
  1392. /*
  1393. [base]: HW scaling video to OutputSize
  1394. [sub]: SW scaling subtitle to FixedOutputSize
  1395. [base][sub]: SW overlay
  1396. */
  1397. outputSizeParam = outputSizeParam.TrimStart(',');
  1398. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload[base];[base][sub]overlay,format=nv12,hwupload\"";
  1399. }
  1400. // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first
  1401. else if (IsVaapiSupported(state) && (videoDecoder ?? string.Empty).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1
  1402. && string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  1403. {
  1404. /*
  1405. [base]: SW scaling video to OutputSize
  1406. [sub]: SW scaling subtitle to FixedOutputSize
  1407. [base][sub]: SW overlay
  1408. */
  1409. outputSizeParam = outputSizeParam.TrimStart(',');
  1410. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"";
  1411. }
  1412. else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1413. {
  1414. /*
  1415. QSV in FFMpeg can now setup hardware overlay for transcodes.
  1416. For software decoding and hardware encoding option, frames must be hwuploaded into hardware
  1417. with fixed frame size.
  1418. */
  1419. if ((videoDecoder ?? string.Empty).IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1)
  1420. {
  1421. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay_qsv=x=(W-w)/2:y=(H-h)/2{3}\"";
  1422. }
  1423. else
  1424. {
  1425. 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}\"";
  1426. }
  1427. }
  1428. return string.Format(
  1429. CultureInfo.InvariantCulture,
  1430. retStr,
  1431. mapPrefix,
  1432. subtitleStreamIndex,
  1433. state.VideoStream.Index,
  1434. outputSizeParam,
  1435. videoSizeParam);
  1436. }
  1437. private (int? width, int? height) GetFixedOutputSize(
  1438. int? videoWidth,
  1439. int? videoHeight,
  1440. int? requestedWidth,
  1441. int? requestedHeight,
  1442. int? requestedMaxWidth,
  1443. int? requestedMaxHeight)
  1444. {
  1445. if (!videoWidth.HasValue && !requestedWidth.HasValue)
  1446. {
  1447. return (null, null);
  1448. }
  1449. if (!videoHeight.HasValue && !requestedHeight.HasValue)
  1450. {
  1451. return (null, null);
  1452. }
  1453. decimal inputWidth = Convert.ToDecimal(videoWidth ?? requestedWidth);
  1454. decimal inputHeight = Convert.ToDecimal(videoHeight ?? requestedHeight);
  1455. decimal outputWidth = requestedWidth.HasValue ? Convert.ToDecimal(requestedWidth.Value) : inputWidth;
  1456. decimal outputHeight = requestedHeight.HasValue ? Convert.ToDecimal(requestedHeight.Value) : inputHeight;
  1457. decimal maximumWidth = requestedMaxWidth.HasValue ? Convert.ToDecimal(requestedMaxWidth.Value) : outputWidth;
  1458. decimal maximumHeight = requestedMaxHeight.HasValue ? Convert.ToDecimal(requestedMaxHeight.Value) : outputHeight;
  1459. if (outputWidth > maximumWidth || outputHeight > maximumHeight)
  1460. {
  1461. var scale = Math.Min(maximumWidth / outputWidth, maximumHeight / outputHeight);
  1462. outputWidth = Math.Min(maximumWidth, Math.Truncate(outputWidth * scale));
  1463. outputHeight = Math.Min(maximumHeight, Math.Truncate(outputHeight * scale));
  1464. }
  1465. outputWidth = 2 * Math.Truncate(outputWidth / 2);
  1466. outputHeight = 2 * Math.Truncate(outputHeight / 2);
  1467. return (Convert.ToInt32(outputWidth), Convert.ToInt32(outputHeight));
  1468. }
  1469. public List<string> GetScalingFilters(EncodingJobInfo state,
  1470. int? videoWidth,
  1471. int? videoHeight,
  1472. Video3DFormat? threedFormat,
  1473. string videoDecoder,
  1474. string videoEncoder,
  1475. int? requestedWidth,
  1476. int? requestedHeight,
  1477. int? requestedMaxWidth,
  1478. int? requestedMaxHeight)
  1479. {
  1480. var filters = new List<string>();
  1481. var (width, height) = GetFixedOutputSize(
  1482. videoWidth,
  1483. videoHeight,
  1484. requestedWidth,
  1485. requestedHeight,
  1486. requestedMaxWidth,
  1487. requestedMaxHeight);
  1488. var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  1489. if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) || (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);
  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 ?? string.Empty).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.Policy.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.Policy.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 || string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  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 (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  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.EnableDecodingColorDepth10) ? 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.EnableDecodingColorDepth10) ? 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. return (isColorDepth10 &&
  2239. !encodingOptions.EnableDecodingColorDepth10) ? null : "-c:v h264_cuvid";
  2240. }
  2241. break;
  2242. case "hevc":
  2243. case "h265":
  2244. if (_mediaEncoder.SupportsDecoder("hevc_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
  2245. {
  2246. return (isColorDepth10 &&
  2247. !encodingOptions.EnableDecodingColorDepth10) ? null : "-c:v hevc_cuvid";
  2248. }
  2249. break;
  2250. case "mpeg2video":
  2251. if (_mediaEncoder.SupportsDecoder("mpeg2_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2252. {
  2253. return "-c:v mpeg2_cuvid";
  2254. }
  2255. break;
  2256. case "vc1":
  2257. if (_mediaEncoder.SupportsDecoder("vc1_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2258. {
  2259. return "-c:v vc1_cuvid";
  2260. }
  2261. break;
  2262. case "mpeg4":
  2263. if (_mediaEncoder.SupportsDecoder("mpeg4_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2264. {
  2265. return "-c:v mpeg4_cuvid";
  2266. }
  2267. break;
  2268. case "vp8":
  2269. if (_mediaEncoder.SupportsDecoder("vp8_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase))
  2270. {
  2271. return "-c:v vp8_cuvid";
  2272. }
  2273. break;
  2274. case "vp9":
  2275. if (_mediaEncoder.SupportsDecoder("vp9_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
  2276. {
  2277. return (isColorDepth10 &&
  2278. !encodingOptions.EnableDecodingColorDepth10) ? null : "-c:v vp9_cuvid";
  2279. }
  2280. break;
  2281. }
  2282. }
  2283. else if (string.Equals(encodingOptions.HardwareAccelerationType, "mediacodec", StringComparison.OrdinalIgnoreCase))
  2284. {
  2285. switch (videoStream.Codec.ToLowerInvariant())
  2286. {
  2287. case "avc":
  2288. case "h264":
  2289. if (_mediaEncoder.SupportsDecoder("h264_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2290. {
  2291. return "-c:v h264_mediacodec";
  2292. }
  2293. break;
  2294. case "hevc":
  2295. case "h265":
  2296. if (_mediaEncoder.SupportsDecoder("hevc_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
  2297. {
  2298. return (isColorDepth10 &&
  2299. !encodingOptions.EnableDecodingColorDepth10) ? null : "-c:v hevc_mediacodec";
  2300. }
  2301. break;
  2302. case "mpeg2video":
  2303. if (_mediaEncoder.SupportsDecoder("mpeg2_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2304. {
  2305. return "-c:v mpeg2_mediacodec";
  2306. }
  2307. break;
  2308. case "mpeg4":
  2309. if (_mediaEncoder.SupportsDecoder("mpeg4_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2310. {
  2311. return "-c:v mpeg4_mediacodec";
  2312. }
  2313. break;
  2314. case "vp8":
  2315. if (_mediaEncoder.SupportsDecoder("vp8_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase))
  2316. {
  2317. return "-c:v vp8_mediacodec";
  2318. }
  2319. break;
  2320. case "vp9":
  2321. if (_mediaEncoder.SupportsDecoder("vp9_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
  2322. {
  2323. return (isColorDepth10 &&
  2324. !encodingOptions.EnableDecodingColorDepth10) ? null : "-c:v vp9_mediacodec";
  2325. }
  2326. break;
  2327. }
  2328. }
  2329. else if (string.Equals(encodingOptions.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase))
  2330. {
  2331. switch (videoStream.Codec.ToLowerInvariant())
  2332. {
  2333. case "avc":
  2334. case "h264":
  2335. if (_mediaEncoder.SupportsDecoder("h264_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2336. {
  2337. return "-c:v h264_mmal";
  2338. }
  2339. break;
  2340. case "mpeg2video":
  2341. if (_mediaEncoder.SupportsDecoder("mpeg2_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2342. {
  2343. return "-c:v mpeg2_mmal";
  2344. }
  2345. break;
  2346. case "mpeg4":
  2347. if (_mediaEncoder.SupportsDecoder("mpeg4_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2348. {
  2349. return "-c:v mpeg4_mmal";
  2350. }
  2351. break;
  2352. case "vc1":
  2353. if (_mediaEncoder.SupportsDecoder("vc1_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2354. {
  2355. return "-c:v vc1_mmal";
  2356. }
  2357. break;
  2358. }
  2359. }
  2360. else if (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  2361. {
  2362. switch (videoStream.Codec.ToLowerInvariant())
  2363. {
  2364. case "avc":
  2365. case "h264":
  2366. return GetHwaccelType(state, encodingOptions, "h264");
  2367. case "hevc":
  2368. case "h265":
  2369. if (isColorDepth10)
  2370. {
  2371. if (encodingOptions.EnableDecodingColorDepth10)
  2372. {
  2373. return GetHwaccelType(state, encodingOptions, "hevc");
  2374. }
  2375. return null;
  2376. }
  2377. return GetHwaccelType(state, encodingOptions, "hevc");
  2378. case "mpeg2video":
  2379. return GetHwaccelType(state, encodingOptions, "mpeg2video");
  2380. case "vc1":
  2381. return GetHwaccelType(state, encodingOptions, "vc1");
  2382. case "mpeg4":
  2383. return GetHwaccelType(state, encodingOptions, "mpeg4");
  2384. case "vp9":
  2385. if (isColorDepth10)
  2386. {
  2387. if (encodingOptions.EnableDecodingColorDepth10)
  2388. {
  2389. return GetHwaccelType(state, encodingOptions, "vp9");
  2390. }
  2391. return null;
  2392. }
  2393. return GetHwaccelType(state, encodingOptions, "vp9");
  2394. }
  2395. }
  2396. else if (string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  2397. {
  2398. switch (videoStream.Codec.ToLowerInvariant())
  2399. {
  2400. case "avc":
  2401. case "h264":
  2402. return GetHwaccelType(state, encodingOptions, "h264");
  2403. case "hevc":
  2404. case "h265":
  2405. if (isColorDepth10)
  2406. {
  2407. if (encodingOptions.EnableDecodingColorDepth10)
  2408. {
  2409. return GetHwaccelType(state, encodingOptions, "hevc");
  2410. }
  2411. return null;
  2412. }
  2413. return GetHwaccelType(state, encodingOptions, "hevc");
  2414. case "mpeg2video":
  2415. return GetHwaccelType(state, encodingOptions, "mpeg2video");
  2416. case "vc1":
  2417. return GetHwaccelType(state, encodingOptions, "vc1");
  2418. case "vp8":
  2419. return GetHwaccelType(state, encodingOptions, "vp8");
  2420. case "vp9":
  2421. if (isColorDepth10)
  2422. {
  2423. if (encodingOptions.EnableDecodingColorDepth10)
  2424. {
  2425. return GetHwaccelType(state, encodingOptions, "vp9");
  2426. }
  2427. return null;
  2428. }
  2429. return GetHwaccelType(state, encodingOptions, "vp9");
  2430. }
  2431. }
  2432. else if (string.Equals(encodingOptions.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  2433. {
  2434. switch (videoStream.Codec.ToLowerInvariant())
  2435. {
  2436. case "avc":
  2437. case "h264":
  2438. if (_mediaEncoder.SupportsDecoder("h264_videotoolbox") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2439. {
  2440. return "-c:v h264_videotoolbox";
  2441. }
  2442. break;
  2443. case "mpeg2video":
  2444. if (_mediaEncoder.SupportsDecoder("mpeg2_videotoolbox") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2445. {
  2446. return "-c:v mpeg2_videotoolbox";
  2447. }
  2448. break;
  2449. case "mpeg4":
  2450. if (_mediaEncoder.SupportsDecoder("mpeg4_videotoolbox") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2451. {
  2452. return "-c:v mpeg4_videotoolbox";
  2453. }
  2454. break;
  2455. case "vc1":
  2456. if (_mediaEncoder.SupportsDecoder("vc1_videotoolbox") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2457. {
  2458. return "-c:v vc1_videotoolbox";
  2459. }
  2460. break;
  2461. }
  2462. }
  2463. }
  2464. var whichCodec = videoStream.Codec.ToLowerInvariant();
  2465. switch (whichCodec)
  2466. {
  2467. case "avc":
  2468. whichCodec = "h264";
  2469. break;
  2470. case "h265":
  2471. whichCodec = "hevc";
  2472. break;
  2473. }
  2474. // Avoid a second attempt if no hardware acceleration is being used
  2475. encodingOptions.HardwareDecodingCodecs = encodingOptions.HardwareDecodingCodecs.Where(val => val != whichCodec).ToArray();
  2476. // leave blank so ffmpeg will decide
  2477. return null;
  2478. }
  2479. /// <summary>
  2480. /// Gets a hwaccel type to use as a hardware decoder(dxva/vaapi) depending on the system
  2481. /// </summary>
  2482. public string GetHwaccelType(EncodingJobInfo state, EncodingOptions options, string videoCodec)
  2483. {
  2484. var IsWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;
  2485. var IsNewWindows = Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1);
  2486. var IsDxvaSupported = _mediaEncoder.SupportsHwaccel("dxva2") || _mediaEncoder.SupportsHwaccel("d3d11va");
  2487. if ((IsDxvaSupported || IsVaapiSupported(state)) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  2488. {
  2489. if (!IsWindows)
  2490. {
  2491. return "-hwaccel vaapi";
  2492. }
  2493. else if (IsWindows && IsNewWindows)
  2494. {
  2495. return "-hwaccel d3d11va";
  2496. }
  2497. else if (IsWindows && !IsNewWindows)
  2498. {
  2499. return "-hwaccel dxva2";
  2500. }
  2501. }
  2502. return null;
  2503. }
  2504. public string GetSubtitleEmbedArguments(EncodingJobInfo state)
  2505. {
  2506. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  2507. {
  2508. return string.Empty;
  2509. }
  2510. var format = state.SupportedSubtitleCodecs.FirstOrDefault();
  2511. string codec;
  2512. if (string.IsNullOrEmpty(format) || string.Equals(format, state.SubtitleStream.Codec, StringComparison.OrdinalIgnoreCase))
  2513. {
  2514. codec = "copy";
  2515. }
  2516. else
  2517. {
  2518. codec = format;
  2519. }
  2520. return " -codec:s:0 " + codec + " -disposition:s:0 default";
  2521. }
  2522. public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath, string defaultPreset)
  2523. {
  2524. // Get the output codec name
  2525. var videoCodec = GetVideoEncoder(state, encodingOptions);
  2526. var format = string.Empty;
  2527. var keyFrame = string.Empty;
  2528. if (string.Equals(Path.GetExtension(outputPath), ".mp4", StringComparison.OrdinalIgnoreCase)
  2529. && state.BaseRequest.Context == EncodingContext.Streaming)
  2530. {
  2531. // Comparison: https://github.com/jansmolders86/mediacenterjs/blob/master/lib/transcoding/desktop.js
  2532. format = " -f mp4 -movflags frag_keyframe+empty_moov";
  2533. }
  2534. var threads = GetNumberOfThreads(state, encodingOptions, videoCodec);
  2535. var inputModifier = GetInputModifier(state, encodingOptions);
  2536. return string.Format(
  2537. CultureInfo.InvariantCulture,
  2538. "{0} {1}{2} {3} {4} -map_metadata -1 -map_chapters -1 -threads {5} {6}{7}{8} -y \"{9}\"",
  2539. inputModifier,
  2540. GetInputArgument(state, encodingOptions),
  2541. keyFrame,
  2542. GetMapArgs(state),
  2543. GetProgressiveVideoArguments(state, encodingOptions, videoCodec, defaultPreset),
  2544. threads,
  2545. GetProgressiveVideoAudioArguments(state, encodingOptions),
  2546. GetSubtitleEmbedArguments(state),
  2547. format,
  2548. outputPath).Trim();
  2549. }
  2550. public string GetOutputFFlags(EncodingJobInfo state)
  2551. {
  2552. var flags = new List<string>();
  2553. if (state.GenPtsOutput)
  2554. {
  2555. flags.Add("+genpts");
  2556. }
  2557. if (flags.Count > 0)
  2558. {
  2559. return " -fflags " + string.Join("", flags);
  2560. }
  2561. return string.Empty;
  2562. }
  2563. public string GetProgressiveVideoArguments(EncodingJobInfo state, EncodingOptions encodingOptions, string videoCodec, string defaultPreset)
  2564. {
  2565. var args = "-codec:v:0 " + videoCodec;
  2566. if (state.BaseRequest.EnableMpegtsM2TsMode)
  2567. {
  2568. args += " -mpegts_m2ts_mode 1";
  2569. }
  2570. if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  2571. {
  2572. if (state.VideoStream != null
  2573. && string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase)
  2574. && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
  2575. {
  2576. string bitStreamArgs = GetBitStreamArgs(state.VideoStream);
  2577. if (!string.IsNullOrEmpty(bitStreamArgs))
  2578. {
  2579. args += " " + bitStreamArgs;
  2580. }
  2581. }
  2582. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  2583. {
  2584. args += " -copyts -avoid_negative_ts disabled -start_at_zero";
  2585. }
  2586. if (!state.RunTimeTicks.HasValue)
  2587. {
  2588. args += " -fflags +genpts";
  2589. }
  2590. }
  2591. else
  2592. {
  2593. var keyFrameArg = string.Format(
  2594. CultureInfo.InvariantCulture,
  2595. " -force_key_frames \"expr:gte(t,n_forced*{0})\"",
  2596. 5);
  2597. args += keyFrameArg;
  2598. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2599. var hasCopyTs = false;
  2600. // Add resolution params, if specified
  2601. if (!hasGraphicalSubs)
  2602. {
  2603. var outputSizeParam = GetOutputSizeParam(state, encodingOptions, videoCodec);
  2604. args += outputSizeParam;
  2605. hasCopyTs = outputSizeParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  2606. }
  2607. // This is for graphical subs
  2608. if (hasGraphicalSubs)
  2609. {
  2610. var graphicalSubtitleParam = GetGraphicalSubtitleParam(state, encodingOptions, videoCodec);
  2611. args += graphicalSubtitleParam;
  2612. hasCopyTs = graphicalSubtitleParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  2613. }
  2614. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  2615. {
  2616. if (!hasCopyTs)
  2617. {
  2618. args += " -copyts";
  2619. }
  2620. args += " -avoid_negative_ts disabled";
  2621. if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
  2622. {
  2623. args += " -start_at_zero";
  2624. }
  2625. }
  2626. var qualityParam = GetVideoQualityParam(state, videoCodec, encodingOptions, defaultPreset);
  2627. if (!string.IsNullOrEmpty(qualityParam))
  2628. {
  2629. args += " " + qualityParam.Trim();
  2630. }
  2631. }
  2632. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  2633. {
  2634. args += " -vsync " + state.OutputVideoSync;
  2635. }
  2636. args += GetOutputFFlags(state);
  2637. return args;
  2638. }
  2639. public string GetProgressiveVideoAudioArguments(EncodingJobInfo state, EncodingOptions encodingOptions)
  2640. {
  2641. // If the video doesn't have an audio stream, return a default.
  2642. if (state.AudioStream == null && state.VideoStream != null)
  2643. {
  2644. return string.Empty;
  2645. }
  2646. // Get the output codec name
  2647. var codec = GetAudioEncoder(state);
  2648. var args = "-codec:a:0 " + codec;
  2649. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  2650. {
  2651. return args;
  2652. }
  2653. // Add the number of audio channels
  2654. var channels = state.OutputAudioChannels;
  2655. if (channels.HasValue)
  2656. {
  2657. args += " -ac " + channels.Value;
  2658. }
  2659. var bitrate = state.OutputAudioBitrate;
  2660. if (bitrate.HasValue)
  2661. {
  2662. args += " -ab " + bitrate.Value.ToString(_usCulture);
  2663. }
  2664. if (state.OutputAudioSampleRate.HasValue)
  2665. {
  2666. args += " -ar " + state.OutputAudioSampleRate.Value.ToString(_usCulture);
  2667. }
  2668. args += " " + GetAudioFilterParam(state, encodingOptions, false);
  2669. return args;
  2670. }
  2671. public string GetProgressiveAudioFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath)
  2672. {
  2673. var audioTranscodeParams = new List<string>();
  2674. var bitrate = state.OutputAudioBitrate;
  2675. if (bitrate.HasValue)
  2676. {
  2677. audioTranscodeParams.Add("-ab " + bitrate.Value.ToString(_usCulture));
  2678. }
  2679. if (state.OutputAudioChannels.HasValue)
  2680. {
  2681. audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(_usCulture));
  2682. }
  2683. // opus will fail on 44100
  2684. if (!string.Equals(state.OutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase))
  2685. {
  2686. if (state.OutputAudioSampleRate.HasValue)
  2687. {
  2688. audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(_usCulture));
  2689. }
  2690. }
  2691. var threads = GetNumberOfThreads(state, encodingOptions, null);
  2692. var inputModifier = GetInputModifier(state, encodingOptions);
  2693. return string.Format(
  2694. CultureInfo.InvariantCulture,
  2695. "{0} {1}{7}{8} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1{6} -y \"{5}\"",
  2696. inputModifier,
  2697. GetInputArgument(state, encodingOptions),
  2698. threads,
  2699. " -vn",
  2700. string.Join(" ", audioTranscodeParams),
  2701. outputPath,
  2702. string.Empty,
  2703. string.Empty,
  2704. string.Empty).Trim();
  2705. }
  2706. }
  2707. }