EncodingHelper.cs 131 KB

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