EncodingHelper.cs 96 KB

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