EncodingHelper.cs 117 KB

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