EncodingHelper.cs 117 KB

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