EncodingHelper.cs 116 KB

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