EncodingHelper.cs 97 KB

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