EncodingHelper.cs 128 KB

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