EncodingHelper.cs 124 KB

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