EncodingHelper.cs 116 KB

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