EncodingHelper.cs 116 KB

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