nvenc.c 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146
  1. /*
  2. * H.264/HEVC/AV1 hardware encoding using nvidia nvenc
  3. * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #include "config_components.h"
  23. #include "nvenc.h"
  24. #include "hevc/sei.h"
  25. #if CONFIG_AV1_NVENC_ENCODER
  26. #include "av1.h"
  27. #endif
  28. #include "libavutil/hwcontext_cuda.h"
  29. #include "libavutil/hwcontext.h"
  30. #include "libavutil/cuda_check.h"
  31. #include "libavutil/imgutils.h"
  32. #include "libavutil/mem.h"
  33. #include "libavutil/pixdesc.h"
  34. #include "libavutil/mathematics.h"
  35. #include "libavutil/mastering_display_metadata.h"
  36. #include "atsc_a53.h"
  37. #include "codec_desc.h"
  38. #include "encode.h"
  39. #include "internal.h"
  40. #include "packet_internal.h"
  41. #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
  42. #define NVENC_CAP 0x30
  43. #ifndef NVENC_NO_DEPRECATED_RC
  44. #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
  45. rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
  46. rc == NV_ENC_PARAMS_RC_CBR_HQ)
  47. #else
  48. #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR)
  49. #endif
  50. const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
  51. AV_PIX_FMT_YUV420P,
  52. AV_PIX_FMT_NV12,
  53. AV_PIX_FMT_P010,
  54. AV_PIX_FMT_YUV444P,
  55. AV_PIX_FMT_P016, // Truncated to 10bits
  56. #ifdef NVENC_HAVE_422_SUPPORT
  57. AV_PIX_FMT_NV16,
  58. AV_PIX_FMT_P210,
  59. AV_PIX_FMT_P216,
  60. #endif
  61. AV_PIX_FMT_YUV444P16, // Truncated to 10bits
  62. AV_PIX_FMT_0RGB32,
  63. AV_PIX_FMT_RGB32,
  64. AV_PIX_FMT_0BGR32,
  65. AV_PIX_FMT_BGR32,
  66. AV_PIX_FMT_X2RGB10,
  67. AV_PIX_FMT_X2BGR10,
  68. AV_PIX_FMT_GBRP,
  69. AV_PIX_FMT_GBRP16, // Truncated to 10bits
  70. AV_PIX_FMT_CUDA,
  71. #if CONFIG_D3D11VA
  72. AV_PIX_FMT_D3D11,
  73. #endif
  74. AV_PIX_FMT_NONE
  75. };
  76. const AVCodecHWConfigInternal *const ff_nvenc_hw_configs[] = {
  77. HW_CONFIG_ENCODER_FRAMES(CUDA, CUDA),
  78. HW_CONFIG_ENCODER_DEVICE(NONE, CUDA),
  79. #if CONFIG_D3D11VA
  80. HW_CONFIG_ENCODER_FRAMES(D3D11, D3D11VA),
  81. HW_CONFIG_ENCODER_DEVICE(NONE, D3D11VA),
  82. #endif
  83. NULL,
  84. };
  85. #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
  86. pix_fmt == AV_PIX_FMT_P016 || \
  87. pix_fmt == AV_PIX_FMT_P210 || \
  88. pix_fmt == AV_PIX_FMT_P216 || \
  89. pix_fmt == AV_PIX_FMT_YUV444P16 || \
  90. pix_fmt == AV_PIX_FMT_X2RGB10 || \
  91. pix_fmt == AV_PIX_FMT_X2BGR10 || \
  92. pix_fmt == AV_PIX_FMT_GBRP16)
  93. #define IS_RGB(pix_fmt) (pix_fmt == AV_PIX_FMT_0RGB32 || \
  94. pix_fmt == AV_PIX_FMT_RGB32 || \
  95. pix_fmt == AV_PIX_FMT_0BGR32 || \
  96. pix_fmt == AV_PIX_FMT_BGR32 || \
  97. pix_fmt == AV_PIX_FMT_X2RGB10 || \
  98. pix_fmt == AV_PIX_FMT_X2BGR10)
  99. #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
  100. pix_fmt == AV_PIX_FMT_YUV444P16 || \
  101. pix_fmt == AV_PIX_FMT_GBRP || \
  102. pix_fmt == AV_PIX_FMT_GBRP16 || \
  103. (ctx->rgb_mode == NVENC_RGB_MODE_444 && IS_RGB(pix_fmt)))
  104. #define IS_YUV422(pix_fmt) (pix_fmt == AV_PIX_FMT_NV16 || \
  105. pix_fmt == AV_PIX_FMT_P210 || \
  106. pix_fmt == AV_PIX_FMT_P216)
  107. #define IS_GBRP(pix_fmt) (pix_fmt == AV_PIX_FMT_GBRP || \
  108. pix_fmt == AV_PIX_FMT_GBRP16)
  109. static const struct {
  110. NVENCSTATUS nverr;
  111. int averr;
  112. const char *desc;
  113. } nvenc_errors[] = {
  114. { NV_ENC_SUCCESS, 0, "success" },
  115. { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
  116. { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
  117. { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
  118. { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
  119. { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
  120. { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
  121. { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
  122. { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
  123. { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
  124. { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
  125. { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
  126. { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
  127. { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
  128. { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
  129. { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
  130. { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
  131. { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
  132. { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
  133. { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
  134. { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
  135. { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
  136. { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
  137. { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
  138. { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
  139. { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
  140. };
  141. static int nvenc_map_error(NVENCSTATUS err, const char **desc)
  142. {
  143. int i;
  144. for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
  145. if (nvenc_errors[i].nverr == err) {
  146. if (desc)
  147. *desc = nvenc_errors[i].desc;
  148. return nvenc_errors[i].averr;
  149. }
  150. }
  151. if (desc)
  152. *desc = "unknown error";
  153. return AVERROR_UNKNOWN;
  154. }
  155. static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err,
  156. const char *error_string)
  157. {
  158. const char *desc;
  159. const char *details = "(no details)";
  160. int ret = nvenc_map_error(err, &desc);
  161. #ifdef NVENC_HAVE_GETLASTERRORSTRING
  162. NvencContext *ctx = avctx->priv_data;
  163. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  164. if (p_nvenc && ctx->nvencoder)
  165. details = p_nvenc->nvEncGetLastErrorString(ctx->nvencoder);
  166. #endif
  167. av_log(avctx, AV_LOG_ERROR, "%s: %s (%d): %s\n", error_string, desc, err, details);
  168. return ret;
  169. }
  170. typedef struct GUIDTuple {
  171. const GUID guid;
  172. int flags;
  173. } GUIDTuple;
  174. #define PRESET_ALIAS(alias, name, ...) \
  175. [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
  176. #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
  177. static void nvenc_map_preset(NvencContext *ctx)
  178. {
  179. GUIDTuple presets[] = {
  180. #ifdef NVENC_HAVE_NEW_PRESETS
  181. PRESET(P1),
  182. PRESET(P2),
  183. PRESET(P3),
  184. PRESET(P4),
  185. PRESET(P5),
  186. PRESET(P6),
  187. PRESET(P7),
  188. PRESET_ALIAS(SLOW, P7, NVENC_TWO_PASSES),
  189. PRESET_ALIAS(MEDIUM, P4, NVENC_ONE_PASS),
  190. PRESET_ALIAS(FAST, P1, NVENC_ONE_PASS),
  191. // Compat aliases
  192. PRESET_ALIAS(DEFAULT, P4, NVENC_DEPRECATED_PRESET),
  193. PRESET_ALIAS(HP, P1, NVENC_DEPRECATED_PRESET),
  194. PRESET_ALIAS(HQ, P7, NVENC_DEPRECATED_PRESET),
  195. PRESET_ALIAS(BD, P5, NVENC_DEPRECATED_PRESET),
  196. PRESET_ALIAS(LOW_LATENCY_DEFAULT, P4, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
  197. PRESET_ALIAS(LOW_LATENCY_HP, P1, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
  198. PRESET_ALIAS(LOW_LATENCY_HQ, P7, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
  199. PRESET_ALIAS(LOSSLESS_DEFAULT, P4, NVENC_DEPRECATED_PRESET | NVENC_LOSSLESS),
  200. PRESET_ALIAS(LOSSLESS_HP, P1, NVENC_DEPRECATED_PRESET | NVENC_LOSSLESS),
  201. #else
  202. PRESET(DEFAULT),
  203. PRESET(HP),
  204. PRESET(HQ),
  205. PRESET(BD),
  206. PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
  207. PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
  208. PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
  209. PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
  210. PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
  211. PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
  212. PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
  213. PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
  214. #endif
  215. };
  216. GUIDTuple *t = &presets[ctx->preset];
  217. ctx->init_encode_params.presetGUID = t->guid;
  218. ctx->flags = t->flags;
  219. #ifdef NVENC_HAVE_NEW_PRESETS
  220. if (ctx->tuning_info == NV_ENC_TUNING_INFO_LOSSLESS)
  221. ctx->flags |= NVENC_LOSSLESS;
  222. #endif
  223. }
  224. #undef PRESET
  225. #undef PRESET_ALIAS
  226. static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
  227. {
  228. #if NVENCAPI_CHECK_VERSION(13, 1)
  229. const char *minver = "(unknown)";
  230. #elif NVENCAPI_CHECK_VERSION(13, 0)
  231. const char *minver = "570.0";
  232. #elif NVENCAPI_CHECK_VERSION(12, 2)
  233. # if defined(_WIN32) || defined(__CYGWIN__)
  234. const char *minver = "551.76";
  235. # else
  236. const char *minver = "550.54.14";
  237. # endif
  238. #elif NVENCAPI_CHECK_VERSION(12, 1)
  239. # if defined(_WIN32) || defined(__CYGWIN__)
  240. const char *minver = "531.61";
  241. # else
  242. const char *minver = "530.41.03";
  243. # endif
  244. #elif NVENCAPI_CHECK_VERSION(12, 0)
  245. # if defined(_WIN32) || defined(__CYGWIN__)
  246. const char *minver = "522.25";
  247. # else
  248. const char *minver = "520.56.06";
  249. # endif
  250. #elif NVENCAPI_CHECK_VERSION(11, 1)
  251. # if defined(_WIN32) || defined(__CYGWIN__)
  252. const char *minver = "471.41";
  253. # else
  254. const char *minver = "470.57.02";
  255. # endif
  256. #elif NVENCAPI_CHECK_VERSION(11, 0)
  257. # if defined(_WIN32) || defined(__CYGWIN__)
  258. const char *minver = "456.71";
  259. # else
  260. const char *minver = "455.28";
  261. # endif
  262. #elif NVENCAPI_CHECK_VERSION(10, 0)
  263. # if defined(_WIN32) || defined(__CYGWIN__)
  264. const char *minver = "450.51";
  265. # else
  266. const char *minver = "445.87";
  267. # endif
  268. #elif NVENCAPI_CHECK_VERSION(9, 1)
  269. # if defined(_WIN32) || defined(__CYGWIN__)
  270. const char *minver = "436.15";
  271. # else
  272. const char *minver = "435.21";
  273. # endif
  274. #elif NVENCAPI_CHECK_VERSION(9, 0)
  275. # if defined(_WIN32) || defined(__CYGWIN__)
  276. const char *minver = "418.81";
  277. # else
  278. const char *minver = "418.30";
  279. # endif
  280. #elif NVENCAPI_CHECK_VERSION(8, 2)
  281. # if defined(_WIN32) || defined(__CYGWIN__)
  282. const char *minver = "397.93";
  283. # else
  284. const char *minver = "396.24";
  285. #endif
  286. #elif NVENCAPI_CHECK_VERSION(8, 1)
  287. # if defined(_WIN32) || defined(__CYGWIN__)
  288. const char *minver = "390.77";
  289. # else
  290. const char *minver = "390.25";
  291. # endif
  292. #else
  293. # if defined(_WIN32) || defined(__CYGWIN__)
  294. const char *minver = "378.66";
  295. # else
  296. const char *minver = "378.13";
  297. # endif
  298. #endif
  299. av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
  300. }
  301. static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
  302. {
  303. NvencContext *ctx = avctx->priv_data;
  304. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  305. NVENCSTATUS err;
  306. uint32_t nvenc_max_ver;
  307. int ret;
  308. ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
  309. if (ret < 0)
  310. return ret;
  311. ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
  312. if (ret < 0) {
  313. nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
  314. return ret;
  315. }
  316. err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
  317. if (err != NV_ENC_SUCCESS)
  318. return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
  319. av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
  320. if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
  321. av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
  322. "Required: %d.%d Found: %d.%d\n",
  323. NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
  324. nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
  325. nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
  326. return AVERROR(ENOSYS);
  327. }
  328. dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
  329. err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
  330. if (err != NV_ENC_SUCCESS)
  331. return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
  332. av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
  333. return 0;
  334. }
  335. static int nvenc_push_context(AVCodecContext *avctx)
  336. {
  337. NvencContext *ctx = avctx->priv_data;
  338. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  339. if (ctx->d3d11_device)
  340. return 0;
  341. return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
  342. }
  343. static int nvenc_pop_context(AVCodecContext *avctx)
  344. {
  345. NvencContext *ctx = avctx->priv_data;
  346. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  347. CUcontext dummy;
  348. if (ctx->d3d11_device)
  349. return 0;
  350. return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
  351. }
  352. static av_cold int nvenc_open_session(AVCodecContext *avctx)
  353. {
  354. NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
  355. NvencContext *ctx = avctx->priv_data;
  356. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  357. NVENCSTATUS ret;
  358. params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
  359. params.apiVersion = NVENCAPI_VERSION;
  360. if (ctx->d3d11_device) {
  361. params.device = ctx->d3d11_device;
  362. params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
  363. } else {
  364. params.device = ctx->cu_context;
  365. params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
  366. }
  367. ret = p_nvenc->nvEncOpenEncodeSessionEx(&params, &ctx->nvencoder);
  368. if (ret != NV_ENC_SUCCESS) {
  369. ctx->nvencoder = NULL;
  370. return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
  371. }
  372. return 0;
  373. }
  374. static int nvenc_check_codec_support(AVCodecContext *avctx)
  375. {
  376. NvencContext *ctx = avctx->priv_data;
  377. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  378. int i, ret, count = 0;
  379. GUID *guids = NULL;
  380. ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
  381. if (ret != NV_ENC_SUCCESS || !count)
  382. return AVERROR(ENOSYS);
  383. guids = av_malloc(count * sizeof(GUID));
  384. if (!guids)
  385. return AVERROR(ENOMEM);
  386. ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
  387. if (ret != NV_ENC_SUCCESS) {
  388. ret = AVERROR(ENOSYS);
  389. goto fail;
  390. }
  391. ret = AVERROR(ENOSYS);
  392. for (i = 0; i < count; i++) {
  393. if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
  394. ret = 0;
  395. break;
  396. }
  397. }
  398. fail:
  399. av_free(guids);
  400. return ret;
  401. }
  402. static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
  403. {
  404. NvencContext *ctx = avctx->priv_data;
  405. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  406. NV_ENC_CAPS_PARAM params = { 0 };
  407. int ret, val = 0;
  408. params.version = NV_ENC_CAPS_PARAM_VER;
  409. params.capsToQuery = cap;
  410. ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, &params, &val);
  411. if (ret == NV_ENC_SUCCESS)
  412. return val;
  413. return 0;
  414. }
  415. static int nvenc_check_capabilities(AVCodecContext *avctx)
  416. {
  417. NvencContext *ctx = avctx->priv_data;
  418. int tmp, ret;
  419. ret = nvenc_check_codec_support(avctx);
  420. if (ret < 0) {
  421. av_log(avctx, AV_LOG_WARNING, "Codec not supported\n");
  422. return ret;
  423. }
  424. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
  425. if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
  426. av_log(avctx, AV_LOG_WARNING, "YUV444P not supported\n");
  427. return AVERROR(ENOSYS);
  428. }
  429. #ifdef NVENC_HAVE_422_SUPPORT
  430. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV422_ENCODE);
  431. #else
  432. ret = 0;
  433. #endif
  434. if (IS_YUV422(ctx->data_pix_fmt) && ret <= 0) {
  435. av_log(avctx, AV_LOG_WARNING, "YUV422P not supported\n");
  436. return AVERROR(ENOSYS);
  437. }
  438. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
  439. if (ctx->flags & NVENC_LOSSLESS && ret <= 0) {
  440. av_log(avctx, AV_LOG_WARNING, "Lossless encoding not supported\n");
  441. return AVERROR(ENOSYS);
  442. }
  443. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
  444. if (ret < avctx->width) {
  445. av_log(avctx, AV_LOG_WARNING, "Width %d exceeds %d\n",
  446. avctx->width, ret);
  447. return AVERROR(ENOSYS);
  448. }
  449. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
  450. if (ret < avctx->height) {
  451. av_log(avctx, AV_LOG_WARNING, "Height %d exceeds %d\n",
  452. avctx->height, ret);
  453. return AVERROR(ENOSYS);
  454. }
  455. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
  456. if (ret < avctx->max_b_frames) {
  457. av_log(avctx, AV_LOG_WARNING, "Max B-frames %d exceed %d\n",
  458. avctx->max_b_frames, ret);
  459. return AVERROR(ENOSYS);
  460. }
  461. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
  462. if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  463. av_log(avctx, AV_LOG_WARNING,
  464. "Interlaced encoding is not supported. Supported level: %d\n",
  465. ret);
  466. return AVERROR(ENOSYS);
  467. }
  468. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
  469. if ((IS_10BIT(ctx->data_pix_fmt) || ctx->highbitdepth) && ret <= 0) {
  470. av_log(avctx, AV_LOG_WARNING, "10 bit encode not supported\n");
  471. return AVERROR(ENOSYS);
  472. }
  473. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
  474. if (ctx->rc_lookahead > 0 && ret <= 0) {
  475. av_log(avctx, AV_LOG_WARNING, "RC lookahead not supported\n");
  476. return AVERROR(ENOSYS);
  477. }
  478. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
  479. if (ctx->temporal_aq > 0 && ret <= 0) {
  480. av_log(avctx, AV_LOG_WARNING, "Temporal AQ not supported\n");
  481. return AVERROR(ENOSYS);
  482. }
  483. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
  484. if (ctx->weighted_pred > 0 && ret <= 0) {
  485. av_log (avctx, AV_LOG_WARNING, "Weighted Prediction not supported\n");
  486. return AVERROR(ENOSYS);
  487. }
  488. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
  489. if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
  490. av_log(avctx, AV_LOG_WARNING, "CABAC entropy coding not supported\n");
  491. return AVERROR(ENOSYS);
  492. }
  493. #ifdef NVENC_HAVE_BFRAME_REF_MODE
  494. tmp = (ctx->b_ref_mode >= 0) ? ctx->b_ref_mode : NV_ENC_BFRAME_REF_MODE_DISABLED;
  495. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
  496. if (tmp == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1 && ret != 3) {
  497. av_log(avctx, AV_LOG_WARNING, "Each B frame as reference is not supported\n");
  498. return AVERROR(ENOSYS);
  499. } else if (tmp != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
  500. av_log(avctx, AV_LOG_WARNING, "B frames as references are not supported\n");
  501. return AVERROR(ENOSYS);
  502. }
  503. #else
  504. tmp = (ctx->b_ref_mode >= 0) ? ctx->b_ref_mode : 0;
  505. if (tmp > 0) {
  506. av_log(avctx, AV_LOG_WARNING, "B frames as references need SDK 8.1 at build time\n");
  507. return AVERROR(ENOSYS);
  508. }
  509. #endif
  510. #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
  511. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
  512. if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
  513. av_log(avctx, AV_LOG_WARNING, "Multiple reference frames are not supported by the device\n");
  514. return AVERROR(ENOSYS);
  515. }
  516. #else
  517. if(avctx->refs != 0) {
  518. av_log(avctx, AV_LOG_WARNING, "Multiple reference frames need SDK 9.1 at build time\n");
  519. return AVERROR(ENOSYS);
  520. }
  521. #endif
  522. #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
  523. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SINGLE_SLICE_INTRA_REFRESH);
  524. if(ctx->single_slice_intra_refresh && ret <= 0) {
  525. av_log(avctx, AV_LOG_WARNING, "Single slice intra refresh not supported by the device\n");
  526. return AVERROR(ENOSYS);
  527. }
  528. #else
  529. if(ctx->single_slice_intra_refresh) {
  530. av_log(avctx, AV_LOG_WARNING, "Single slice intra refresh needs SDK 11.1 at build time\n");
  531. return AVERROR(ENOSYS);
  532. }
  533. #endif
  534. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_INTRA_REFRESH);
  535. if((ctx->intra_refresh || ctx->single_slice_intra_refresh) && ret <= 0) {
  536. av_log(avctx, AV_LOG_WARNING, "Intra refresh not supported by the device\n");
  537. return AVERROR(ENOSYS);
  538. }
  539. #ifndef NVENC_HAVE_HEVC_CONSTRAINED_ENCODING
  540. if (ctx->constrained_encoding && avctx->codec->id == AV_CODEC_ID_HEVC) {
  541. av_log(avctx, AV_LOG_WARNING, "HEVC constrained encoding needs SDK 10.0 at build time\n");
  542. return AVERROR(ENOSYS);
  543. }
  544. #endif
  545. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CONSTRAINED_ENCODING);
  546. if(ctx->constrained_encoding && ret <= 0) {
  547. av_log(avctx, AV_LOG_WARNING, "Constrained encoding not supported by the device\n");
  548. return AVERROR(ENOSYS);
  549. }
  550. #if defined(NVENC_HAVE_TEMPORAL_FILTER) || defined(NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER)
  551. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_FILTER);
  552. if(ctx->tf_level > 0 && ret <= 0) {
  553. av_log(avctx, AV_LOG_WARNING, "Temporal filtering not supported by the device\n");
  554. return AVERROR(ENOSYS);
  555. }
  556. #endif
  557. #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
  558. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD_LEVEL);
  559. if(ctx->rc_lookahead > 0 && ctx->lookahead_level > 0 &&
  560. ctx->lookahead_level != NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT &&
  561. ctx->lookahead_level > ret)
  562. {
  563. av_log(avctx, AV_LOG_WARNING, "Lookahead level not supported. Maximum level: %d\n", ret);
  564. return AVERROR(ENOSYS);
  565. }
  566. #endif
  567. #ifdef NVENC_HAVE_UNIDIR_B
  568. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_UNIDIRECTIONAL_B);
  569. if(ctx->unidir_b && ret <= 0) {
  570. av_log(avctx, AV_LOG_WARNING, "Unidirectional B-Frames not supported by the device\n");
  571. return AVERROR(ENOSYS);
  572. }
  573. #endif
  574. ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
  575. return 0;
  576. }
  577. static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
  578. {
  579. NvencContext *ctx = avctx->priv_data;
  580. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  581. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  582. char name[128] = { 0};
  583. int major, minor, ret;
  584. CUdevice cu_device;
  585. int loglevel = AV_LOG_VERBOSE;
  586. if (ctx->device == LIST_DEVICES)
  587. loglevel = AV_LOG_INFO;
  588. ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
  589. if (ret < 0)
  590. return ret;
  591. ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
  592. if (ret < 0)
  593. return ret;
  594. ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
  595. if (ret < 0)
  596. return ret;
  597. av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
  598. if (((major << 4) | minor) < NVENC_CAP) {
  599. av_log(avctx, loglevel, "does not support NVENC\n");
  600. goto fail;
  601. }
  602. if (ctx->device != idx && ctx->device != ANY_DEVICE)
  603. return -1;
  604. ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
  605. if (ret < 0)
  606. goto fail;
  607. ctx->cu_context = ctx->cu_context_internal;
  608. ctx->cu_stream = NULL;
  609. if ((ret = nvenc_pop_context(avctx)) < 0)
  610. goto fail2;
  611. if ((ret = nvenc_open_session(avctx)) < 0)
  612. goto fail2;
  613. if ((ret = nvenc_check_capabilities(avctx)) < 0)
  614. goto fail3;
  615. av_log(avctx, loglevel, "supports NVENC\n");
  616. dl_fn->nvenc_device_count++;
  617. if (ctx->device == idx || ctx->device == ANY_DEVICE)
  618. return 0;
  619. fail3:
  620. if ((ret = nvenc_push_context(avctx)) < 0)
  621. return ret;
  622. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  623. ctx->nvencoder = NULL;
  624. if ((ret = nvenc_pop_context(avctx)) < 0)
  625. return ret;
  626. fail2:
  627. CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
  628. ctx->cu_context_internal = NULL;
  629. fail:
  630. return AVERROR(ENOSYS);
  631. }
  632. static av_cold int nvenc_setup_device(AVCodecContext *avctx)
  633. {
  634. NvencContext *ctx = avctx->priv_data;
  635. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  636. switch (avctx->codec->id) {
  637. case AV_CODEC_ID_H264:
  638. ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
  639. break;
  640. case AV_CODEC_ID_HEVC:
  641. ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
  642. break;
  643. #if CONFIG_AV1_NVENC_ENCODER
  644. case AV_CODEC_ID_AV1:
  645. ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_AV1_GUID;
  646. break;
  647. #endif
  648. default:
  649. return AVERROR_BUG;
  650. }
  651. nvenc_map_preset(ctx);
  652. if (ctx->flags & NVENC_DEPRECATED_PRESET)
  653. av_log(avctx, AV_LOG_WARNING, "The selected preset is deprecated. Use p1 to p7 + -tune or fast/medium/slow.\n");
  654. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
  655. AVHWFramesContext *frames_ctx;
  656. AVHWDeviceContext *hwdev_ctx;
  657. AVCUDADeviceContext *cuda_device_hwctx = NULL;
  658. #if CONFIG_D3D11VA
  659. AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
  660. #endif
  661. int ret;
  662. if (avctx->hw_frames_ctx) {
  663. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  664. if (frames_ctx->format == AV_PIX_FMT_CUDA)
  665. cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
  666. #if CONFIG_D3D11VA
  667. else if (frames_ctx->format == AV_PIX_FMT_D3D11)
  668. d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
  669. #endif
  670. else
  671. return AVERROR(EINVAL);
  672. } else if (avctx->hw_device_ctx) {
  673. hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  674. if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
  675. cuda_device_hwctx = hwdev_ctx->hwctx;
  676. #if CONFIG_D3D11VA
  677. else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
  678. d3d11_device_hwctx = hwdev_ctx->hwctx;
  679. #endif
  680. else
  681. return AVERROR(EINVAL);
  682. } else {
  683. return AVERROR(EINVAL);
  684. }
  685. if (cuda_device_hwctx) {
  686. ctx->cu_context = cuda_device_hwctx->cuda_ctx;
  687. ctx->cu_stream = cuda_device_hwctx->stream;
  688. }
  689. #if CONFIG_D3D11VA
  690. else if (d3d11_device_hwctx) {
  691. ctx->d3d11_device = d3d11_device_hwctx->device;
  692. ID3D11Device_AddRef(ctx->d3d11_device);
  693. }
  694. #endif
  695. ret = nvenc_open_session(avctx);
  696. if (ret < 0)
  697. return ret;
  698. ret = nvenc_check_capabilities(avctx);
  699. if (ret < 0) {
  700. av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
  701. return ret;
  702. }
  703. } else {
  704. int i, nb_devices = 0;
  705. if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
  706. return AVERROR_UNKNOWN;
  707. if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
  708. return AVERROR_UNKNOWN;
  709. if (!nb_devices) {
  710. av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
  711. return AVERROR_EXTERNAL;
  712. }
  713. av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
  714. dl_fn->nvenc_device_count = 0;
  715. for (i = 0; i < nb_devices; ++i) {
  716. if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
  717. return 0;
  718. }
  719. if (ctx->device == LIST_DEVICES)
  720. return AVERROR_EXIT;
  721. if (!dl_fn->nvenc_device_count) {
  722. av_log(avctx, AV_LOG_FATAL, "No capable devices found\n");
  723. return AVERROR_EXTERNAL;
  724. }
  725. av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
  726. return AVERROR(EINVAL);
  727. }
  728. return 0;
  729. }
  730. static av_cold void set_constqp(AVCodecContext *avctx)
  731. {
  732. NvencContext *ctx = avctx->priv_data;
  733. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  734. #if CONFIG_AV1_NVENC_ENCODER
  735. int qmax = avctx->codec->id == AV_CODEC_ID_AV1 ? 255 : 51;
  736. #else
  737. int qmax = 51;
  738. #endif
  739. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  740. if (ctx->init_qp_p >= 0) {
  741. rc->constQP.qpInterP = ctx->init_qp_p;
  742. if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
  743. rc->constQP.qpIntra = ctx->init_qp_i;
  744. rc->constQP.qpInterB = ctx->init_qp_b;
  745. } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  746. rc->constQP.qpIntra = av_clip(
  747. rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, qmax);
  748. rc->constQP.qpInterB = av_clip(
  749. rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, qmax);
  750. } else {
  751. rc->constQP.qpIntra = rc->constQP.qpInterP;
  752. rc->constQP.qpInterB = rc->constQP.qpInterP;
  753. }
  754. } else if (ctx->cqp >= 0) {
  755. rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
  756. if (avctx->b_quant_factor != 0.0)
  757. rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, qmax);
  758. if (avctx->i_quant_factor != 0.0)
  759. rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, qmax);
  760. }
  761. avctx->qmin = ctx->qmin = -1;
  762. avctx->qmax = ctx->qmax = -1;
  763. }
  764. static av_cold void set_vbr(AVCodecContext *avctx)
  765. {
  766. NvencContext *ctx = avctx->priv_data;
  767. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  768. int qp_inter_p;
  769. #if CONFIG_AV1_NVENC_ENCODER
  770. int qmax = avctx->codec->id == AV_CODEC_ID_AV1 ? 255 : 51;
  771. #else
  772. int qmax = 51;
  773. #endif
  774. if (avctx->qmin >= 0 || avctx->qmax >= 0)
  775. av_log(avctx, AV_LOG_WARNING, "Passing qmin/qmax via global AVCodecContext options. Use encoder options instead.\n");
  776. if (avctx->qmin >= 0 && ctx->qmin < 0)
  777. ctx->qmin = avctx->qmin;
  778. if (avctx->qmax >= 0 && ctx->qmax < 0)
  779. ctx->qmax = avctx->qmax;
  780. avctx->qmin = ctx->qmin;
  781. avctx->qmax = ctx->qmax;
  782. if (ctx->qmin >= 0 && ctx->qmax >= 0) {
  783. rc->enableMinQP = 1;
  784. rc->enableMaxQP = 1;
  785. rc->minQP.qpInterB = ctx->qmin;
  786. rc->minQP.qpInterP = ctx->qmin;
  787. rc->minQP.qpIntra = ctx->qmin;
  788. rc->maxQP.qpInterB = ctx->qmax;
  789. rc->maxQP.qpInterP = ctx->qmax;
  790. rc->maxQP.qpIntra = ctx->qmax;
  791. qp_inter_p = (ctx->qmax + 3 * ctx->qmin) / 4; // biased towards Qmin
  792. } else if (ctx->qmin >= 0) {
  793. rc->enableMinQP = 1;
  794. rc->minQP.qpInterB = ctx->qmin;
  795. rc->minQP.qpInterP = ctx->qmin;
  796. rc->minQP.qpIntra = ctx->qmin;
  797. qp_inter_p = ctx->qmin;
  798. } else {
  799. qp_inter_p = 26; // default to 26
  800. }
  801. rc->enableInitialRCQP = 1;
  802. if (ctx->init_qp_p < 0) {
  803. rc->initialRCQP.qpInterP = qp_inter_p;
  804. } else {
  805. rc->initialRCQP.qpInterP = ctx->init_qp_p;
  806. }
  807. if (ctx->init_qp_i < 0) {
  808. if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  809. rc->initialRCQP.qpIntra = av_clip(
  810. rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, qmax);
  811. } else {
  812. rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
  813. }
  814. } else {
  815. rc->initialRCQP.qpIntra = ctx->init_qp_i;
  816. }
  817. if (ctx->init_qp_b < 0) {
  818. if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  819. rc->initialRCQP.qpInterB = av_clip(
  820. rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, qmax);
  821. } else {
  822. rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
  823. }
  824. } else {
  825. rc->initialRCQP.qpInterB = ctx->init_qp_b;
  826. }
  827. }
  828. static av_cold void set_lossless(AVCodecContext *avctx)
  829. {
  830. NvencContext *ctx = avctx->priv_data;
  831. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  832. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  833. rc->constQP.qpInterB = 0;
  834. rc->constQP.qpInterP = 0;
  835. rc->constQP.qpIntra = 0;
  836. avctx->qmin = ctx->qmin = -1;
  837. avctx->qmax = ctx->qmax = -1;
  838. }
  839. static void nvenc_override_rate_control(AVCodecContext *avctx)
  840. {
  841. NvencContext *ctx = avctx->priv_data;
  842. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  843. switch (ctx->rc) {
  844. case NV_ENC_PARAMS_RC_CONSTQP:
  845. set_constqp(avctx);
  846. return;
  847. #ifndef NVENC_NO_DEPRECATED_RC
  848. case NV_ENC_PARAMS_RC_VBR_MINQP:
  849. if (avctx->qmin < 0 && ctx->qmin < 0) {
  850. av_log(avctx, AV_LOG_WARNING,
  851. "The variable bitrate rate-control requires "
  852. "the 'qmin' option set.\n");
  853. set_vbr(avctx);
  854. return;
  855. }
  856. /* fall through */
  857. case NV_ENC_PARAMS_RC_VBR_HQ:
  858. #endif
  859. case NV_ENC_PARAMS_RC_VBR:
  860. set_vbr(avctx);
  861. break;
  862. case NV_ENC_PARAMS_RC_CBR:
  863. #ifndef NVENC_NO_DEPRECATED_RC
  864. case NV_ENC_PARAMS_RC_CBR_HQ:
  865. case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
  866. #endif
  867. break;
  868. }
  869. rc->rateControlMode = ctx->rc;
  870. }
  871. static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
  872. {
  873. NvencContext *ctx = avctx->priv_data;
  874. // default minimum of 4 surfaces
  875. // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
  876. // another multiply by 2 to avoid blocking next PBB group
  877. int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
  878. // lookahead enabled
  879. if (ctx->rc_lookahead > 0) {
  880. // +1 is to account for lkd_bound calculation later
  881. // +4 is to allow sufficient pipelining with lookahead
  882. nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
  883. if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
  884. {
  885. av_log(avctx, AV_LOG_WARNING,
  886. "Defined rc_lookahead requires more surfaces, "
  887. "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
  888. }
  889. ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
  890. } else {
  891. if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
  892. {
  893. av_log(avctx, AV_LOG_WARNING,
  894. "Defined b-frame requires more surfaces, "
  895. "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
  896. ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
  897. }
  898. else if (ctx->nb_surfaces <= 0)
  899. ctx->nb_surfaces = nb_surfaces;
  900. // otherwise use user specified value
  901. }
  902. ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
  903. ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
  904. // Output in the worst case will only start when the surface buffer is completely full.
  905. // Hence we need to keep at least the max amount of surfaces plus the max reorder delay around.
  906. ctx->frame_data_array_nb = FFMAX(ctx->nb_surfaces, ctx->nb_surfaces + ctx->encode_config.frameIntervalP - 1);
  907. return 0;
  908. }
  909. static av_cold int nvenc_setup_rate_control(AVCodecContext *avctx)
  910. {
  911. NvencContext *ctx = avctx->priv_data;
  912. if (avctx->global_quality > 0)
  913. av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
  914. if (ctx->cqp < 0 && avctx->global_quality > 0)
  915. ctx->cqp = avctx->global_quality;
  916. if (avctx->bit_rate > 0) {
  917. ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
  918. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  919. ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
  920. }
  921. if (avctx->rc_max_rate > 0)
  922. ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
  923. #ifdef NVENC_HAVE_MULTIPASS
  924. ctx->encode_config.rcParams.multiPass = ctx->multipass;
  925. if (ctx->flags & NVENC_ONE_PASS)
  926. ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
  927. if (ctx->flags & NVENC_TWO_PASSES || ctx->twopass > 0)
  928. ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
  929. if (ctx->rc < 0) {
  930. if (ctx->cbr) {
  931. ctx->rc = NV_ENC_PARAMS_RC_CBR;
  932. } else if (ctx->cqp >= 0) {
  933. ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
  934. } else if (ctx->quality >= 0.0f) {
  935. ctx->rc = NV_ENC_PARAMS_RC_VBR;
  936. }
  937. }
  938. #else
  939. if (ctx->rc < 0) {
  940. if (ctx->flags & NVENC_ONE_PASS)
  941. ctx->twopass = 0;
  942. if (ctx->flags & NVENC_TWO_PASSES)
  943. ctx->twopass = 1;
  944. if (ctx->twopass < 0)
  945. ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
  946. if (ctx->cbr) {
  947. if (ctx->twopass) {
  948. ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
  949. } else {
  950. ctx->rc = NV_ENC_PARAMS_RC_CBR;
  951. }
  952. } else if (ctx->cqp >= 0) {
  953. ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
  954. } else if (ctx->twopass) {
  955. ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
  956. } else if ((avctx->qmin >= 0 && avctx->qmax >= 0) ||
  957. (ctx->qmin >= 0 && ctx->qmax >= 0)) {
  958. ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
  959. }
  960. }
  961. #endif
  962. if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
  963. av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
  964. av_log(avctx, AV_LOG_WARNING, "Use -rc constqp/cbr/vbr, -tune and -multipass instead.\n");
  965. ctx->rc &= ~RC_MODE_DEPRECATED;
  966. }
  967. #ifdef NVENC_HAVE_QP_CHROMA_OFFSETS
  968. ctx->encode_config.rcParams.cbQPIndexOffset = ctx->qp_cb_offset;
  969. ctx->encode_config.rcParams.crQPIndexOffset = ctx->qp_cr_offset;
  970. #else
  971. if (ctx->qp_cb_offset || ctx->qp_cr_offset)
  972. av_log(avctx, AV_LOG_WARNING, "Failed setting QP CB/CR offsets, SDK 11.1 or greater required at compile time.\n");
  973. #endif
  974. #ifdef NVENC_HAVE_LDKFS
  975. if (ctx->ldkfs)
  976. ctx->encode_config.rcParams.lowDelayKeyFrameScale = ctx->ldkfs;
  977. #endif
  978. if (ctx->flags & NVENC_LOSSLESS) {
  979. set_lossless(avctx);
  980. } else if (ctx->rc >= 0) {
  981. nvenc_override_rate_control(avctx);
  982. } else {
  983. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
  984. set_vbr(avctx);
  985. }
  986. if (avctx->rc_buffer_size > 0) {
  987. ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
  988. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  989. avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
  990. }
  991. if (ctx->aq) {
  992. ctx->encode_config.rcParams.enableAQ = 1;
  993. ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
  994. av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
  995. }
  996. if (ctx->temporal_aq) {
  997. ctx->encode_config.rcParams.enableTemporalAQ = 1;
  998. av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
  999. }
  1000. if (ctx->rc_lookahead > 0) {
  1001. int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
  1002. ctx->encode_config.frameIntervalP - 4;
  1003. if (lkd_bound < 0) {
  1004. ctx->encode_config.rcParams.enableLookahead = 0;
  1005. av_log(avctx, AV_LOG_WARNING,
  1006. "Lookahead not enabled. Increase buffer delay (-delay).\n");
  1007. } else {
  1008. ctx->encode_config.rcParams.enableLookahead = 1;
  1009. ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
  1010. ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
  1011. ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
  1012. av_log(avctx, AV_LOG_VERBOSE,
  1013. "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
  1014. ctx->encode_config.rcParams.lookaheadDepth,
  1015. ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
  1016. ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
  1017. if (ctx->encode_config.rcParams.lookaheadDepth < ctx->rc_lookahead)
  1018. av_log(avctx, AV_LOG_WARNING, "Clipping lookahead depth to %d (from %d) due to lack of surfaces/delay",
  1019. ctx->encode_config.rcParams.lookaheadDepth, ctx->rc_lookahead);
  1020. #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
  1021. if (ctx->lookahead_level >= 0) {
  1022. switch (ctx->lookahead_level) {
  1023. case NV_ENC_LOOKAHEAD_LEVEL_0:
  1024. case NV_ENC_LOOKAHEAD_LEVEL_1:
  1025. case NV_ENC_LOOKAHEAD_LEVEL_2:
  1026. case NV_ENC_LOOKAHEAD_LEVEL_3:
  1027. case NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT:
  1028. break;
  1029. default:
  1030. av_log(avctx, AV_LOG_ERROR, "Invalid lookahead level.\n");
  1031. return AVERROR(EINVAL);
  1032. }
  1033. ctx->encode_config.rcParams.lookaheadLevel = ctx->lookahead_level;
  1034. }
  1035. #endif
  1036. }
  1037. }
  1038. if (ctx->strict_gop) {
  1039. ctx->encode_config.rcParams.strictGOPTarget = 1;
  1040. av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
  1041. }
  1042. if (ctx->nonref_p)
  1043. ctx->encode_config.rcParams.enableNonRefP = 1;
  1044. if (ctx->zerolatency)
  1045. ctx->encode_config.rcParams.zeroReorderDelay = 1;
  1046. if (ctx->quality) {
  1047. //convert from float to fixed point 8.8
  1048. int tmp_quality = (int)(ctx->quality * 256.0f);
  1049. ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
  1050. ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
  1051. av_log(avctx, AV_LOG_VERBOSE, "CQ(%d) mode enabled.\n", tmp_quality);
  1052. // CQ mode shall discard avg bitrate/vbv buffer size and honor only max bitrate
  1053. ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate = 0;
  1054. ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size = 0;
  1055. ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
  1056. }
  1057. return 0;
  1058. }
  1059. static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
  1060. {
  1061. NvencContext *ctx = avctx->priv_data;
  1062. NV_ENC_CONFIG *cc = &ctx->encode_config;
  1063. NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
  1064. NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
  1065. const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(ctx->data_pix_fmt);
  1066. if ((pixdesc->flags & AV_PIX_FMT_FLAG_RGB) && !IS_GBRP(ctx->data_pix_fmt)) {
  1067. vui->colourMatrix = AVCOL_SPC_BT470BG;
  1068. vui->colourPrimaries = avctx->color_primaries;
  1069. vui->transferCharacteristics = avctx->color_trc;
  1070. vui->videoFullRangeFlag = 0;
  1071. } else {
  1072. vui->colourMatrix = IS_GBRP(ctx->data_pix_fmt) ? AVCOL_SPC_RGB : avctx->colorspace;
  1073. vui->colourPrimaries = avctx->color_primaries;
  1074. vui->transferCharacteristics = avctx->color_trc;
  1075. vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  1076. || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
  1077. }
  1078. vui->colourDescriptionPresentFlag =
  1079. (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
  1080. vui->videoSignalTypePresentFlag =
  1081. (vui->colourDescriptionPresentFlag
  1082. || vui->videoFormat != 5
  1083. || vui->videoFullRangeFlag != 0);
  1084. if (ctx->max_slice_size > 0) {
  1085. h264->sliceMode = 1;
  1086. h264->sliceModeData = ctx->max_slice_size;
  1087. } else {
  1088. h264->sliceMode = 3;
  1089. h264->sliceModeData = avctx->slices > 0 ? avctx->slices : 1;
  1090. }
  1091. if (ctx->intra_refresh) {
  1092. h264->enableIntraRefresh = 1;
  1093. h264->intraRefreshPeriod = cc->gopLength;
  1094. h264->intraRefreshCnt = cc->gopLength - 1;
  1095. cc->gopLength = NVENC_INFINITE_GOPLENGTH;
  1096. h264->outputRecoveryPointSEI = 1;
  1097. #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
  1098. h264->singleSliceIntraRefresh = ctx->single_slice_intra_refresh;
  1099. #endif
  1100. }
  1101. if (ctx->constrained_encoding)
  1102. h264->enableConstrainedEncoding = 1;
  1103. h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  1104. h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  1105. h264->outputAUD = ctx->aud;
  1106. if (ctx->dpb_size >= 0) {
  1107. /* 0 means "let the hardware decide" */
  1108. h264->maxNumRefFrames = ctx->dpb_size;
  1109. }
  1110. h264->idrPeriod = cc->gopLength;
  1111. if (IS_CBR(cc->rcParams.rateControlMode)) {
  1112. h264->outputBufferingPeriodSEI = 1;
  1113. }
  1114. h264->outputPictureTimingSEI = 1;
  1115. #ifndef NVENC_NO_DEPRECATED_RC
  1116. if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
  1117. cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
  1118. cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
  1119. h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
  1120. h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
  1121. }
  1122. #endif
  1123. if (ctx->flags & NVENC_LOSSLESS) {
  1124. h264->qpPrimeYZeroTransformBypassFlag = 1;
  1125. } else {
  1126. switch(ctx->profile) {
  1127. case NV_ENC_H264_PROFILE_BASELINE:
  1128. cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
  1129. avctx->profile = AV_PROFILE_H264_BASELINE;
  1130. break;
  1131. case NV_ENC_H264_PROFILE_MAIN:
  1132. cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
  1133. avctx->profile = AV_PROFILE_H264_MAIN;
  1134. break;
  1135. case NV_ENC_H264_PROFILE_HIGH:
  1136. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
  1137. avctx->profile = AV_PROFILE_H264_HIGH;
  1138. break;
  1139. #ifdef NVENC_HAVE_H264_10BIT_SUPPORT
  1140. case NV_ENC_H264_PROFILE_HIGH_10:
  1141. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
  1142. avctx->profile = AV_PROFILE_H264_HIGH_10;
  1143. break;
  1144. #endif
  1145. #ifdef NVENC_HAVE_422_SUPPORT
  1146. case NV_ENC_H264_PROFILE_HIGH_422:
  1147. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
  1148. avctx->profile = AV_PROFILE_H264_HIGH_422;
  1149. break;
  1150. #endif
  1151. case NV_ENC_H264_PROFILE_HIGH_444P:
  1152. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  1153. avctx->profile = AV_PROFILE_H264_HIGH_444_PREDICTIVE;
  1154. break;
  1155. }
  1156. }
  1157. #ifdef NVENC_HAVE_H264_10BIT_SUPPORT
  1158. // force setting profile as high10 if input is 10 bit or if it should be encoded as 10 bit
  1159. if (IS_10BIT(ctx->data_pix_fmt) || ctx->highbitdepth) {
  1160. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
  1161. avctx->profile = AV_PROFILE_H264_HIGH_10;
  1162. }
  1163. #endif
  1164. // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
  1165. if (IS_YUV444(ctx->data_pix_fmt)) {
  1166. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  1167. avctx->profile = AV_PROFILE_H264_HIGH_444_PREDICTIVE;
  1168. }
  1169. #ifdef NVENC_HAVE_422_SUPPORT
  1170. // force setting profile as high422p if input is AV_PIX_FMT_YUV422P
  1171. if (IS_YUV422(ctx->data_pix_fmt)) {
  1172. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
  1173. avctx->profile = AV_PROFILE_H264_HIGH_422;
  1174. }
  1175. #endif
  1176. vui->bitstreamRestrictionFlag = cc->gopLength != 1 || avctx->profile < AV_PROFILE_H264_HIGH;
  1177. h264->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : IS_YUV422(ctx->data_pix_fmt) ? 2 : 1;
  1178. h264->level = ctx->level;
  1179. #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
  1180. h264->inputBitDepth = IS_10BIT(ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
  1181. h264->outputBitDepth = (IS_10BIT(ctx->data_pix_fmt) || ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
  1182. #endif
  1183. if (ctx->coder >= 0)
  1184. h264->entropyCodingMode = ctx->coder;
  1185. #ifdef NVENC_HAVE_BFRAME_REF_MODE
  1186. if (ctx->b_ref_mode >= 0)
  1187. h264->useBFramesAsRef = ctx->b_ref_mode;
  1188. #endif
  1189. #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
  1190. h264->numRefL0 = avctx->refs;
  1191. h264->numRefL1 = avctx->refs;
  1192. #endif
  1193. #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
  1194. if (ctx->tf_level >= 0) {
  1195. h264->tfLevel = ctx->tf_level;
  1196. switch (ctx->tf_level)
  1197. {
  1198. case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
  1199. case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
  1200. break;
  1201. default:
  1202. av_log(avctx, AV_LOG_ERROR, "Invalid temporal filtering level.\n");
  1203. return AVERROR(EINVAL);
  1204. }
  1205. if (ctx->encode_config.frameIntervalP < 5)
  1206. av_log(avctx, AV_LOG_WARNING, "Temporal filtering needs at least 4 B-Frames (-bf 4).\n");
  1207. }
  1208. #endif
  1209. return 0;
  1210. }
  1211. static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
  1212. {
  1213. NvencContext *ctx = avctx->priv_data;
  1214. NV_ENC_CONFIG *cc = &ctx->encode_config;
  1215. NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
  1216. NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
  1217. const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(ctx->data_pix_fmt);
  1218. if ((pixdesc->flags & AV_PIX_FMT_FLAG_RGB) && !IS_GBRP(ctx->data_pix_fmt)) {
  1219. vui->colourMatrix = AVCOL_SPC_BT470BG;
  1220. vui->colourPrimaries = avctx->color_primaries;
  1221. vui->transferCharacteristics = avctx->color_trc;
  1222. vui->videoFullRangeFlag = 0;
  1223. } else {
  1224. vui->colourMatrix = IS_GBRP(ctx->data_pix_fmt) ? AVCOL_SPC_RGB : avctx->colorspace;
  1225. vui->colourPrimaries = avctx->color_primaries;
  1226. vui->transferCharacteristics = avctx->color_trc;
  1227. vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  1228. || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
  1229. }
  1230. vui->colourDescriptionPresentFlag =
  1231. (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
  1232. vui->videoSignalTypePresentFlag =
  1233. (vui->colourDescriptionPresentFlag
  1234. || vui->videoFormat != 5
  1235. || vui->videoFullRangeFlag != 0);
  1236. if (ctx->max_slice_size > 0) {
  1237. hevc->sliceMode = 1;
  1238. hevc->sliceModeData = ctx->max_slice_size;
  1239. } else {
  1240. hevc->sliceMode = 3;
  1241. hevc->sliceModeData = avctx->slices > 0 ? avctx->slices : 1;
  1242. }
  1243. if (ctx->intra_refresh) {
  1244. hevc->enableIntraRefresh = 1;
  1245. hevc->intraRefreshPeriod = cc->gopLength;
  1246. hevc->intraRefreshCnt = cc->gopLength - 1;
  1247. cc->gopLength = NVENC_INFINITE_GOPLENGTH;
  1248. #ifdef NVENC_HAVE_HEVC_OUTPUT_RECOVERY_POINT_SEI
  1249. hevc->outputRecoveryPointSEI = 1;
  1250. #endif
  1251. #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
  1252. hevc->singleSliceIntraRefresh = ctx->single_slice_intra_refresh;
  1253. #endif
  1254. }
  1255. #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
  1256. ctx->mdm = hevc->outputMasteringDisplay = !!av_frame_side_data_get(avctx->decoded_side_data,
  1257. avctx->nb_decoded_side_data,
  1258. AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
  1259. ctx->cll = hevc->outputMaxCll = !!av_frame_side_data_get(avctx->decoded_side_data,
  1260. avctx->nb_decoded_side_data,
  1261. AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
  1262. #endif
  1263. #ifdef NVENC_HAVE_HEVC_CONSTRAINED_ENCODING
  1264. if (ctx->constrained_encoding)
  1265. hevc->enableConstrainedEncoding = 1;
  1266. #endif
  1267. hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  1268. hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  1269. hevc->outputAUD = ctx->aud;
  1270. if (ctx->dpb_size >= 0) {
  1271. /* 0 means "let the hardware decide" */
  1272. hevc->maxNumRefFramesInDPB = ctx->dpb_size;
  1273. }
  1274. hevc->idrPeriod = cc->gopLength;
  1275. if (IS_CBR(cc->rcParams.rateControlMode)) {
  1276. hevc->outputBufferingPeriodSEI = 1;
  1277. }
  1278. hevc->outputPictureTimingSEI = 1;
  1279. switch (ctx->profile) {
  1280. case NV_ENC_HEVC_PROFILE_MAIN:
  1281. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
  1282. avctx->profile = AV_PROFILE_HEVC_MAIN;
  1283. break;
  1284. case NV_ENC_HEVC_PROFILE_MAIN_10:
  1285. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
  1286. avctx->profile = AV_PROFILE_HEVC_MAIN_10;
  1287. break;
  1288. case NV_ENC_HEVC_PROFILE_REXT:
  1289. cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
  1290. avctx->profile = AV_PROFILE_HEVC_REXT;
  1291. break;
  1292. }
  1293. // force setting profile as main10 if input is 10 bit or if it should be encoded as 10 bit
  1294. if (IS_10BIT(ctx->data_pix_fmt) || ctx->highbitdepth) {
  1295. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
  1296. avctx->profile = AV_PROFILE_HEVC_MAIN_10;
  1297. }
  1298. // force setting profile as rext if input is yuv444 or yuv422
  1299. if (IS_YUV444(ctx->data_pix_fmt) || IS_YUV422(ctx->data_pix_fmt)) {
  1300. cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
  1301. avctx->profile = AV_PROFILE_HEVC_REXT;
  1302. }
  1303. hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : IS_YUV422(ctx->data_pix_fmt) ? 2 : 1;
  1304. #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
  1305. hevc->inputBitDepth = IS_10BIT(ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
  1306. hevc->outputBitDepth = (IS_10BIT(ctx->data_pix_fmt) || ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
  1307. #else
  1308. hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
  1309. #endif
  1310. hevc->level = ctx->level;
  1311. hevc->tier = ctx->tier;
  1312. #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
  1313. if (ctx->b_ref_mode >= 0)
  1314. hevc->useBFramesAsRef = ctx->b_ref_mode;
  1315. #endif
  1316. #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
  1317. hevc->numRefL0 = avctx->refs;
  1318. hevc->numRefL1 = avctx->refs;
  1319. #endif
  1320. #ifdef NVENC_HAVE_TEMPORAL_FILTER
  1321. if (ctx->tf_level >= 0) {
  1322. hevc->tfLevel = ctx->tf_level;
  1323. switch (ctx->tf_level)
  1324. {
  1325. case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
  1326. case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
  1327. break;
  1328. default:
  1329. av_log(avctx, AV_LOG_ERROR, "Invalid temporal filtering level.\n");
  1330. return AVERROR(EINVAL);
  1331. }
  1332. if (ctx->encode_config.frameIntervalP < 5)
  1333. av_log(avctx, AV_LOG_WARNING, "Temporal filtering needs at least 4 B-Frames (-bf 4).\n");
  1334. }
  1335. #endif
  1336. return 0;
  1337. }
  1338. #if CONFIG_AV1_NVENC_ENCODER
  1339. static av_cold int nvenc_setup_av1_config(AVCodecContext *avctx)
  1340. {
  1341. NvencContext *ctx = avctx->priv_data;
  1342. NV_ENC_CONFIG *cc = &ctx->encode_config;
  1343. NV_ENC_CONFIG_AV1 *av1 = &cc->encodeCodecConfig.av1Config;
  1344. const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(ctx->data_pix_fmt);
  1345. if ((pixdesc->flags & AV_PIX_FMT_FLAG_RGB) && !IS_GBRP(ctx->data_pix_fmt)) {
  1346. av1->matrixCoefficients = AVCOL_SPC_BT470BG;
  1347. av1->colorPrimaries = avctx->color_primaries;
  1348. av1->transferCharacteristics = avctx->color_trc;
  1349. av1->colorRange = 0;
  1350. } else {
  1351. av1->matrixCoefficients = IS_GBRP(ctx->data_pix_fmt) ? AVCOL_SPC_RGB : avctx->colorspace;
  1352. av1->colorPrimaries = avctx->color_primaries;
  1353. av1->transferCharacteristics = avctx->color_trc;
  1354. av1->colorRange = (avctx->color_range == AVCOL_RANGE_JPEG
  1355. || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
  1356. }
  1357. if (IS_YUV444(ctx->data_pix_fmt)) {
  1358. av_log(avctx, AV_LOG_ERROR, "AV1 High Profile not supported, required for 4:4:4 encoding\n");
  1359. return AVERROR(ENOTSUP);
  1360. } else {
  1361. cc->profileGUID = NV_ENC_AV1_PROFILE_MAIN_GUID;
  1362. avctx->profile = AV_PROFILE_AV1_MAIN;
  1363. }
  1364. if (ctx->dpb_size >= 0) {
  1365. /* 0 means "let the hardware decide" */
  1366. av1->maxNumRefFramesInDPB = ctx->dpb_size;
  1367. }
  1368. if (ctx->intra_refresh) {
  1369. av1->enableIntraRefresh = 1;
  1370. av1->intraRefreshPeriod = cc->gopLength;
  1371. av1->intraRefreshCnt = cc->gopLength - 1;
  1372. cc->gopLength = NVENC_INFINITE_GOPLENGTH;
  1373. }
  1374. av1->idrPeriod = cc->gopLength;
  1375. if (IS_CBR(cc->rcParams.rateControlMode)) {
  1376. av1->enableBitstreamPadding = 1;
  1377. }
  1378. if (ctx->tile_cols >= 0)
  1379. av1->numTileColumns = ctx->tile_cols;
  1380. if (ctx->tile_rows >= 0)
  1381. av1->numTileRows = ctx->tile_rows;
  1382. av1->outputAnnexBFormat = 0;
  1383. av1->level = ctx->level;
  1384. av1->tier = ctx->tier;
  1385. av1->enableTimingInfo = ctx->timing_info;
  1386. /* mp4 encapsulation requires sequence headers to be present on all keyframes for AV1 */
  1387. av1->disableSeqHdr = 0;
  1388. av1->repeatSeqHdr = 1;
  1389. av1->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
  1390. #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
  1391. av1->inputBitDepth = IS_10BIT(ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
  1392. av1->outputBitDepth = (IS_10BIT(ctx->data_pix_fmt) || ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
  1393. #else
  1394. av1->inputPixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
  1395. av1->pixelBitDepthMinus8 = (IS_10BIT(ctx->data_pix_fmt) || ctx->highbitdepth) ? 2 : 0;
  1396. #endif
  1397. #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
  1398. ctx->mdm = av1->outputMasteringDisplay = !!av_frame_side_data_get(avctx->decoded_side_data,
  1399. avctx->nb_decoded_side_data,
  1400. AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
  1401. ctx->cll = av1->outputMaxCll = !!av_frame_side_data_get(avctx->decoded_side_data,
  1402. avctx->nb_decoded_side_data,
  1403. AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
  1404. #endif
  1405. if (ctx->b_ref_mode >= 0)
  1406. av1->useBFramesAsRef = ctx->b_ref_mode;
  1407. av1->numFwdRefs = avctx->refs;
  1408. av1->numBwdRefs = avctx->refs;
  1409. #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
  1410. if (ctx->tf_level >= 0) {
  1411. av1->tfLevel = ctx->tf_level;
  1412. switch (ctx->tf_level)
  1413. {
  1414. case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
  1415. case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
  1416. break;
  1417. default:
  1418. av_log(avctx, AV_LOG_ERROR, "Invalid temporal filtering level.\n");
  1419. return AVERROR(EINVAL);
  1420. }
  1421. if (ctx->encode_config.frameIntervalP < 5)
  1422. av_log(avctx, AV_LOG_WARNING, "Temporal filtering needs at least 4 B-Frames (-bf 4).\n");
  1423. }
  1424. #endif
  1425. return 0;
  1426. }
  1427. #endif
  1428. static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
  1429. {
  1430. switch (avctx->codec->id) {
  1431. case AV_CODEC_ID_H264:
  1432. return nvenc_setup_h264_config(avctx);
  1433. case AV_CODEC_ID_HEVC:
  1434. return nvenc_setup_hevc_config(avctx);
  1435. #if CONFIG_AV1_NVENC_ENCODER
  1436. case AV_CODEC_ID_AV1:
  1437. return nvenc_setup_av1_config(avctx);
  1438. #endif
  1439. /* Earlier switch/case will return if unknown codec is passed. */
  1440. }
  1441. return 0;
  1442. }
  1443. static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
  1444. int sw, sh;
  1445. sw = avctx->width;
  1446. sh = avctx->height;
  1447. #if CONFIG_AV1_NVENC_ENCODER
  1448. if (avctx->codec->id == AV_CODEC_ID_AV1) {
  1449. /* For AV1 we actually need to calculate the render width/height, not the dar */
  1450. if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0
  1451. && avctx->sample_aspect_ratio.num != avctx->sample_aspect_ratio.den)
  1452. {
  1453. if (avctx->sample_aspect_ratio.num > avctx->sample_aspect_ratio.den) {
  1454. sw = av_rescale(sw, avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  1455. } else {
  1456. sh = av_rescale(sh, avctx->sample_aspect_ratio.den, avctx->sample_aspect_ratio.num);
  1457. }
  1458. }
  1459. *dw = sw;
  1460. *dh = sh;
  1461. return;
  1462. }
  1463. #endif
  1464. if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
  1465. sw *= avctx->sample_aspect_ratio.num;
  1466. sh *= avctx->sample_aspect_ratio.den;
  1467. }
  1468. av_reduce(dw, dh, sw, sh, 1024 * 1024);
  1469. }
  1470. static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
  1471. {
  1472. NvencContext *ctx = avctx->priv_data;
  1473. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1474. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1475. NV_ENC_PRESET_CONFIG preset_config = { 0 };
  1476. NVENCSTATUS nv_status = NV_ENC_SUCCESS;
  1477. AVCPBProperties *cpb_props;
  1478. int res = 0;
  1479. int dw, dh;
  1480. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  1481. ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
  1482. ctx->init_encode_params.encodeHeight = avctx->height;
  1483. ctx->init_encode_params.encodeWidth = avctx->width;
  1484. ctx->init_encode_params.encodeConfig = &ctx->encode_config;
  1485. preset_config.version = NV_ENC_PRESET_CONFIG_VER;
  1486. preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
  1487. #ifdef NVENC_HAVE_NEW_PRESETS
  1488. ctx->init_encode_params.tuningInfo = ctx->tuning_info;
  1489. if (ctx->flags & NVENC_LOSSLESS)
  1490. ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
  1491. else if (ctx->flags & NVENC_LOWLATENCY)
  1492. ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
  1493. nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(ctx->nvencoder,
  1494. ctx->init_encode_params.encodeGUID,
  1495. ctx->init_encode_params.presetGUID,
  1496. ctx->init_encode_params.tuningInfo,
  1497. &preset_config);
  1498. #else
  1499. nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
  1500. ctx->init_encode_params.encodeGUID,
  1501. ctx->init_encode_params.presetGUID,
  1502. &preset_config);
  1503. #endif
  1504. if (nv_status != NV_ENC_SUCCESS)
  1505. return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
  1506. memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
  1507. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  1508. compute_dar(avctx, &dw, &dh);
  1509. ctx->init_encode_params.darHeight = dh;
  1510. ctx->init_encode_params.darWidth = dw;
  1511. if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
  1512. ctx->init_encode_params.frameRateNum = avctx->framerate.num;
  1513. ctx->init_encode_params.frameRateDen = avctx->framerate.den;
  1514. } else {
  1515. ctx->init_encode_params.frameRateNum = avctx->time_base.den;
  1516. FF_DISABLE_DEPRECATION_WARNINGS
  1517. ctx->init_encode_params.frameRateDen = avctx->time_base.num
  1518. #if FF_API_TICKS_PER_FRAME
  1519. * avctx->ticks_per_frame
  1520. #endif
  1521. ;
  1522. FF_ENABLE_DEPRECATION_WARNINGS
  1523. }
  1524. #ifdef NVENC_HAVE_UNIDIR_B
  1525. ctx->init_encode_params.enableUniDirectionalB = ctx->unidir_b;
  1526. #endif
  1527. ctx->init_encode_params.enableEncodeAsync = 0;
  1528. ctx->init_encode_params.enablePTD = 1;
  1529. #ifdef NVENC_HAVE_NEW_PRESETS
  1530. /* If lookahead isn't set from CLI, use value from preset.
  1531. * P6 & P7 presets may enable lookahead for better quality.
  1532. * */
  1533. if (ctx->rc_lookahead == 0 && ctx->encode_config.rcParams.enableLookahead)
  1534. ctx->rc_lookahead = ctx->encode_config.rcParams.lookaheadDepth;
  1535. #endif
  1536. if (ctx->weighted_pred == 1)
  1537. ctx->init_encode_params.enableWeightedPrediction = 1;
  1538. #ifdef NVENC_HAVE_SPLIT_FRAME_ENCODING
  1539. ctx->init_encode_params.splitEncodeMode = ctx->split_encode_mode;
  1540. if (ctx->split_encode_mode != NV_ENC_SPLIT_DISABLE_MODE) {
  1541. if (avctx->codec->id == AV_CODEC_ID_HEVC && ctx->weighted_pred == 1)
  1542. av_log(avctx, AV_LOG_WARNING, "Split encoding not supported with weighted prediction enabled.\n");
  1543. }
  1544. #endif
  1545. if (ctx->bluray_compat) {
  1546. ctx->aud = 1;
  1547. ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
  1548. avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
  1549. switch (avctx->codec->id) {
  1550. case AV_CODEC_ID_H264:
  1551. /* maximum level depends on used resolution */
  1552. break;
  1553. case AV_CODEC_ID_HEVC:
  1554. ctx->level = NV_ENC_LEVEL_HEVC_51;
  1555. ctx->tier = NV_ENC_TIER_HEVC_HIGH;
  1556. break;
  1557. }
  1558. }
  1559. if (avctx->gop_size > 0) {
  1560. // only overwrite preset if a GOP size was selected as input
  1561. ctx->encode_config.gopLength = avctx->gop_size;
  1562. } else if (avctx->gop_size == 0) {
  1563. ctx->encode_config.frameIntervalP = 0;
  1564. ctx->encode_config.gopLength = 1;
  1565. }
  1566. if (avctx->max_b_frames >= 0 && ctx->encode_config.gopLength > 1) {
  1567. /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
  1568. ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
  1569. }
  1570. /* force to enable intra refresh */
  1571. if(ctx->single_slice_intra_refresh)
  1572. ctx->intra_refresh = 1;
  1573. nvenc_recalc_surfaces(avctx);
  1574. res = nvenc_setup_rate_control(avctx);
  1575. if (res < 0)
  1576. return res;
  1577. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  1578. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
  1579. } else {
  1580. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
  1581. }
  1582. res = nvenc_setup_codec_config(avctx);
  1583. if (res)
  1584. return res;
  1585. res = nvenc_push_context(avctx);
  1586. if (res < 0)
  1587. return res;
  1588. nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
  1589. if (nv_status != NV_ENC_SUCCESS) {
  1590. nvenc_pop_context(avctx);
  1591. return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
  1592. }
  1593. #ifdef NVENC_HAVE_CUSTREAM_PTR
  1594. if (ctx->cu_context) {
  1595. nv_status = p_nvenc->nvEncSetIOCudaStreams(ctx->nvencoder, &ctx->cu_stream, &ctx->cu_stream);
  1596. if (nv_status != NV_ENC_SUCCESS) {
  1597. nvenc_pop_context(avctx);
  1598. return nvenc_print_error(avctx, nv_status, "SetIOCudaStreams failed");
  1599. }
  1600. }
  1601. #endif
  1602. res = nvenc_pop_context(avctx);
  1603. if (res < 0)
  1604. return res;
  1605. if (ctx->encode_config.frameIntervalP > 1)
  1606. avctx->has_b_frames = 2;
  1607. if (ctx->encode_config.rcParams.averageBitRate > 0)
  1608. avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
  1609. cpb_props = ff_encode_add_cpb_side_data(avctx);
  1610. if (!cpb_props)
  1611. return AVERROR(ENOMEM);
  1612. cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
  1613. cpb_props->avg_bitrate = avctx->bit_rate;
  1614. cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
  1615. return 0;
  1616. }
  1617. static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
  1618. {
  1619. switch (pix_fmt) {
  1620. case AV_PIX_FMT_YUV420P:
  1621. return NV_ENC_BUFFER_FORMAT_YV12;
  1622. case AV_PIX_FMT_NV12:
  1623. return NV_ENC_BUFFER_FORMAT_NV12;
  1624. case AV_PIX_FMT_P010:
  1625. case AV_PIX_FMT_P016:
  1626. return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
  1627. case AV_PIX_FMT_GBRP:
  1628. case AV_PIX_FMT_YUV444P:
  1629. return NV_ENC_BUFFER_FORMAT_YUV444;
  1630. case AV_PIX_FMT_GBRP16:
  1631. case AV_PIX_FMT_YUV444P16:
  1632. return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
  1633. case AV_PIX_FMT_0RGB32:
  1634. case AV_PIX_FMT_RGB32:
  1635. return NV_ENC_BUFFER_FORMAT_ARGB;
  1636. case AV_PIX_FMT_0BGR32:
  1637. case AV_PIX_FMT_BGR32:
  1638. return NV_ENC_BUFFER_FORMAT_ABGR;
  1639. case AV_PIX_FMT_X2RGB10:
  1640. return NV_ENC_BUFFER_FORMAT_ARGB10;
  1641. case AV_PIX_FMT_X2BGR10:
  1642. return NV_ENC_BUFFER_FORMAT_ABGR10;
  1643. #ifdef NVENC_HAVE_422_SUPPORT
  1644. case AV_PIX_FMT_NV16:
  1645. return NV_ENC_BUFFER_FORMAT_NV16;
  1646. case AV_PIX_FMT_P210:
  1647. case AV_PIX_FMT_P216:
  1648. return NV_ENC_BUFFER_FORMAT_P210;
  1649. #endif
  1650. default:
  1651. return NV_ENC_BUFFER_FORMAT_UNDEFINED;
  1652. }
  1653. }
  1654. static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
  1655. {
  1656. NvencContext *ctx = avctx->priv_data;
  1657. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1658. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1659. NvencSurface* tmp_surface = &ctx->surfaces[idx];
  1660. NVENCSTATUS nv_status;
  1661. NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
  1662. allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
  1663. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1664. ctx->surfaces[idx].in_ref = av_frame_alloc();
  1665. if (!ctx->surfaces[idx].in_ref)
  1666. return AVERROR(ENOMEM);
  1667. } else {
  1668. NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
  1669. ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
  1670. if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
  1671. av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
  1672. av_get_pix_fmt_name(ctx->data_pix_fmt));
  1673. return AVERROR(EINVAL);
  1674. }
  1675. allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
  1676. allocSurf.width = avctx->width;
  1677. allocSurf.height = avctx->height;
  1678. allocSurf.bufferFmt = ctx->surfaces[idx].format;
  1679. nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
  1680. if (nv_status != NV_ENC_SUCCESS) {
  1681. return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
  1682. }
  1683. ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
  1684. ctx->surfaces[idx].width = allocSurf.width;
  1685. ctx->surfaces[idx].height = allocSurf.height;
  1686. }
  1687. nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
  1688. if (nv_status != NV_ENC_SUCCESS) {
  1689. int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
  1690. if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
  1691. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
  1692. av_frame_free(&ctx->surfaces[idx].in_ref);
  1693. return err;
  1694. }
  1695. ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
  1696. av_fifo_write(ctx->unused_surface_queue, &tmp_surface, 1);
  1697. return 0;
  1698. }
  1699. static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
  1700. {
  1701. NvencContext *ctx = avctx->priv_data;
  1702. int i, res = 0, res2;
  1703. ctx->surfaces = av_calloc(ctx->nb_surfaces, sizeof(*ctx->surfaces));
  1704. if (!ctx->surfaces)
  1705. return AVERROR(ENOMEM);
  1706. ctx->frame_data_array = av_calloc(ctx->frame_data_array_nb, sizeof(*ctx->frame_data_array));
  1707. if (!ctx->frame_data_array)
  1708. return AVERROR(ENOMEM);
  1709. ctx->timestamp_list = av_fifo_alloc2(ctx->nb_surfaces + ctx->encode_config.frameIntervalP,
  1710. sizeof(int64_t), 0);
  1711. if (!ctx->timestamp_list)
  1712. return AVERROR(ENOMEM);
  1713. ctx->unused_surface_queue = av_fifo_alloc2(ctx->nb_surfaces, sizeof(NvencSurface*), 0);
  1714. if (!ctx->unused_surface_queue)
  1715. return AVERROR(ENOMEM);
  1716. ctx->output_surface_queue = av_fifo_alloc2(ctx->nb_surfaces, sizeof(NvencSurface*), 0);
  1717. if (!ctx->output_surface_queue)
  1718. return AVERROR(ENOMEM);
  1719. ctx->output_surface_ready_queue = av_fifo_alloc2(ctx->nb_surfaces, sizeof(NvencSurface*), 0);
  1720. if (!ctx->output_surface_ready_queue)
  1721. return AVERROR(ENOMEM);
  1722. res = nvenc_push_context(avctx);
  1723. if (res < 0)
  1724. return res;
  1725. for (i = 0; i < ctx->nb_surfaces; i++) {
  1726. if ((res = nvenc_alloc_surface(avctx, i)) < 0)
  1727. goto fail;
  1728. }
  1729. fail:
  1730. res2 = nvenc_pop_context(avctx);
  1731. if (res2 < 0)
  1732. return res2;
  1733. return res;
  1734. }
  1735. static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
  1736. {
  1737. NvencContext *ctx = avctx->priv_data;
  1738. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1739. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1740. NVENCSTATUS nv_status;
  1741. uint32_t outSize = 0;
  1742. char tmpHeader[NV_MAX_SEQ_HDR_LEN];
  1743. NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
  1744. payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
  1745. payload.spsppsBuffer = tmpHeader;
  1746. payload.inBufferSize = sizeof(tmpHeader);
  1747. payload.outSPSPPSPayloadSize = &outSize;
  1748. nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
  1749. if (nv_status != NV_ENC_SUCCESS) {
  1750. return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
  1751. }
  1752. avctx->extradata_size = outSize;
  1753. avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
  1754. if (!avctx->extradata) {
  1755. return AVERROR(ENOMEM);
  1756. }
  1757. memcpy(avctx->extradata, tmpHeader, outSize);
  1758. return 0;
  1759. }
  1760. av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
  1761. {
  1762. NvencContext *ctx = avctx->priv_data;
  1763. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1764. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1765. int i, res;
  1766. /* the encoder has to be flushed before it can be closed */
  1767. if (ctx->nvencoder) {
  1768. NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
  1769. .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
  1770. res = nvenc_push_context(avctx);
  1771. if (res < 0)
  1772. return res;
  1773. p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
  1774. }
  1775. av_fifo_freep2(&ctx->timestamp_list);
  1776. av_fifo_freep2(&ctx->output_surface_ready_queue);
  1777. av_fifo_freep2(&ctx->output_surface_queue);
  1778. av_fifo_freep2(&ctx->unused_surface_queue);
  1779. if (ctx->frame_data_array) {
  1780. for (i = 0; i < ctx->frame_data_array_nb; i++)
  1781. av_buffer_unref(&ctx->frame_data_array[i].frame_opaque_ref);
  1782. av_freep(&ctx->frame_data_array);
  1783. }
  1784. if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
  1785. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1786. if (ctx->registered_frames[i].mapped)
  1787. p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
  1788. if (ctx->registered_frames[i].regptr)
  1789. p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
  1790. }
  1791. ctx->nb_registered_frames = 0;
  1792. }
  1793. if (ctx->surfaces) {
  1794. for (i = 0; i < ctx->nb_surfaces; ++i) {
  1795. if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
  1796. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
  1797. av_frame_free(&ctx->surfaces[i].in_ref);
  1798. p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
  1799. }
  1800. }
  1801. av_freep(&ctx->surfaces);
  1802. ctx->nb_surfaces = 0;
  1803. av_frame_free(&ctx->frame);
  1804. av_freep(&ctx->sei_data);
  1805. if (ctx->nvencoder) {
  1806. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  1807. res = nvenc_pop_context(avctx);
  1808. if (res < 0)
  1809. return res;
  1810. }
  1811. ctx->nvencoder = NULL;
  1812. if (ctx->cu_context_internal)
  1813. CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
  1814. ctx->cu_context = ctx->cu_context_internal = NULL;
  1815. #if CONFIG_D3D11VA
  1816. if (ctx->d3d11_device) {
  1817. ID3D11Device_Release(ctx->d3d11_device);
  1818. ctx->d3d11_device = NULL;
  1819. }
  1820. #endif
  1821. nvenc_free_functions(&dl_fn->nvenc_dl);
  1822. cuda_free_functions(&dl_fn->cuda_dl);
  1823. dl_fn->nvenc_device_count = 0;
  1824. av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
  1825. return 0;
  1826. }
  1827. av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
  1828. {
  1829. NvencContext *ctx = avctx->priv_data;
  1830. int ret;
  1831. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1832. AVHWFramesContext *frames_ctx;
  1833. if (!avctx->hw_frames_ctx) {
  1834. av_log(avctx, AV_LOG_ERROR,
  1835. "hw_frames_ctx must be set when using GPU frames as input\n");
  1836. return AVERROR(EINVAL);
  1837. }
  1838. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1839. if (frames_ctx->format != avctx->pix_fmt) {
  1840. av_log(avctx, AV_LOG_ERROR,
  1841. "hw_frames_ctx must match the GPU frame type\n");
  1842. return AVERROR(EINVAL);
  1843. }
  1844. ctx->data_pix_fmt = frames_ctx->sw_format;
  1845. } else {
  1846. ctx->data_pix_fmt = avctx->pix_fmt;
  1847. }
  1848. if (ctx->rgb_mode == NVENC_RGB_MODE_DISABLED && IS_RGB(ctx->data_pix_fmt)) {
  1849. av_log(avctx, AV_LOG_ERROR, "Packed RGB input, but RGB support is disabled.\n");
  1850. return AVERROR(EINVAL);
  1851. }
  1852. ctx->frame = av_frame_alloc();
  1853. if (!ctx->frame)
  1854. return AVERROR(ENOMEM);
  1855. if ((ret = nvenc_load_libraries(avctx)) < 0)
  1856. return ret;
  1857. if ((ret = nvenc_setup_device(avctx)) < 0)
  1858. return ret;
  1859. if ((ret = nvenc_setup_encoder(avctx)) < 0)
  1860. return ret;
  1861. if ((ret = nvenc_setup_surfaces(avctx)) < 0)
  1862. return ret;
  1863. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  1864. if ((ret = nvenc_setup_extradata(avctx)) < 0)
  1865. return ret;
  1866. }
  1867. return 0;
  1868. }
  1869. static NvencSurface *get_free_frame(NvencContext *ctx)
  1870. {
  1871. NvencSurface *tmp_surf;
  1872. if (av_fifo_read(ctx->unused_surface_queue, &tmp_surf, 1) < 0)
  1873. // queue empty
  1874. return NULL;
  1875. return tmp_surf;
  1876. }
  1877. static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
  1878. NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
  1879. {
  1880. int dst_linesize[4] = {
  1881. lock_buffer_params->pitch,
  1882. lock_buffer_params->pitch,
  1883. lock_buffer_params->pitch,
  1884. lock_buffer_params->pitch
  1885. };
  1886. uint8_t *dst_data[4];
  1887. int ret;
  1888. if (frame->format == AV_PIX_FMT_YUV420P)
  1889. dst_linesize[1] = dst_linesize[2] >>= 1;
  1890. ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
  1891. lock_buffer_params->bufferDataPtr, dst_linesize);
  1892. if (ret < 0)
  1893. return ret;
  1894. if (frame->format == AV_PIX_FMT_YUV420P)
  1895. FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
  1896. av_image_copy2(dst_data, dst_linesize,
  1897. frame->data, frame->linesize, frame->format,
  1898. avctx->width, avctx->height);
  1899. return 0;
  1900. }
  1901. static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
  1902. {
  1903. NvencContext *ctx = avctx->priv_data;
  1904. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1905. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1906. NVENCSTATUS nv_status;
  1907. int i, first_round;
  1908. if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
  1909. for (first_round = 1; first_round >= 0; first_round--) {
  1910. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1911. if (!ctx->registered_frames[i].mapped) {
  1912. if (ctx->registered_frames[i].regptr) {
  1913. if (first_round)
  1914. continue;
  1915. nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
  1916. if (nv_status != NV_ENC_SUCCESS)
  1917. return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
  1918. ctx->registered_frames[i].ptr = NULL;
  1919. ctx->registered_frames[i].regptr = NULL;
  1920. }
  1921. return i;
  1922. }
  1923. }
  1924. }
  1925. } else {
  1926. return ctx->nb_registered_frames++;
  1927. }
  1928. av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
  1929. return AVERROR(ENOMEM);
  1930. }
  1931. static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
  1932. {
  1933. NvencContext *ctx = avctx->priv_data;
  1934. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1935. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1936. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
  1937. NV_ENC_REGISTER_RESOURCE reg = { 0 };
  1938. int i, idx, ret;
  1939. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1940. if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
  1941. return i;
  1942. else if (avctx->pix_fmt == AV_PIX_FMT_D3D11 && ctx->registered_frames[i].ptr == frame->data[0] && ctx->registered_frames[i].ptr_index == (intptr_t)frame->data[1])
  1943. return i;
  1944. }
  1945. idx = nvenc_find_free_reg_resource(avctx);
  1946. if (idx < 0)
  1947. return idx;
  1948. reg.version = NV_ENC_REGISTER_RESOURCE_VER;
  1949. reg.width = frames_ctx->width;
  1950. reg.height = frames_ctx->height;
  1951. reg.pitch = frame->linesize[0];
  1952. reg.resourceToRegister = frame->data[0];
  1953. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  1954. reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
  1955. }
  1956. else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1957. reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
  1958. reg.subResourceIndex = (intptr_t)frame->data[1];
  1959. }
  1960. reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
  1961. if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
  1962. av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
  1963. av_get_pix_fmt_name(frames_ctx->sw_format));
  1964. return AVERROR(EINVAL);
  1965. }
  1966. ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
  1967. if (ret != NV_ENC_SUCCESS) {
  1968. nvenc_print_error(avctx, ret, "Error registering an input resource");
  1969. return AVERROR_UNKNOWN;
  1970. }
  1971. ctx->registered_frames[idx].ptr = frame->data[0];
  1972. ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
  1973. ctx->registered_frames[idx].regptr = reg.registeredResource;
  1974. return idx;
  1975. }
  1976. static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
  1977. NvencSurface *nvenc_frame)
  1978. {
  1979. NvencContext *ctx = avctx->priv_data;
  1980. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1981. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1982. int res;
  1983. NVENCSTATUS nv_status;
  1984. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1985. int reg_idx = nvenc_register_frame(avctx, frame);
  1986. if (reg_idx < 0) {
  1987. av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
  1988. return reg_idx;
  1989. }
  1990. res = av_frame_ref(nvenc_frame->in_ref, frame);
  1991. if (res < 0)
  1992. return res;
  1993. if (!ctx->registered_frames[reg_idx].mapped) {
  1994. ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
  1995. ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
  1996. nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
  1997. if (nv_status != NV_ENC_SUCCESS) {
  1998. av_frame_unref(nvenc_frame->in_ref);
  1999. return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
  2000. }
  2001. }
  2002. ctx->registered_frames[reg_idx].mapped += 1;
  2003. nvenc_frame->reg_idx = reg_idx;
  2004. nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
  2005. nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
  2006. nvenc_frame->pitch = frame->linesize[0];
  2007. return 0;
  2008. } else {
  2009. NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
  2010. lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
  2011. lockBufferParams.inputBuffer = nvenc_frame->input_surface;
  2012. nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
  2013. if (nv_status != NV_ENC_SUCCESS) {
  2014. return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
  2015. }
  2016. nvenc_frame->pitch = lockBufferParams.pitch;
  2017. res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
  2018. nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
  2019. if (nv_status != NV_ENC_SUCCESS) {
  2020. return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
  2021. }
  2022. return res;
  2023. }
  2024. }
  2025. static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
  2026. NV_ENC_PIC_PARAMS *params,
  2027. NV_ENC_SEI_PAYLOAD *sei_data,
  2028. int sei_count)
  2029. {
  2030. NvencContext *ctx = avctx->priv_data;
  2031. switch (avctx->codec->id) {
  2032. case AV_CODEC_ID_H264:
  2033. params->codecPicParams.h264PicParams.sliceMode =
  2034. ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
  2035. params->codecPicParams.h264PicParams.sliceModeData =
  2036. ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
  2037. if (sei_count > 0) {
  2038. params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
  2039. params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
  2040. }
  2041. break;
  2042. case AV_CODEC_ID_HEVC:
  2043. params->codecPicParams.hevcPicParams.sliceMode =
  2044. ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
  2045. params->codecPicParams.hevcPicParams.sliceModeData =
  2046. ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
  2047. if (sei_count > 0) {
  2048. params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
  2049. params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
  2050. }
  2051. break;
  2052. #if CONFIG_AV1_NVENC_ENCODER
  2053. case AV_CODEC_ID_AV1:
  2054. params->codecPicParams.av1PicParams.numTileColumns =
  2055. ctx->encode_config.encodeCodecConfig.av1Config.numTileColumns;
  2056. params->codecPicParams.av1PicParams.numTileRows =
  2057. ctx->encode_config.encodeCodecConfig.av1Config.numTileRows;
  2058. if (sei_count > 0) {
  2059. params->codecPicParams.av1PicParams.obuPayloadArray = sei_data;
  2060. params->codecPicParams.av1PicParams.obuPayloadArrayCnt = sei_count;
  2061. }
  2062. break;
  2063. #endif
  2064. }
  2065. }
  2066. static inline void timestamp_queue_enqueue(AVFifo *queue, int64_t timestamp)
  2067. {
  2068. av_fifo_write(queue, &timestamp, 1);
  2069. }
  2070. static inline int64_t timestamp_queue_dequeue(AVFifo *queue)
  2071. {
  2072. int64_t timestamp = AV_NOPTS_VALUE;
  2073. // The following call might fail if the queue is empty.
  2074. av_fifo_read(queue, &timestamp, 1);
  2075. return timestamp;
  2076. }
  2077. static inline int64_t timestamp_queue_peek(AVFifo *queue, size_t index)
  2078. {
  2079. int64_t timestamp = AV_NOPTS_VALUE;
  2080. av_fifo_peek(queue, &timestamp, 1, index);
  2081. return timestamp;
  2082. }
  2083. static int nvenc_set_timestamp(AVCodecContext *avctx,
  2084. NV_ENC_LOCK_BITSTREAM *params,
  2085. AVPacket *pkt)
  2086. {
  2087. NvencContext *ctx = avctx->priv_data;
  2088. unsigned int delay;
  2089. int64_t delay_time;
  2090. pkt->pts = params->outputTimeStamp;
  2091. if (!(avctx->codec_descriptor->props & AV_CODEC_PROP_REORDER)) {
  2092. pkt->dts = pkt->pts;
  2093. return 0;
  2094. }
  2095. // This can be more than necessary, but we don't know the real reorder delay.
  2096. delay = FFMAX(ctx->encode_config.frameIntervalP - 1, 0);
  2097. if (ctx->output_frame_num >= delay) {
  2098. pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
  2099. ctx->output_frame_num++;
  2100. return 0;
  2101. }
  2102. delay_time = ctx->initial_delay_time;
  2103. if (!delay_time) {
  2104. int64_t t1, t2, t3;
  2105. t1 = timestamp_queue_peek(ctx->timestamp_list, delay);
  2106. t2 = timestamp_queue_peek(ctx->timestamp_list, 0);
  2107. t3 = (delay > 1) ? timestamp_queue_peek(ctx->timestamp_list, 1) : t1;
  2108. if (t1 != AV_NOPTS_VALUE) {
  2109. delay_time = t1 - t2;
  2110. } else if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
  2111. delay_time = av_rescale_q(delay, (AVRational) {avctx->framerate.den, avctx->framerate.num},
  2112. avctx->time_base);
  2113. } else if (t3 != AV_NOPTS_VALUE) {
  2114. delay_time = delay * (t3 - t2);
  2115. } else {
  2116. delay_time = delay;
  2117. }
  2118. ctx->initial_delay_time = delay_time;
  2119. }
  2120. /* The following method is simple, but doesn't guarantee monotonic with VFR
  2121. * when delay_time isn't accurate (that is, t1 == AV_NOPTS_VALUE)
  2122. *
  2123. * dts = timestamp_queue_peek(ctx->timestamp_list, ctx->output_frame_num) - delay_time
  2124. */
  2125. pkt->dts = timestamp_queue_peek(ctx->timestamp_list, 0) - delay_time * (delay - ctx->output_frame_num) / delay;
  2126. ctx->output_frame_num++;
  2127. return 0;
  2128. }
  2129. static int nvenc_store_frame_data(AVCodecContext *avctx, NV_ENC_PIC_PARAMS *pic_params, const AVFrame *frame)
  2130. {
  2131. NvencContext *ctx = avctx->priv_data;
  2132. int res = 0;
  2133. int idx = ctx->frame_data_array_pos;
  2134. NvencFrameData *frame_data = &ctx->frame_data_array[idx];
  2135. // in case the encoder got reconfigured, there might be leftovers
  2136. av_buffer_unref(&frame_data->frame_opaque_ref);
  2137. if (frame->opaque_ref && avctx->flags & AV_CODEC_FLAG_COPY_OPAQUE) {
  2138. frame_data->frame_opaque_ref = av_buffer_ref(frame->opaque_ref);
  2139. if (!frame_data->frame_opaque_ref)
  2140. return AVERROR(ENOMEM);
  2141. }
  2142. frame_data->duration = frame->duration;
  2143. frame_data->frame_opaque = frame->opaque;
  2144. ctx->frame_data_array_pos = (ctx->frame_data_array_pos + 1) % ctx->frame_data_array_nb;
  2145. pic_params->inputDuration = idx;
  2146. return res;
  2147. }
  2148. static int nvenc_retrieve_frame_data(AVCodecContext *avctx, NV_ENC_LOCK_BITSTREAM *lock_params, AVPacket *pkt)
  2149. {
  2150. NvencContext *ctx = avctx->priv_data;
  2151. int res = 0;
  2152. int idx = lock_params->outputDuration;
  2153. NvencFrameData *frame_data = &ctx->frame_data_array[idx];
  2154. pkt->duration = frame_data->duration;
  2155. if (avctx->flags & AV_CODEC_FLAG_COPY_OPAQUE) {
  2156. pkt->opaque = frame_data->frame_opaque;
  2157. pkt->opaque_ref = frame_data->frame_opaque_ref;
  2158. frame_data->frame_opaque_ref = NULL;
  2159. }
  2160. av_buffer_unref(&frame_data->frame_opaque_ref);
  2161. return res;
  2162. }
  2163. static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
  2164. {
  2165. NvencContext *ctx = avctx->priv_data;
  2166. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  2167. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  2168. NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
  2169. NVENCSTATUS nv_status;
  2170. int res = 0;
  2171. enum AVPictureType pict_type;
  2172. lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
  2173. lock_params.doNotWait = 0;
  2174. lock_params.outputBitstream = tmpoutsurf->output_surface;
  2175. nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
  2176. if (nv_status != NV_ENC_SUCCESS) {
  2177. res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
  2178. goto error;
  2179. }
  2180. res = ff_get_encode_buffer(avctx, pkt, lock_params.bitstreamSizeInBytes, 0);
  2181. if (res < 0) {
  2182. p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  2183. goto error;
  2184. }
  2185. memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
  2186. nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  2187. if (nv_status != NV_ENC_SUCCESS) {
  2188. res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
  2189. goto error;
  2190. }
  2191. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  2192. ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
  2193. if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
  2194. nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
  2195. if (nv_status != NV_ENC_SUCCESS) {
  2196. res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
  2197. goto error;
  2198. }
  2199. } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
  2200. res = AVERROR_BUG;
  2201. goto error;
  2202. }
  2203. av_frame_unref(tmpoutsurf->in_ref);
  2204. tmpoutsurf->input_surface = NULL;
  2205. }
  2206. switch (lock_params.pictureType) {
  2207. case NV_ENC_PIC_TYPE_IDR:
  2208. pkt->flags |= AV_PKT_FLAG_KEY;
  2209. case NV_ENC_PIC_TYPE_I:
  2210. pict_type = AV_PICTURE_TYPE_I;
  2211. break;
  2212. case NV_ENC_PIC_TYPE_P:
  2213. pict_type = AV_PICTURE_TYPE_P;
  2214. break;
  2215. case NV_ENC_PIC_TYPE_B:
  2216. pict_type = AV_PICTURE_TYPE_B;
  2217. break;
  2218. case NV_ENC_PIC_TYPE_BI:
  2219. pict_type = AV_PICTURE_TYPE_BI;
  2220. break;
  2221. default:
  2222. av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
  2223. av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
  2224. res = AVERROR_EXTERNAL;
  2225. goto error;
  2226. }
  2227. ff_side_data_set_encoder_stats(pkt,
  2228. (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
  2229. res = nvenc_set_timestamp(avctx, &lock_params, pkt);
  2230. if (res < 0)
  2231. goto error2;
  2232. res = nvenc_retrieve_frame_data(avctx, &lock_params, pkt);
  2233. if (res < 0)
  2234. goto error2;
  2235. return 0;
  2236. error:
  2237. timestamp_queue_dequeue(ctx->timestamp_list);
  2238. error2:
  2239. return res;
  2240. }
  2241. static int output_ready(AVCodecContext *avctx, int flush)
  2242. {
  2243. NvencContext *ctx = avctx->priv_data;
  2244. int nb_ready, nb_pending;
  2245. nb_ready = av_fifo_can_read(ctx->output_surface_ready_queue);
  2246. nb_pending = av_fifo_can_read(ctx->output_surface_queue);
  2247. if (flush)
  2248. return nb_ready > 0;
  2249. return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
  2250. }
  2251. static int prepare_sei_data_array(AVCodecContext *avctx, const AVFrame *frame)
  2252. {
  2253. NvencContext *ctx = avctx->priv_data;
  2254. int sei_count = 0;
  2255. int i, res;
  2256. if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
  2257. void *a53_data = NULL;
  2258. size_t a53_size = 0;
  2259. if (ff_alloc_a53_sei(frame, 0, &a53_data, &a53_size) < 0) {
  2260. av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
  2261. }
  2262. if (a53_data) {
  2263. void *tmp = av_fast_realloc(ctx->sei_data,
  2264. &ctx->sei_data_size,
  2265. (sei_count + 1) * sizeof(*ctx->sei_data));
  2266. if (!tmp) {
  2267. av_free(a53_data);
  2268. res = AVERROR(ENOMEM);
  2269. goto error;
  2270. } else {
  2271. ctx->sei_data = tmp;
  2272. ctx->sei_data[sei_count].payloadSize = (uint32_t)a53_size;
  2273. ctx->sei_data[sei_count].payload = (uint8_t*)a53_data;
  2274. #if CONFIG_AV1_NVENC_ENCODER
  2275. if (avctx->codec->id == AV_CODEC_ID_AV1)
  2276. ctx->sei_data[sei_count].payloadType = AV1_METADATA_TYPE_ITUT_T35;
  2277. else
  2278. #endif
  2279. ctx->sei_data[sei_count].payloadType = SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35;
  2280. sei_count++;
  2281. }
  2282. }
  2283. }
  2284. if (ctx->s12m_tc && av_frame_get_side_data(frame, AV_FRAME_DATA_S12M_TIMECODE)) {
  2285. void *tc_data = NULL;
  2286. size_t tc_size = 0;
  2287. if (ff_alloc_timecode_sei(frame, avctx->framerate, 0, &tc_data, &tc_size) < 0) {
  2288. av_log(ctx, AV_LOG_ERROR, "Not enough memory for timecode sei, skipping\n");
  2289. }
  2290. if (tc_data) {
  2291. void *tmp = av_fast_realloc(ctx->sei_data,
  2292. &ctx->sei_data_size,
  2293. (sei_count + 1) * sizeof(*ctx->sei_data));
  2294. if (!tmp) {
  2295. av_free(tc_data);
  2296. res = AVERROR(ENOMEM);
  2297. goto error;
  2298. } else {
  2299. ctx->sei_data = tmp;
  2300. ctx->sei_data[sei_count].payloadSize = (uint32_t)tc_size;
  2301. ctx->sei_data[sei_count].payload = (uint8_t*)tc_data;
  2302. #if CONFIG_AV1_NVENC_ENCODER
  2303. if (avctx->codec->id == AV_CODEC_ID_AV1)
  2304. ctx->sei_data[sei_count].payloadType = AV1_METADATA_TYPE_TIMECODE;
  2305. else
  2306. #endif
  2307. ctx->sei_data[sei_count].payloadType = SEI_TYPE_TIME_CODE;
  2308. sei_count++;
  2309. }
  2310. }
  2311. }
  2312. if (!ctx->udu_sei)
  2313. return sei_count;
  2314. for (i = 0; i < frame->nb_side_data; i++) {
  2315. AVFrameSideData *side_data = frame->side_data[i];
  2316. void *tmp;
  2317. if (side_data->type != AV_FRAME_DATA_SEI_UNREGISTERED)
  2318. continue;
  2319. tmp = av_fast_realloc(ctx->sei_data,
  2320. &ctx->sei_data_size,
  2321. (sei_count + 1) * sizeof(*ctx->sei_data));
  2322. if (!tmp) {
  2323. res = AVERROR(ENOMEM);
  2324. goto error;
  2325. } else {
  2326. ctx->sei_data = tmp;
  2327. ctx->sei_data[sei_count].payloadSize = side_data->size;
  2328. ctx->sei_data[sei_count].payloadType = SEI_TYPE_USER_DATA_UNREGISTERED;
  2329. ctx->sei_data[sei_count].payload = av_memdup(side_data->data, side_data->size);
  2330. if (!ctx->sei_data[sei_count].payload) {
  2331. res = AVERROR(ENOMEM);
  2332. goto error;
  2333. }
  2334. sei_count++;
  2335. }
  2336. }
  2337. return sei_count;
  2338. error:
  2339. for (i = 0; i < sei_count; i++)
  2340. av_freep(&(ctx->sei_data[i].payload));
  2341. return res;
  2342. }
  2343. static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
  2344. {
  2345. NvencContext *ctx = avctx->priv_data;
  2346. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  2347. NVENCSTATUS ret;
  2348. NV_ENC_RECONFIGURE_PARAMS params = { 0 };
  2349. int needs_reconfig = 0;
  2350. int needs_encode_config = 0;
  2351. int reconfig_bitrate = 0, reconfig_dar = 0;
  2352. int dw, dh;
  2353. params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
  2354. params.reInitEncodeParams = ctx->init_encode_params;
  2355. compute_dar(avctx, &dw, &dh);
  2356. if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
  2357. av_log(avctx, AV_LOG_VERBOSE,
  2358. "aspect ratio change (DAR): %d:%d -> %d:%d\n",
  2359. ctx->init_encode_params.darWidth,
  2360. ctx->init_encode_params.darHeight, dw, dh);
  2361. params.reInitEncodeParams.darHeight = dh;
  2362. params.reInitEncodeParams.darWidth = dw;
  2363. needs_reconfig = 1;
  2364. reconfig_dar = 1;
  2365. }
  2366. if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
  2367. if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
  2368. av_log(avctx, AV_LOG_VERBOSE,
  2369. "avg bitrate change: %d -> %d\n",
  2370. params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
  2371. (uint32_t)avctx->bit_rate);
  2372. params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
  2373. reconfig_bitrate = 1;
  2374. }
  2375. if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
  2376. av_log(avctx, AV_LOG_VERBOSE,
  2377. "max bitrate change: %d -> %d\n",
  2378. params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
  2379. (uint32_t)avctx->rc_max_rate);
  2380. params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
  2381. reconfig_bitrate = 1;
  2382. }
  2383. if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
  2384. av_log(avctx, AV_LOG_VERBOSE,
  2385. "vbv buffer size change: %d -> %d\n",
  2386. params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
  2387. avctx->rc_buffer_size);
  2388. params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
  2389. reconfig_bitrate = 1;
  2390. }
  2391. if (reconfig_bitrate) {
  2392. params.resetEncoder = 1;
  2393. params.forceIDR = 1;
  2394. needs_encode_config = 1;
  2395. needs_reconfig = 1;
  2396. }
  2397. }
  2398. if (!needs_encode_config)
  2399. params.reInitEncodeParams.encodeConfig = NULL;
  2400. if (needs_reconfig) {
  2401. ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, &params);
  2402. if (ret != NV_ENC_SUCCESS) {
  2403. nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
  2404. } else {
  2405. if (reconfig_dar) {
  2406. ctx->init_encode_params.darHeight = dh;
  2407. ctx->init_encode_params.darWidth = dw;
  2408. }
  2409. if (reconfig_bitrate) {
  2410. ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
  2411. ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
  2412. ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
  2413. }
  2414. }
  2415. }
  2416. }
  2417. static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
  2418. {
  2419. NVENCSTATUS nv_status;
  2420. NvencSurface *tmp_out_surf, *in_surf;
  2421. int res, res2;
  2422. int sei_count = 0;
  2423. int i;
  2424. #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
  2425. MASTERING_DISPLAY_INFO mastering_disp_info = { 0 };
  2426. CONTENT_LIGHT_LEVEL content_light_level = { 0 };
  2427. #endif
  2428. NvencContext *ctx = avctx->priv_data;
  2429. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  2430. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  2431. NV_ENC_PIC_PARAMS pic_params = { 0 };
  2432. pic_params.version = NV_ENC_PIC_PARAMS_VER;
  2433. if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
  2434. return AVERROR(EINVAL);
  2435. if (frame && frame->buf[0]) {
  2436. in_surf = get_free_frame(ctx);
  2437. if (!in_surf)
  2438. return AVERROR(EAGAIN);
  2439. res = nvenc_push_context(avctx);
  2440. if (res < 0)
  2441. return res;
  2442. reconfig_encoder(avctx, frame);
  2443. res = nvenc_upload_frame(avctx, frame, in_surf);
  2444. res2 = nvenc_pop_context(avctx);
  2445. if (res2 < 0)
  2446. return res2;
  2447. if (res)
  2448. return res;
  2449. pic_params.inputBuffer = in_surf->input_surface;
  2450. pic_params.bufferFmt = in_surf->format;
  2451. pic_params.inputWidth = in_surf->width;
  2452. pic_params.inputHeight = in_surf->height;
  2453. pic_params.inputPitch = in_surf->pitch;
  2454. pic_params.outputBitstream = in_surf->output_surface;
  2455. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  2456. if (frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST)
  2457. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
  2458. else
  2459. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
  2460. } else {
  2461. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
  2462. }
  2463. if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
  2464. pic_params.encodePicFlags =
  2465. ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
  2466. } else {
  2467. pic_params.encodePicFlags = 0;
  2468. }
  2469. pic_params.frameIdx = ctx->frame_idx_counter++;
  2470. pic_params.inputTimeStamp = frame->pts;
  2471. if (ctx->extra_sei) {
  2472. res = prepare_sei_data_array(avctx, frame);
  2473. if (res < 0)
  2474. return res;
  2475. sei_count = res;
  2476. }
  2477. #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
  2478. if (ctx->mdm || ctx->cll) {
  2479. const AVFrameSideData *sd_mdm = av_frame_get_side_data(frame, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
  2480. const AVFrameSideData *sd_cll = av_frame_get_side_data(frame, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
  2481. const int chroma_den = (avctx->codec->id == AV_CODEC_ID_AV1) ? 1 << 16 : 50000;
  2482. const int max_luma_den = (avctx->codec->id == AV_CODEC_ID_AV1) ? 1 << 8 : 10000;
  2483. const int min_luma_den = (avctx->codec->id == AV_CODEC_ID_AV1) ? 1 << 14 : 10000;
  2484. if (!sd_mdm)
  2485. sd_mdm = av_frame_side_data_get(avctx->decoded_side_data,
  2486. avctx->nb_decoded_side_data,
  2487. AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
  2488. if (!sd_cll)
  2489. sd_cll = av_frame_side_data_get(avctx->decoded_side_data,
  2490. avctx->nb_decoded_side_data,
  2491. AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
  2492. if (sd_mdm) {
  2493. const AVMasteringDisplayMetadata *mdm = (AVMasteringDisplayMetadata *)sd_mdm->data;
  2494. mastering_disp_info.r.x = av_rescale(mdm->display_primaries[0][0].num, chroma_den,
  2495. mdm->display_primaries[0][0].den);
  2496. mastering_disp_info.r.y = av_rescale(mdm->display_primaries[0][1].num, chroma_den,
  2497. mdm->display_primaries[0][1].den);
  2498. mastering_disp_info.g.x = av_rescale(mdm->display_primaries[1][0].num, chroma_den,
  2499. mdm->display_primaries[1][0].den);
  2500. mastering_disp_info.g.y = av_rescale(mdm->display_primaries[1][1].num, chroma_den,
  2501. mdm->display_primaries[1][1].den);
  2502. mastering_disp_info.b.x = av_rescale(mdm->display_primaries[2][0].num, chroma_den,
  2503. mdm->display_primaries[2][0].den);
  2504. mastering_disp_info.b.y = av_rescale(mdm->display_primaries[2][1].num, chroma_den,
  2505. mdm->display_primaries[2][1].den);
  2506. mastering_disp_info.whitePoint.x = av_rescale(mdm->white_point[0].num, chroma_den,
  2507. mdm->white_point[0].den);
  2508. mastering_disp_info.whitePoint.y = av_rescale(mdm->white_point[1].num, chroma_den,
  2509. mdm->white_point[1].den);
  2510. mastering_disp_info.maxLuma = av_rescale(mdm->max_luminance.num, max_luma_den,
  2511. mdm->max_luminance.den);
  2512. mastering_disp_info.minLuma = av_rescale(mdm->min_luminance.num, min_luma_den,
  2513. mdm->min_luminance.den);
  2514. if (avctx->codec->id == AV_CODEC_ID_HEVC)
  2515. pic_params.codecPicParams.hevcPicParams.pMasteringDisplay = &mastering_disp_info;
  2516. else if (avctx->codec->id == AV_CODEC_ID_AV1)
  2517. pic_params.codecPicParams.av1PicParams.pMasteringDisplay = &mastering_disp_info;
  2518. else
  2519. return AVERROR_BUG;
  2520. }
  2521. if (sd_cll) {
  2522. const AVContentLightMetadata *cll = (AVContentLightMetadata *)sd_cll->data;
  2523. content_light_level.maxContentLightLevel = cll->MaxCLL;
  2524. content_light_level.maxPicAverageLightLevel = cll->MaxFALL;
  2525. if (avctx->codec->id == AV_CODEC_ID_HEVC)
  2526. pic_params.codecPicParams.hevcPicParams.pMaxCll = &content_light_level;
  2527. else if (avctx->codec->id == AV_CODEC_ID_AV1)
  2528. pic_params.codecPicParams.av1PicParams.pMaxCll = &content_light_level;
  2529. else
  2530. return AVERROR_BUG;
  2531. }
  2532. }
  2533. #endif
  2534. res = nvenc_store_frame_data(avctx, &pic_params, frame);
  2535. if (res < 0)
  2536. return res;
  2537. nvenc_codec_specific_pic_params(avctx, &pic_params, ctx->sei_data, sei_count);
  2538. } else {
  2539. pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
  2540. }
  2541. res = nvenc_push_context(avctx);
  2542. if (res < 0)
  2543. return res;
  2544. nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
  2545. for (i = 0; i < sei_count; i++)
  2546. av_freep(&(ctx->sei_data[i].payload));
  2547. res = nvenc_pop_context(avctx);
  2548. if (res < 0)
  2549. return res;
  2550. if (nv_status != NV_ENC_SUCCESS &&
  2551. nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
  2552. return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
  2553. if (frame && frame->buf[0]) {
  2554. av_fifo_write(ctx->output_surface_queue, &in_surf, 1);
  2555. if (avctx->codec_descriptor->props & AV_CODEC_PROP_REORDER)
  2556. timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
  2557. }
  2558. /* all the pending buffers are now ready for output */
  2559. if (nv_status == NV_ENC_SUCCESS) {
  2560. while (av_fifo_read(ctx->output_surface_queue, &tmp_out_surf, 1) >= 0)
  2561. av_fifo_write(ctx->output_surface_ready_queue, &tmp_out_surf, 1);
  2562. }
  2563. return 0;
  2564. }
  2565. int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
  2566. {
  2567. NvencSurface *tmp_out_surf;
  2568. int res, res2;
  2569. NvencContext *ctx = avctx->priv_data;
  2570. AVFrame *frame = ctx->frame;
  2571. if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
  2572. return AVERROR(EINVAL);
  2573. if (!frame->buf[0]) {
  2574. res = ff_encode_get_frame(avctx, frame);
  2575. if (res < 0 && res != AVERROR_EOF)
  2576. return res;
  2577. }
  2578. res = nvenc_send_frame(avctx, frame);
  2579. if (res < 0) {
  2580. if (res != AVERROR(EAGAIN))
  2581. return res;
  2582. } else
  2583. av_frame_unref(frame);
  2584. if (output_ready(avctx, avctx->internal->draining)) {
  2585. av_fifo_read(ctx->output_surface_ready_queue, &tmp_out_surf, 1);
  2586. res = nvenc_push_context(avctx);
  2587. if (res < 0)
  2588. return res;
  2589. res = process_output_surface(avctx, pkt, tmp_out_surf);
  2590. res2 = nvenc_pop_context(avctx);
  2591. if (res2 < 0)
  2592. return res2;
  2593. if (res)
  2594. return res;
  2595. av_fifo_write(ctx->unused_surface_queue, &tmp_out_surf, 1);
  2596. } else if (avctx->internal->draining) {
  2597. return AVERROR_EOF;
  2598. } else {
  2599. return AVERROR(EAGAIN);
  2600. }
  2601. return 0;
  2602. }
  2603. av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
  2604. {
  2605. NvencContext *ctx = avctx->priv_data;
  2606. nvenc_send_frame(avctx, NULL);
  2607. av_fifo_reset2(ctx->timestamp_list);
  2608. ctx->output_frame_num = 0;
  2609. ctx->initial_delay_time = 0;
  2610. }