EncodingHelper.cs 97 KB

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