EncodingHelper.cs 103 KB

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