qsvenc.c 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765
  1. /*
  2. * Intel MediaSDK QSV encoder utility functions
  3. *
  4. * copyright (c) 2013 Yukinori Yamazoe
  5. * copyright (c) 2015 Anton Khirnov
  6. *
  7. * This file is part of FFmpeg.
  8. *
  9. * FFmpeg is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * FFmpeg is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with FFmpeg; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. #include <string.h>
  24. #include <sys/types.h>
  25. #include <mfxvideo.h>
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/common.h"
  28. #include "libavutil/hwcontext.h"
  29. #include "libavutil/hwcontext_qsv.h"
  30. #include "libavutil/mem.h"
  31. #include "libavutil/log.h"
  32. #include "libavutil/dict.h"
  33. #include "libavutil/time.h"
  34. #include "libavutil/imgutils.h"
  35. #include "avcodec.h"
  36. #include "encode.h"
  37. #include "internal.h"
  38. #include "packet_internal.h"
  39. #include "qsv.h"
  40. #include "qsv_internal.h"
  41. #include "qsvenc.h"
  42. #include "libavutil/refstruct.h"
  43. struct profile_names {
  44. mfxU16 profile;
  45. const char *name;
  46. };
  47. static const struct profile_names avc_profiles[] = {
  48. { MFX_PROFILE_AVC_BASELINE, "avc baseline" },
  49. { MFX_PROFILE_AVC_MAIN, "avc main" },
  50. { MFX_PROFILE_AVC_EXTENDED, "avc extended" },
  51. { MFX_PROFILE_AVC_HIGH, "avc high" },
  52. { MFX_PROFILE_AVC_HIGH_422, "avc high 422" },
  53. { MFX_PROFILE_AVC_CONSTRAINED_BASELINE, "avc constrained baseline" },
  54. { MFX_PROFILE_AVC_CONSTRAINED_HIGH, "avc constrained high" },
  55. { MFX_PROFILE_AVC_PROGRESSIVE_HIGH, "avc progressive high" },
  56. };
  57. static const struct profile_names mpeg2_profiles[] = {
  58. { MFX_PROFILE_MPEG2_SIMPLE, "mpeg2 simple" },
  59. { MFX_PROFILE_MPEG2_MAIN, "mpeg2 main" },
  60. { MFX_PROFILE_MPEG2_HIGH, "mpeg2 high" },
  61. };
  62. static const struct profile_names hevc_profiles[] = {
  63. { MFX_PROFILE_HEVC_MAIN, "hevc main" },
  64. { MFX_PROFILE_HEVC_MAIN10, "hevc main10" },
  65. { MFX_PROFILE_HEVC_MAINSP, "hevc mainsp" },
  66. { MFX_PROFILE_HEVC_REXT, "hevc rext" },
  67. #if QSV_VERSION_ATLEAST(1, 32)
  68. { MFX_PROFILE_HEVC_SCC, "hevc scc" },
  69. #endif
  70. };
  71. static const struct profile_names vp9_profiles[] = {
  72. { MFX_PROFILE_VP9_0, "vp9 0" },
  73. { MFX_PROFILE_VP9_1, "vp9 1" },
  74. { MFX_PROFILE_VP9_2, "vp9 2" },
  75. { MFX_PROFILE_VP9_3, "vp9 3" },
  76. };
  77. static const struct profile_names av1_profiles[] = {
  78. #if QSV_VERSION_ATLEAST(1, 34)
  79. { MFX_PROFILE_AV1_MAIN, "av1 main" },
  80. { MFX_PROFILE_AV1_HIGH, "av1 high" },
  81. { MFX_PROFILE_AV1_PRO, "av1 professional" },
  82. #endif
  83. };
  84. typedef struct QSVPacket {
  85. AVPacket pkt;
  86. mfxSyncPoint *sync;
  87. mfxBitstream *bs;
  88. } QSVPacket;
  89. static const char *print_profile(enum AVCodecID codec_id, mfxU16 profile)
  90. {
  91. const struct profile_names *profiles;
  92. int i, num_profiles;
  93. switch (codec_id) {
  94. case AV_CODEC_ID_H264:
  95. profiles = avc_profiles;
  96. num_profiles = FF_ARRAY_ELEMS(avc_profiles);
  97. break;
  98. case AV_CODEC_ID_MPEG2VIDEO:
  99. profiles = mpeg2_profiles;
  100. num_profiles = FF_ARRAY_ELEMS(mpeg2_profiles);
  101. break;
  102. case AV_CODEC_ID_HEVC:
  103. profiles = hevc_profiles;
  104. num_profiles = FF_ARRAY_ELEMS(hevc_profiles);
  105. break;
  106. case AV_CODEC_ID_VP9:
  107. profiles = vp9_profiles;
  108. num_profiles = FF_ARRAY_ELEMS(vp9_profiles);
  109. break;
  110. case AV_CODEC_ID_AV1:
  111. profiles = av1_profiles;
  112. num_profiles = FF_ARRAY_ELEMS(av1_profiles);
  113. break;
  114. default:
  115. return "unknown";
  116. }
  117. for (i = 0; i < num_profiles; i++)
  118. if (profile == profiles[i].profile)
  119. return profiles[i].name;
  120. return "unknown";
  121. }
  122. static const struct {
  123. mfxU16 rc_mode;
  124. const char *name;
  125. } rc_names[] = {
  126. { MFX_RATECONTROL_CBR, "CBR" },
  127. { MFX_RATECONTROL_VBR, "VBR" },
  128. { MFX_RATECONTROL_CQP, "CQP" },
  129. #if QSV_HAVE_AVBR
  130. { MFX_RATECONTROL_AVBR, "AVBR" },
  131. #endif
  132. { MFX_RATECONTROL_LA, "LA" },
  133. { MFX_RATECONTROL_ICQ, "ICQ" },
  134. { MFX_RATECONTROL_LA_ICQ, "LA_ICQ" },
  135. #if QSV_HAVE_VCM
  136. { MFX_RATECONTROL_VCM, "VCM" },
  137. #endif
  138. #if !QSV_ONEVPL
  139. { MFX_RATECONTROL_LA_EXT, "LA_EXT" },
  140. #endif
  141. { MFX_RATECONTROL_LA_HRD, "LA_HRD" },
  142. { MFX_RATECONTROL_QVBR, "QVBR" },
  143. };
  144. #define UPDATE_PARAM(a, b) \
  145. do { \
  146. if ((a) != (b)) { \
  147. a = b; \
  148. updated = 1; \
  149. } \
  150. } while (0) \
  151. #define MFX_IMPL_VIA_MASK(impl) (0x0f00 & (impl))
  152. static const char *print_ratecontrol(mfxU16 rc_mode)
  153. {
  154. int i;
  155. for (i = 0; i < FF_ARRAY_ELEMS(rc_names); i++)
  156. if (rc_mode == rc_names[i].rc_mode)
  157. return rc_names[i].name;
  158. return "unknown";
  159. }
  160. static const char *print_threestate(mfxU16 val)
  161. {
  162. if (val == MFX_CODINGOPTION_ON)
  163. return "ON";
  164. else if (val == MFX_CODINGOPTION_OFF)
  165. return "OFF";
  166. return "unknown";
  167. }
  168. static void dump_video_param(AVCodecContext *avctx, QSVEncContext *q,
  169. mfxExtBuffer **coding_opts)
  170. {
  171. mfxInfoMFX *info = &q->param.mfx;
  172. // co is always at index 1
  173. mfxExtCodingOption *co = (mfxExtCodingOption*)coding_opts[1];
  174. mfxExtCodingOption2 *co2 = NULL;
  175. mfxExtCodingOption3 *co3 = NULL;
  176. mfxExtHEVCTiles *exthevctiles = NULL;
  177. #if QSV_HAVE_HE
  178. mfxExtHyperModeParam *exthypermodeparam = NULL;
  179. #endif
  180. const char *tmp_str = NULL;
  181. if (q->co2_idx > 0)
  182. co2 = (mfxExtCodingOption2*)coding_opts[q->co2_idx];
  183. if (q->co3_idx > 0)
  184. co3 = (mfxExtCodingOption3*)coding_opts[q->co3_idx];
  185. if (q->exthevctiles_idx > 0)
  186. exthevctiles = (mfxExtHEVCTiles *)coding_opts[q->exthevctiles_idx];
  187. #if QSV_HAVE_HE
  188. if (q->exthypermodeparam_idx > 0)
  189. exthypermodeparam = (mfxExtHyperModeParam *)coding_opts[q->exthypermodeparam_idx];
  190. #endif
  191. av_log(avctx, AV_LOG_VERBOSE, "profile: %s; level: %"PRIu16"\n",
  192. print_profile(avctx->codec_id, info->CodecProfile), info->CodecLevel);
  193. av_log(avctx, AV_LOG_VERBOSE,
  194. "GopPicSize: %"PRIu16"; GopRefDist: %"PRIu16"; GopOptFlag:%s%s; IdrInterval: %"PRIu16"\n",
  195. info->GopPicSize, info->GopRefDist,
  196. info->GopOptFlag & MFX_GOP_CLOSED ? " closed" : "",
  197. info->GopOptFlag & MFX_GOP_STRICT ? " strict" : "",
  198. info->IdrInterval);
  199. av_log(avctx, AV_LOG_VERBOSE, "TargetUsage: %"PRIu16"; RateControlMethod: %s\n",
  200. info->TargetUsage, print_ratecontrol(info->RateControlMethod));
  201. if (info->RateControlMethod == MFX_RATECONTROL_CBR ||
  202. info->RateControlMethod == MFX_RATECONTROL_VBR
  203. #if QSV_HAVE_VCM
  204. || info->RateControlMethod == MFX_RATECONTROL_VCM
  205. #endif
  206. ) {
  207. av_log(avctx, AV_LOG_VERBOSE,
  208. "BufferSizeInKB: %"PRIu16"; InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
  209. info->BufferSizeInKB, info->InitialDelayInKB, info->TargetKbps, info->MaxKbps, info->BRCParamMultiplier);
  210. } else if (info->RateControlMethod == MFX_RATECONTROL_CQP) {
  211. av_log(avctx, AV_LOG_VERBOSE, "QPI: %"PRIu16"; QPP: %"PRIu16"; QPB: %"PRIu16"\n",
  212. info->QPI, info->QPP, info->QPB);
  213. }
  214. #if QSV_HAVE_AVBR
  215. else if (info->RateControlMethod == MFX_RATECONTROL_AVBR) {
  216. av_log(avctx, AV_LOG_VERBOSE,
  217. "TargetKbps: %"PRIu16"; Accuracy: %"PRIu16"; Convergence: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
  218. info->TargetKbps, info->Accuracy, info->Convergence, info->BRCParamMultiplier);
  219. }
  220. #endif
  221. else if (info->RateControlMethod == MFX_RATECONTROL_LA
  222. || info->RateControlMethod == MFX_RATECONTROL_LA_HRD
  223. ) {
  224. av_log(avctx, AV_LOG_VERBOSE,
  225. "TargetKbps: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
  226. info->TargetKbps, info->BRCParamMultiplier);
  227. } else if (info->RateControlMethod == MFX_RATECONTROL_ICQ ||
  228. info->RateControlMethod == MFX_RATECONTROL_LA_ICQ)
  229. av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"\n", info->ICQQuality);
  230. av_log(avctx, AV_LOG_VERBOSE, "NumSlice: %"PRIu16"; NumRefFrame: %"PRIu16"\n",
  231. info->NumSlice, info->NumRefFrame);
  232. av_log(avctx, AV_LOG_VERBOSE, "RateDistortionOpt: %s\n",
  233. print_threestate(co->RateDistortionOpt));
  234. av_log(avctx, AV_LOG_VERBOSE, "RecoveryPointSEI: %s\n", print_threestate(co->RecoveryPointSEI));
  235. av_log(avctx, AV_LOG_VERBOSE, "VDENC: %s\n", print_threestate(info->LowPower));
  236. if (avctx->codec_id == AV_CODEC_ID_H264) {
  237. av_log(avctx, AV_LOG_VERBOSE, "Entropy coding: %s; MaxDecFrameBuffering: %"PRIu16"\n",
  238. co->CAVLC == MFX_CODINGOPTION_ON ? "CAVLC" : "CABAC", co->MaxDecFrameBuffering);
  239. av_log(avctx, AV_LOG_VERBOSE,
  240. "NalHrdConformance: %s; SingleSeiNalUnit: %s; VuiVclHrdParameters: %s VuiNalHrdParameters: %s\n",
  241. print_threestate(co->NalHrdConformance), print_threestate(co->SingleSeiNalUnit),
  242. print_threestate(co->VuiVclHrdParameters), print_threestate(co->VuiNalHrdParameters));
  243. } else if ((avctx->codec_id == AV_CODEC_ID_HEVC) && QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 28)) {
  244. av_log(avctx, AV_LOG_VERBOSE,
  245. "NalHrdConformance: %s; VuiNalHrdParameters: %s\n",
  246. print_threestate(co->NalHrdConformance), print_threestate(co->VuiNalHrdParameters));
  247. }
  248. av_log(avctx, AV_LOG_VERBOSE, "FrameRateExtD: %"PRIu32"; FrameRateExtN: %"PRIu32" \n",
  249. info->FrameInfo.FrameRateExtD, info->FrameInfo.FrameRateExtN);
  250. if (co2) {
  251. if ((info->RateControlMethod == MFX_RATECONTROL_VBR && q->extbrc && q->look_ahead_depth > 0) ||
  252. (info->RateControlMethod == MFX_RATECONTROL_LA) ||
  253. (info->RateControlMethod == MFX_RATECONTROL_LA_HRD) ||
  254. (info->RateControlMethod == MFX_RATECONTROL_LA_ICQ))
  255. av_log(avctx, AV_LOG_VERBOSE, "LookAheadDepth: %"PRIu16"\n", co2->LookAheadDepth);
  256. av_log(avctx, AV_LOG_VERBOSE, "IntRefType: %"PRIu16"; IntRefCycleSize: %"PRIu16"; IntRefQPDelta: %"PRId16"\n",
  257. co2->IntRefType, co2->IntRefCycleSize, co2->IntRefQPDelta);
  258. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %d; MaxSliceSize: %d\n",
  259. co2->MaxFrameSize, co2->MaxSliceSize);
  260. av_log(avctx, AV_LOG_VERBOSE,
  261. "BitrateLimit: %s; MBBRC: %s; ExtBRC: %s\n",
  262. print_threestate(co2->BitrateLimit), print_threestate(co2->MBBRC),
  263. print_threestate(co2->ExtBRC));
  264. if (co2->Trellis & MFX_TRELLIS_OFF) {
  265. av_log(avctx, AV_LOG_VERBOSE, "Trellis: off\n");
  266. } else if (!co2->Trellis) {
  267. av_log(avctx, AV_LOG_VERBOSE, "Trellis: auto\n");
  268. } else {
  269. char trellis_type[4];
  270. int i = 0;
  271. if (co2->Trellis & MFX_TRELLIS_I) trellis_type[i++] = 'I';
  272. if (co2->Trellis & MFX_TRELLIS_P) trellis_type[i++] = 'P';
  273. if (co2->Trellis & MFX_TRELLIS_B) trellis_type[i++] = 'B';
  274. trellis_type[i] = 0;
  275. av_log(avctx, AV_LOG_VERBOSE, "Trellis: %s\n", trellis_type);
  276. }
  277. switch (co2->LookAheadDS) {
  278. case MFX_LOOKAHEAD_DS_OFF: tmp_str = "off"; break;
  279. case MFX_LOOKAHEAD_DS_2x: tmp_str = "2x"; break;
  280. case MFX_LOOKAHEAD_DS_4x: tmp_str = "4x"; break;
  281. default: tmp_str = "unknown"; break;
  282. }
  283. av_log(avctx, AV_LOG_VERBOSE,
  284. "RepeatPPS: %s; NumMbPerSlice: %"PRIu16"; LookAheadDS: %s\n",
  285. print_threestate(co2->RepeatPPS), co2->NumMbPerSlice, tmp_str);
  286. switch (co2->BRefType) {
  287. case MFX_B_REF_OFF: tmp_str = "off"; break;
  288. case MFX_B_REF_PYRAMID: tmp_str = "pyramid"; break;
  289. default: tmp_str = "auto"; break;
  290. }
  291. av_log(avctx, AV_LOG_VERBOSE,
  292. "AdaptiveI: %s; AdaptiveB: %s; BRefType:%s\n",
  293. print_threestate(co2->AdaptiveI), print_threestate(co2->AdaptiveB), tmp_str);
  294. av_log(avctx, AV_LOG_VERBOSE,
  295. "MinQPI: %"PRIu8"; MaxQPI: %"PRIu8"; MinQPP: %"PRIu8"; MaxQPP: %"PRIu8"; MinQPB: %"PRIu8"; MaxQPB: %"PRIu8"\n",
  296. co2->MinQPI, co2->MaxQPI, co2->MinQPP, co2->MaxQPP, co2->MinQPB, co2->MaxQPB);
  297. av_log(avctx, AV_LOG_VERBOSE, "DisableDeblockingIdc: %"PRIu32" \n", co2->DisableDeblockingIdc);
  298. switch (co2->SkipFrame) {
  299. case MFX_SKIPFRAME_NO_SKIP:
  300. av_log(avctx, AV_LOG_VERBOSE, "SkipFrame: no_skip\n");
  301. break;
  302. case MFX_SKIPFRAME_INSERT_DUMMY:
  303. av_log(avctx, AV_LOG_VERBOSE, "SkipFrame: insert_dummy\n");
  304. break;
  305. case MFX_SKIPFRAME_INSERT_NOTHING:
  306. av_log(avctx, AV_LOG_VERBOSE, "SkipFrame: insert_nothing\n");
  307. break;
  308. case MFX_SKIPFRAME_BRC_ONLY:
  309. av_log(avctx, AV_LOG_VERBOSE, "SkipFrame: brc_only\n");
  310. break;
  311. default: break;
  312. }
  313. }
  314. if (co3) {
  315. if (info->RateControlMethod == MFX_RATECONTROL_QVBR)
  316. av_log(avctx, AV_LOG_VERBOSE, "QVBRQuality: %"PRIu16"\n", co3->QVBRQuality);
  317. switch (co3->PRefType) {
  318. case MFX_P_REF_DEFAULT: av_log(avctx, AV_LOG_VERBOSE, "PRefType: default\n"); break;
  319. case MFX_P_REF_SIMPLE: av_log(avctx, AV_LOG_VERBOSE, "PRefType: simple\n"); break;
  320. case MFX_P_REF_PYRAMID: av_log(avctx, AV_LOG_VERBOSE, "PRefType: pyramid\n"); break;
  321. default: av_log(avctx, AV_LOG_VERBOSE, "PRefType: unknown\n"); break;
  322. }
  323. if (avctx->codec_id == AV_CODEC_ID_HEVC)
  324. av_log(avctx, AV_LOG_VERBOSE,"GPB: %s\n", print_threestate(co3->GPB));
  325. av_log(avctx, AV_LOG_VERBOSE, "TransformSkip: %s \n", print_threestate(co3->TransformSkip));
  326. av_log(avctx, AV_LOG_VERBOSE, "IntRefCycleDist: %"PRId16"\n", co3->IntRefCycleDist);
  327. av_log(avctx, AV_LOG_VERBOSE, "LowDelayBRC: %s\n", print_threestate(co3->LowDelayBRC));
  328. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSizeI: %d; ", co3->MaxFrameSizeI);
  329. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSizeP: %d\n", co3->MaxFrameSizeP);
  330. av_log(avctx, AV_LOG_VERBOSE, "ScenarioInfo: %"PRId16"\n", co3->ScenarioInfo);
  331. }
  332. if (exthevctiles) {
  333. av_log(avctx, AV_LOG_VERBOSE, "NumTileColumns: %"PRIu16"; NumTileRows: %"PRIu16"\n",
  334. exthevctiles->NumTileColumns, exthevctiles->NumTileRows);
  335. }
  336. #if QSV_HAVE_HE
  337. if (exthypermodeparam) {
  338. av_log(avctx, AV_LOG_VERBOSE, "HyperEncode: ");
  339. if (exthypermodeparam->Mode == MFX_HYPERMODE_OFF)
  340. av_log(avctx, AV_LOG_VERBOSE, "OFF");
  341. if (exthypermodeparam->Mode == MFX_HYPERMODE_ON)
  342. av_log(avctx, AV_LOG_VERBOSE, "ON");
  343. if (exthypermodeparam->Mode == MFX_HYPERMODE_ADAPTIVE)
  344. av_log(avctx, AV_LOG_VERBOSE, "Adaptive");
  345. av_log(avctx, AV_LOG_VERBOSE, "\n");
  346. }
  347. #endif
  348. }
  349. static void dump_video_vp9_param(AVCodecContext *avctx, QSVEncContext *q,
  350. mfxExtBuffer **coding_opts)
  351. {
  352. mfxInfoMFX *info = &q->param.mfx;
  353. mfxExtVP9Param *vp9_param = NULL;
  354. mfxExtCodingOption2 *co2 = NULL;
  355. if (q->vp9_idx >= 0)
  356. vp9_param = (mfxExtVP9Param *)coding_opts[q->vp9_idx];
  357. if (q->co2_idx >= 0)
  358. co2 = (mfxExtCodingOption2*)coding_opts[q->co2_idx];
  359. av_log(avctx, AV_LOG_VERBOSE, "profile: %s \n",
  360. print_profile(avctx->codec_id, info->CodecProfile));
  361. av_log(avctx, AV_LOG_VERBOSE,
  362. "GopPicSize: %"PRIu16"; GopRefDist: %"PRIu16"; GopOptFlag:%s%s; IdrInterval: %"PRIu16"\n",
  363. info->GopPicSize, info->GopRefDist,
  364. info->GopOptFlag & MFX_GOP_CLOSED ? " closed" : "",
  365. info->GopOptFlag & MFX_GOP_STRICT ? " strict" : "",
  366. info->IdrInterval);
  367. av_log(avctx, AV_LOG_VERBOSE, "TargetUsage: %"PRIu16"; RateControlMethod: %s\n",
  368. info->TargetUsage, print_ratecontrol(info->RateControlMethod));
  369. if (info->RateControlMethod == MFX_RATECONTROL_CBR ||
  370. info->RateControlMethod == MFX_RATECONTROL_VBR) {
  371. av_log(avctx, AV_LOG_VERBOSE,
  372. "BufferSizeInKB: %"PRIu16"; InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
  373. info->BufferSizeInKB, info->InitialDelayInKB, info->TargetKbps, info->MaxKbps, info->BRCParamMultiplier);
  374. } else if (info->RateControlMethod == MFX_RATECONTROL_CQP) {
  375. av_log(avctx, AV_LOG_VERBOSE, "QPI: %"PRIu16"; QPP: %"PRIu16"; QPB: %"PRIu16"\n",
  376. info->QPI, info->QPP, info->QPB);
  377. }
  378. else if (info->RateControlMethod == MFX_RATECONTROL_ICQ) {
  379. av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"\n", info->ICQQuality);
  380. }
  381. else {
  382. av_log(avctx, AV_LOG_VERBOSE, "Unsupported ratecontrol method: %d \n", info->RateControlMethod);
  383. }
  384. av_log(avctx, AV_LOG_VERBOSE, "NumRefFrame: %"PRIu16"\n", info->NumRefFrame);
  385. av_log(avctx, AV_LOG_VERBOSE, "FrameRateExtD: %"PRIu32"; FrameRateExtN: %"PRIu32" \n",
  386. info->FrameInfo.FrameRateExtD, info->FrameInfo.FrameRateExtN);
  387. if (co2) {
  388. av_log(avctx, AV_LOG_VERBOSE,
  389. "IntRefType: %"PRIu16"; IntRefCycleSize: %"PRIu16"; IntRefQPDelta: %"PRId16"\n",
  390. co2->IntRefType, co2->IntRefCycleSize, co2->IntRefQPDelta);
  391. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %d\n", co2->MaxFrameSize);
  392. av_log(avctx, AV_LOG_VERBOSE,
  393. "BitrateLimit: %s; MBBRC: %s; ExtBRC: %s\n",
  394. print_threestate(co2->BitrateLimit), print_threestate(co2->MBBRC),
  395. print_threestate(co2->ExtBRC));
  396. av_log(avctx, AV_LOG_VERBOSE, "VDENC: %s\n", print_threestate(info->LowPower));
  397. av_log(avctx, AV_LOG_VERBOSE,
  398. "MinQPI: %"PRIu8"; MaxQPI: %"PRIu8"; MinQPP: %"PRIu8"; MaxQPP: %"PRIu8"; MinQPB: %"PRIu8"; MaxQPB: %"PRIu8"\n",
  399. co2->MinQPI, co2->MaxQPI, co2->MinQPP, co2->MaxQPP, co2->MinQPB, co2->MaxQPB);
  400. }
  401. if (vp9_param) {
  402. av_log(avctx, AV_LOG_VERBOSE, "WriteIVFHeaders: %s \n",
  403. print_threestate(vp9_param->WriteIVFHeaders));
  404. }
  405. }
  406. static void dump_video_mjpeg_param(AVCodecContext *avctx, QSVEncContext *q)
  407. {
  408. mfxInfoMFX *info = &q->param.mfx;
  409. av_log(avctx, AV_LOG_VERBOSE, "Interleaved: %"PRIu16" \n", info->Interleaved);
  410. av_log(avctx, AV_LOG_VERBOSE, "Quality: %"PRIu16" \n", info->Quality);
  411. av_log(avctx, AV_LOG_VERBOSE, "RestartInterval: %"PRIu16" \n", info->RestartInterval);
  412. av_log(avctx, AV_LOG_VERBOSE, "FrameRateExtD: %"PRIu32"; FrameRateExtN: %"PRIu32" \n",
  413. info->FrameInfo.FrameRateExtD, info->FrameInfo.FrameRateExtN);
  414. }
  415. #if QSV_HAVE_EXT_AV1_PARAM
  416. static void dump_video_av1_param(AVCodecContext *avctx, QSVEncContext *q,
  417. mfxExtBuffer **coding_opts)
  418. {
  419. mfxInfoMFX *info = &q->param.mfx;
  420. mfxExtAV1TileParam *av1_tile_param = (mfxExtAV1TileParam *)coding_opts[0];
  421. mfxExtAV1BitstreamParam *av1_bs_param = (mfxExtAV1BitstreamParam *)coding_opts[1];
  422. mfxExtCodingOption2 *co2 = (mfxExtCodingOption2*)coding_opts[2];
  423. mfxExtCodingOption3 *co3 = (mfxExtCodingOption3*)coding_opts[3];
  424. av_log(avctx, AV_LOG_VERBOSE, "profile: %s; level: %"PRIu16"\n",
  425. print_profile(avctx->codec_id, info->CodecProfile), info->CodecLevel);
  426. av_log(avctx, AV_LOG_VERBOSE,
  427. "GopPicSize: %"PRIu16"; GopRefDist: %"PRIu16"; GopOptFlag:%s%s; IdrInterval: %"PRIu16"\n",
  428. info->GopPicSize, info->GopRefDist,
  429. info->GopOptFlag & MFX_GOP_CLOSED ? " closed" : "",
  430. info->GopOptFlag & MFX_GOP_STRICT ? " strict" : "",
  431. info->IdrInterval);
  432. av_log(avctx, AV_LOG_VERBOSE, "TargetUsage: %"PRIu16"; RateControlMethod: %s\n",
  433. info->TargetUsage, print_ratecontrol(info->RateControlMethod));
  434. if (info->RateControlMethod == MFX_RATECONTROL_CBR ||
  435. info->RateControlMethod == MFX_RATECONTROL_VBR)
  436. av_log(avctx, AV_LOG_VERBOSE,
  437. "BufferSizeInKB: %"PRIu16"; InitialDelayInKB: %"PRIu16"; TargetKbps: %"PRIu16"; MaxKbps: %"PRIu16"; BRCParamMultiplier: %"PRIu16"\n",
  438. info->BufferSizeInKB, info->InitialDelayInKB, info->TargetKbps, info->MaxKbps, info->BRCParamMultiplier);
  439. else if (info->RateControlMethod == MFX_RATECONTROL_CQP)
  440. av_log(avctx, AV_LOG_VERBOSE, "QPI: %"PRIu16"; QPP: %"PRIu16"; QPB: %"PRIu16"\n",
  441. info->QPI, info->QPP, info->QPB);
  442. else if (info->RateControlMethod == MFX_RATECONTROL_ICQ)
  443. av_log(avctx, AV_LOG_VERBOSE, "ICQQuality: %"PRIu16"\n", info->ICQQuality);
  444. else
  445. av_log(avctx, AV_LOG_VERBOSE, "Unsupported ratecontrol method: %d \n", info->RateControlMethod);
  446. av_log(avctx, AV_LOG_VERBOSE, "NumRefFrame: %"PRIu16"\n", info->NumRefFrame);
  447. av_log(avctx, AV_LOG_VERBOSE,
  448. "IntRefType: %"PRIu16"; IntRefCycleSize: %"PRIu16
  449. "; IntRefQPDelta: %"PRId16"; IntRefCycleDist: %"PRId16"\n",
  450. co2->IntRefType, co2->IntRefCycleSize,
  451. co2->IntRefQPDelta, co3->IntRefCycleDist);
  452. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %d;\n", co2->MaxFrameSize);
  453. av_log(avctx, AV_LOG_VERBOSE,
  454. "BitrateLimit: %s; MBBRC: %s; ExtBRC: %s\n",
  455. print_threestate(co2->BitrateLimit), print_threestate(co2->MBBRC),
  456. print_threestate(co2->ExtBRC));
  457. av_log(avctx, AV_LOG_VERBOSE, "VDENC: %s\n", print_threestate(info->LowPower));
  458. switch (co2->BRefType) {
  459. case MFX_B_REF_OFF: av_log(avctx, AV_LOG_VERBOSE, "BRefType: off\n"); break;
  460. case MFX_B_REF_PYRAMID: av_log(avctx, AV_LOG_VERBOSE, "BRefType: pyramid\n"); break;
  461. default: av_log(avctx, AV_LOG_VERBOSE, "BRefType: auto\n"); break;
  462. }
  463. switch (co3->PRefType) {
  464. case MFX_P_REF_DEFAULT: av_log(avctx, AV_LOG_VERBOSE, "PRefType: default\n"); break;
  465. case MFX_P_REF_SIMPLE: av_log(avctx, AV_LOG_VERBOSE, "PRefType: simple\n"); break;
  466. case MFX_P_REF_PYRAMID: av_log(avctx, AV_LOG_VERBOSE, "PRefType: pyramid\n"); break;
  467. default: av_log(avctx, AV_LOG_VERBOSE, "PRefType: unknown\n"); break;
  468. }
  469. av_log(avctx, AV_LOG_VERBOSE,
  470. "MinQPI: %"PRIu8"; MaxQPI: %"PRIu8"; MinQPP: %"PRIu8"; MaxQPP: %"PRIu8"; MinQPB: %"PRIu8"; MaxQPB: %"PRIu8"\n",
  471. co2->MinQPI, co2->MaxQPI, co2->MinQPP, co2->MaxQPP, co2->MinQPB, co2->MaxQPB);
  472. av_log(avctx, AV_LOG_VERBOSE, "FrameRateExtD: %"PRIu32"; FrameRateExtN: %"PRIu32" \n",
  473. info->FrameInfo.FrameRateExtD, info->FrameInfo.FrameRateExtN);
  474. av_log(avctx, AV_LOG_VERBOSE,
  475. "NumTileRows: %"PRIu16"; NumTileColumns: %"PRIu16"; NumTileGroups: %"PRIu16"\n",
  476. av1_tile_param->NumTileRows, av1_tile_param->NumTileColumns, av1_tile_param->NumTileGroups);
  477. av_log(avctx, AV_LOG_VERBOSE, "WriteIVFHeaders: %s \n",
  478. print_threestate(av1_bs_param->WriteIVFHeaders));
  479. av_log(avctx, AV_LOG_VERBOSE, "LowDelayBRC: %s\n", print_threestate(co3->LowDelayBRC));
  480. av_log(avctx, AV_LOG_VERBOSE, "MaxFrameSize: %d;\n", co2->MaxFrameSize);
  481. }
  482. #endif
  483. static int select_rc_mode(AVCodecContext *avctx, QSVEncContext *q)
  484. {
  485. const char *rc_desc;
  486. mfxU16 rc_mode;
  487. int want_la = q->look_ahead;
  488. int want_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
  489. int want_vcm = q->vcm;
  490. if (want_vcm && !QSV_HAVE_VCM) {
  491. av_log(avctx, AV_LOG_ERROR,
  492. "VCM ratecontrol mode requested, but is not supported by this SDK version\n");
  493. return AVERROR(ENOSYS);
  494. }
  495. if (want_la + want_qscale + want_vcm > 1) {
  496. av_log(avctx, AV_LOG_ERROR,
  497. "More than one of: { constant qscale, lookahead, VCM } requested, "
  498. "only one of them can be used at a time.\n");
  499. return AVERROR(EINVAL);
  500. }
  501. if (want_qscale) {
  502. rc_mode = MFX_RATECONTROL_CQP;
  503. rc_desc = "constant quantization parameter (CQP)";
  504. }
  505. #if QSV_HAVE_VCM
  506. else if (want_vcm) {
  507. rc_mode = MFX_RATECONTROL_VCM;
  508. rc_desc = "video conferencing mode (VCM)";
  509. if (!avctx->bit_rate) {
  510. av_log(avctx, AV_LOG_ERROR, "Using the %s ratecontrol method without "
  511. "setting bitrate. Please use the b option to set the desired "
  512. "bitrate.\n", rc_desc);
  513. return AVERROR(EINVAL);
  514. }
  515. }
  516. #endif
  517. else if (want_la) {
  518. rc_mode = MFX_RATECONTROL_LA;
  519. rc_desc = "VBR with lookahead (LA)";
  520. if (avctx->global_quality > 0) {
  521. rc_mode = MFX_RATECONTROL_LA_ICQ;
  522. rc_desc = "intelligent constant quality with lookahead (LA_ICQ)";
  523. } else if (!avctx->bit_rate) {
  524. av_log(avctx, AV_LOG_ERROR, "Using the %s ratecontrol method without "
  525. "setting bitrate. Please use the b option to set the desired "
  526. "bitrate.\n", rc_desc);
  527. return AVERROR(EINVAL);
  528. }
  529. }
  530. else if (avctx->global_quality > 0 && !avctx->rc_max_rate) {
  531. rc_mode = MFX_RATECONTROL_ICQ;
  532. rc_desc = "intelligent constant quality (ICQ)";
  533. }
  534. else if (avctx->bit_rate) {
  535. if (avctx->rc_max_rate == avctx->bit_rate) {
  536. rc_mode = MFX_RATECONTROL_CBR;
  537. rc_desc = "constant bitrate (CBR)";
  538. }
  539. #if QSV_HAVE_AVBR
  540. else if (!avctx->rc_max_rate &&
  541. (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_HEVC) &&
  542. q->avbr_accuracy &&
  543. q->avbr_convergence) {
  544. rc_mode = MFX_RATECONTROL_AVBR;
  545. rc_desc = "average variable bitrate (AVBR)";
  546. }
  547. #endif
  548. else if (avctx->global_quality > 0) {
  549. rc_mode = MFX_RATECONTROL_QVBR;
  550. rc_desc = "constant quality with VBR algorithm (QVBR)";
  551. } else {
  552. rc_mode = MFX_RATECONTROL_VBR;
  553. rc_desc = "variable bitrate (VBR)";
  554. }
  555. } else {
  556. rc_mode = MFX_RATECONTROL_CQP;
  557. rc_desc = "constant quantization parameter (CQP)";
  558. if (avctx->codec_id == AV_CODEC_ID_AV1)
  559. avctx->global_quality = FF_QP2LAMBDA * 128;
  560. else
  561. avctx->global_quality = FF_QP2LAMBDA * 26;
  562. av_log(avctx, AV_LOG_WARNING, "Using the constant quantization "
  563. "parameter (CQP) by default. Please use the global_quality "
  564. "option and other options for a quality-based mode or the b "
  565. "option and other options for a bitrate-based mode if the "
  566. "default is not the desired choice.\n");
  567. }
  568. q->param.mfx.RateControlMethod = rc_mode;
  569. av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", rc_desc);
  570. return 0;
  571. }
  572. static int check_enc_param(AVCodecContext *avctx, QSVEncContext *q)
  573. {
  574. mfxVideoParam param_out = { .mfx.CodecId = q->param.mfx.CodecId };
  575. mfxStatus ret;
  576. #define UNMATCH(x) (param_out.mfx.x != q->param.mfx.x)
  577. ret = MFXVideoENCODE_Query(q->session, &q->param, &param_out);
  578. if (ret < 0) {
  579. if (UNMATCH(CodecId))
  580. av_log(avctx, AV_LOG_ERROR, "Current codec type is unsupported\n");
  581. if (UNMATCH(CodecProfile))
  582. av_log(avctx, AV_LOG_ERROR, "Current profile is unsupported\n");
  583. if (UNMATCH(RateControlMethod))
  584. av_log(avctx, AV_LOG_ERROR, "Selected ratecontrol mode is unsupported\n");
  585. if (UNMATCH(LowPower))
  586. av_log(avctx, AV_LOG_ERROR, "Low power mode is unsupported\n");
  587. if (UNMATCH(FrameInfo.FrameRateExtN) || UNMATCH(FrameInfo.FrameRateExtD))
  588. av_log(avctx, AV_LOG_ERROR, "Current frame rate is unsupported\n");
  589. if (UNMATCH(FrameInfo.PicStruct))
  590. av_log(avctx, AV_LOG_ERROR, "Current picture structure is unsupported\n");
  591. if (UNMATCH(FrameInfo.Width) || UNMATCH(FrameInfo.Height))
  592. av_log(avctx, AV_LOG_ERROR, "Current resolution is unsupported\n");
  593. if (UNMATCH(FrameInfo.FourCC))
  594. av_log(avctx, AV_LOG_ERROR, "Current pixel format is unsupported\n");
  595. return 0;
  596. }
  597. return 1;
  598. }
  599. static int is_strict_gop(QSVEncContext *q) {
  600. if (q->adaptive_b == 0 && q->adaptive_i == 0)
  601. return 1;
  602. return 0;
  603. }
  604. static int init_video_param_jpeg(AVCodecContext *avctx, QSVEncContext *q)
  605. {
  606. enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
  607. avctx->sw_pix_fmt : avctx->pix_fmt;
  608. const AVPixFmtDescriptor *desc;
  609. int ret;
  610. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  611. if (ret < 0)
  612. return AVERROR_BUG;
  613. q->param.mfx.CodecId = ret;
  614. if (avctx->level > 0)
  615. q->param.mfx.CodecLevel = avctx->level;
  616. q->param.mfx.CodecProfile = q->profile;
  617. desc = av_pix_fmt_desc_get(sw_format);
  618. if (!desc)
  619. return AVERROR_BUG;
  620. ret = ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC, &q->param.mfx.FrameInfo.Shift);
  621. if (ret < 0)
  622. return AVERROR_BUG;
  623. q->param.mfx.FrameInfo.CropX = 0;
  624. q->param.mfx.FrameInfo.CropY = 0;
  625. q->param.mfx.FrameInfo.CropW = avctx->width;
  626. q->param.mfx.FrameInfo.CropH = avctx->height;
  627. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  628. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  629. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420 +
  630. !desc->log2_chroma_w + !desc->log2_chroma_h;
  631. q->param.mfx.FrameInfo.BitDepthLuma = desc->comp[0].depth;
  632. q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
  633. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, 16);
  634. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, 16);
  635. if (avctx->hw_frames_ctx) {
  636. AVHWFramesContext *frames_ctx = (AVHWFramesContext *)avctx->hw_frames_ctx->data;
  637. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  638. mfxFrameInfo *info = frames_hwctx->nb_surfaces ? &frames_hwctx->surfaces[0].Info : frames_hwctx->info;
  639. q->param.mfx.FrameInfo.Width = info->Width;
  640. q->param.mfx.FrameInfo.Height = info->Height;
  641. }
  642. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  643. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  644. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  645. } else {
  646. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  647. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  648. }
  649. q->param.mfx.Interleaved = 1;
  650. q->param.mfx.Quality = av_clip(avctx->global_quality, 1, 100);
  651. q->param.mfx.RestartInterval = 0;
  652. q->width_align = 16;
  653. q->height_align = 16;
  654. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  655. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, q->height_align);
  656. return 0;
  657. }
  658. static int init_video_param(AVCodecContext *avctx, QSVEncContext *q)
  659. {
  660. enum AVPixelFormat sw_format = avctx->pix_fmt == AV_PIX_FMT_QSV ?
  661. avctx->sw_pix_fmt : avctx->pix_fmt;
  662. const AVPixFmtDescriptor *desc;
  663. float quant;
  664. int target_bitrate_kbps, max_bitrate_kbps, brc_param_multiplier;
  665. int buffer_size_in_kilobytes, initial_delay_in_kilobytes;
  666. int ret;
  667. ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
  668. if (ret < 0)
  669. return AVERROR_BUG;
  670. q->param.mfx.CodecId = ret;
  671. if (avctx->level > 0) {
  672. q->param.mfx.CodecLevel = avctx->level;
  673. if (avctx->codec_id == AV_CODEC_ID_HEVC && avctx->level >= MFX_LEVEL_HEVC_4)
  674. q->param.mfx.CodecLevel |= q->tier;
  675. }
  676. if (avctx->compression_level == FF_COMPRESSION_DEFAULT) {
  677. avctx->compression_level = q->preset;
  678. } else if (avctx->compression_level >= 0) {
  679. if (avctx->compression_level > MFX_TARGETUSAGE_BEST_SPEED) {
  680. av_log(avctx, AV_LOG_WARNING, "Invalid compression level: "
  681. "valid range is 0-%d, using %d instead\n",
  682. MFX_TARGETUSAGE_BEST_SPEED, MFX_TARGETUSAGE_BEST_SPEED);
  683. avctx->compression_level = MFX_TARGETUSAGE_BEST_SPEED;
  684. }
  685. }
  686. if (q->low_power == 1) {
  687. q->param.mfx.LowPower = MFX_CODINGOPTION_ON;
  688. } else if (q->low_power == -1)
  689. q->param.mfx.LowPower = MFX_CODINGOPTION_UNKNOWN;
  690. else
  691. q->param.mfx.LowPower = MFX_CODINGOPTION_OFF;
  692. q->param.mfx.CodecProfile = q->profile;
  693. q->param.mfx.TargetUsage = avctx->compression_level;
  694. q->param.mfx.GopPicSize = FFMAX(0, avctx->gop_size);
  695. q->old_gop_size = avctx->gop_size;
  696. q->param.mfx.GopRefDist = FFMAX(-1, avctx->max_b_frames) + 1;
  697. q->param.mfx.GopOptFlag = avctx->flags & AV_CODEC_FLAG_CLOSED_GOP ?
  698. MFX_GOP_CLOSED : is_strict_gop(q) ?
  699. MFX_GOP_STRICT : 0;
  700. q->param.mfx.IdrInterval = q->idr_interval;
  701. q->param.mfx.NumSlice = avctx->slices;
  702. q->param.mfx.NumRefFrame = FFMAX(0, avctx->refs);
  703. q->param.mfx.EncodedOrder = 0;
  704. q->param.mfx.BufferSizeInKB = 0;
  705. desc = av_pix_fmt_desc_get(sw_format);
  706. if (!desc)
  707. return AVERROR_BUG;
  708. ret = ff_qsv_map_pixfmt(sw_format, &q->param.mfx.FrameInfo.FourCC, &q->param.mfx.FrameInfo.Shift);
  709. if (ret < 0)
  710. return AVERROR_BUG;
  711. q->param.mfx.FrameInfo.CropX = 0;
  712. q->param.mfx.FrameInfo.CropY = 0;
  713. q->param.mfx.FrameInfo.CropW = avctx->width;
  714. q->param.mfx.FrameInfo.CropH = avctx->height;
  715. q->param.mfx.FrameInfo.AspectRatioW = avctx->sample_aspect_ratio.num;
  716. q->param.mfx.FrameInfo.AspectRatioH = avctx->sample_aspect_ratio.den;
  717. q->param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420 +
  718. !desc->log2_chroma_w + !desc->log2_chroma_h;
  719. q->param.mfx.FrameInfo.BitDepthLuma = desc->comp[0].depth;
  720. q->param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
  721. // If the minor version is greater than or equal to 19,
  722. // then can use the same alignment settings as H.264 for HEVC
  723. q->width_align = (avctx->codec_id != AV_CODEC_ID_HEVC ||
  724. QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 19)) ? 16 : 32;
  725. q->param.mfx.FrameInfo.Width = FFALIGN(avctx->width, q->width_align);
  726. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  727. // it is important that PicStruct be setup correctly from the
  728. // start--otherwise, encoding doesn't work and results in a bunch
  729. // of incompatible video parameter errors
  730. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_TFF;
  731. // height alignment always must be 32 for interlaced video
  732. q->height_align = 32;
  733. } else {
  734. q->param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
  735. // for progressive video, the height should be aligned to 16 for
  736. // H.264. For HEVC, depending on the version of MFX, it should be
  737. // either 32 or 16. The lower number is better if possible.
  738. // For AV1, it is 32
  739. q->height_align = (avctx->codec_id == AV_CODEC_ID_HEVC ||
  740. avctx->codec_id == AV_CODEC_ID_AV1) ? 32 : 16;
  741. }
  742. q->param.mfx.FrameInfo.Height = FFALIGN(avctx->height, q->height_align);
  743. if (avctx->hw_frames_ctx) {
  744. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  745. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  746. mfxFrameInfo *info = frames_hwctx->nb_surfaces ? &frames_hwctx->surfaces[0].Info : frames_hwctx->info;
  747. q->param.mfx.FrameInfo.Width = info->Width;
  748. q->param.mfx.FrameInfo.Height = info->Height;
  749. }
  750. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  751. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  752. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  753. } else {
  754. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  755. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  756. }
  757. q->old_framerate = avctx->framerate;
  758. ret = select_rc_mode(avctx, q);
  759. if (ret < 0)
  760. return ret;
  761. //libmfx BRC parameters are 16 bits thus maybe overflow, then BRCParamMultiplier is needed
  762. buffer_size_in_kilobytes = avctx->rc_buffer_size / 8000;
  763. initial_delay_in_kilobytes = avctx->rc_initial_buffer_occupancy / 8000;
  764. target_bitrate_kbps = avctx->bit_rate / 1000;
  765. max_bitrate_kbps = avctx->rc_max_rate / 1000;
  766. brc_param_multiplier = (FFMAX(FFMAX3(target_bitrate_kbps, max_bitrate_kbps, buffer_size_in_kilobytes),
  767. initial_delay_in_kilobytes) + 0x10000) / 0x10000;
  768. q->old_rc_buffer_size = avctx->rc_buffer_size;
  769. q->old_rc_initial_buffer_occupancy = avctx->rc_initial_buffer_occupancy;
  770. q->old_bit_rate = avctx->bit_rate;
  771. q->old_rc_max_rate = avctx->rc_max_rate;
  772. switch (q->param.mfx.RateControlMethod) {
  773. case MFX_RATECONTROL_CBR:
  774. case MFX_RATECONTROL_VBR:
  775. if (q->extbrc) {
  776. q->extco2.LookAheadDepth = q->look_ahead_depth;
  777. }
  778. #if QSV_HAVE_VCM
  779. case MFX_RATECONTROL_VCM:
  780. #endif
  781. case MFX_RATECONTROL_QVBR:
  782. q->param.mfx.BufferSizeInKB = buffer_size_in_kilobytes / brc_param_multiplier;
  783. q->param.mfx.InitialDelayInKB = initial_delay_in_kilobytes / brc_param_multiplier;
  784. q->param.mfx.TargetKbps = target_bitrate_kbps / brc_param_multiplier;
  785. q->param.mfx.MaxKbps = max_bitrate_kbps / brc_param_multiplier;
  786. q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
  787. if (q->param.mfx.RateControlMethod == MFX_RATECONTROL_QVBR)
  788. q->extco3.QVBRQuality = av_clip(avctx->global_quality, 0, 51);
  789. break;
  790. case MFX_RATECONTROL_CQP:
  791. quant = avctx->global_quality / FF_QP2LAMBDA;
  792. if (avctx->codec_id == AV_CODEC_ID_AV1) {
  793. q->param.mfx.QPI = av_clip_uintp2(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 8);
  794. q->param.mfx.QPP = av_clip_uintp2(quant, 8);
  795. q->param.mfx.QPB = av_clip_uintp2(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 8);
  796. } else {
  797. q->param.mfx.QPI = av_clip(quant * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  798. q->param.mfx.QPP = av_clip(quant, 0, 51);
  799. q->param.mfx.QPB = av_clip(quant * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  800. }
  801. q->old_global_quality = avctx->global_quality;
  802. q->old_i_quant_factor = avctx->i_quant_factor;
  803. q->old_i_quant_offset = avctx->i_quant_offset;
  804. q->old_b_quant_factor = avctx->b_quant_factor;
  805. q->old_b_quant_offset = avctx->b_quant_offset;
  806. break;
  807. #if QSV_HAVE_AVBR
  808. case MFX_RATECONTROL_AVBR:
  809. q->param.mfx.TargetKbps = target_bitrate_kbps / brc_param_multiplier;
  810. q->param.mfx.Convergence = q->avbr_convergence;
  811. q->param.mfx.Accuracy = q->avbr_accuracy;
  812. q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
  813. break;
  814. #endif
  815. case MFX_RATECONTROL_LA:
  816. q->param.mfx.TargetKbps = target_bitrate_kbps / brc_param_multiplier;
  817. q->extco2.LookAheadDepth = q->look_ahead_depth;
  818. q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
  819. break;
  820. case MFX_RATECONTROL_LA_ICQ:
  821. q->extco2.LookAheadDepth = q->look_ahead_depth;
  822. case MFX_RATECONTROL_ICQ:
  823. q->param.mfx.ICQQuality = av_clip(avctx->global_quality, 1, 51);
  824. break;
  825. }
  826. // The HEVC encoder plugin currently fails with some old libmfx version if coding options
  827. // are provided. Can't find the extract libmfx version which fixed it, just enable it from
  828. // V1.28 in order to keep compatibility security.
  829. if (((avctx->codec_id != AV_CODEC_ID_HEVC) || QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 28))
  830. && (avctx->codec_id != AV_CODEC_ID_VP9)) {
  831. q->extco.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
  832. q->extco.Header.BufferSz = sizeof(q->extco);
  833. q->extco.PicTimingSEI = q->pic_timing_sei ?
  834. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
  835. q->old_pic_timing_sei = q->pic_timing_sei;
  836. if (q->rdo >= 0)
  837. q->extco.RateDistortionOpt = q->rdo > 0 ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  838. if (avctx->codec_id == AV_CODEC_ID_H264) {
  839. q->extco.CAVLC = q->cavlc ? MFX_CODINGOPTION_ON
  840. : MFX_CODINGOPTION_UNKNOWN;
  841. if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)
  842. q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?
  843. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  844. if (q->single_sei_nal_unit >= 0)
  845. q->extco.SingleSeiNalUnit = q->single_sei_nal_unit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  846. if (q->recovery_point_sei >= 0)
  847. q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  848. q->extco.MaxDecFrameBuffering = q->max_dec_frame_buffering;
  849. q->extco.AUDelimiter = q->aud ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  850. } else if (avctx->codec_id == AV_CODEC_ID_HEVC) {
  851. if (avctx->strict_std_compliance != FF_COMPLIANCE_NORMAL)
  852. q->extco.NalHrdConformance = avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL ?
  853. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  854. if (q->recovery_point_sei >= 0)
  855. q->extco.RecoveryPointSEI = q->recovery_point_sei ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  856. q->extco.AUDelimiter = q->aud ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  857. }
  858. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco;
  859. if (avctx->codec_id == AV_CODEC_ID_H264) {
  860. if (q->bitrate_limit >= 0)
  861. q->extco2.BitrateLimit = q->bitrate_limit ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  862. if (avctx->trellis >= 0)
  863. q->extco2.Trellis = (avctx->trellis == 0) ? MFX_TRELLIS_OFF : (MFX_TRELLIS_I | MFX_TRELLIS_P | MFX_TRELLIS_B);
  864. else
  865. q->extco2.Trellis = MFX_TRELLIS_UNKNOWN;
  866. q->extco2.LookAheadDS = q->look_ahead_downsampling;
  867. q->extco2.RepeatPPS = q->repeat_pps ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  868. }
  869. if (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_HEVC) {
  870. if (q->extbrc >= 0)
  871. q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  872. if (q->max_frame_size >= 0)
  873. q->extco2.MaxFrameSize = q->max_frame_size;
  874. q->old_max_frame_size = q->max_frame_size;
  875. if (q->int_ref_type >= 0)
  876. q->extco2.IntRefType = q->int_ref_type;
  877. q->old_int_ref_type = q->int_ref_type;
  878. if (q->int_ref_cycle_size >= 0)
  879. q->extco2.IntRefCycleSize = q->int_ref_cycle_size;
  880. q->old_int_ref_cycle_size = q->int_ref_cycle_size;
  881. if (q->int_ref_qp_delta != INT16_MIN)
  882. q->extco2.IntRefQPDelta = q->int_ref_qp_delta;
  883. q->old_int_ref_qp_delta = q->int_ref_qp_delta;
  884. if (q->max_slice_size >= 0)
  885. q->extco2.MaxSliceSize = q->max_slice_size;
  886. q->extco2.DisableDeblockingIdc = q->dblk_idc;
  887. if (q->b_strategy >= 0)
  888. q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
  889. if (q->adaptive_i >= 0)
  890. q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  891. if (q->adaptive_b >= 0)
  892. q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  893. if ((avctx->qmin >= 0 && avctx->qmax >= 0 && avctx->qmin > avctx->qmax) ||
  894. (q->max_qp_i >= 0 && q->min_qp_i >= 0 && q->min_qp_i > q->max_qp_i) ||
  895. (q->max_qp_p >= 0 && q->min_qp_p >= 0 && q->min_qp_p > q->max_qp_p) ||
  896. (q->max_qp_b >= 0 && q->min_qp_b >= 0 && q->min_qp_b > q->max_qp_b)) {
  897. av_log(avctx, AV_LOG_ERROR,
  898. "qmin and or qmax are set but invalid,"
  899. " please make sure min <= max\n");
  900. return AVERROR(EINVAL);
  901. }
  902. if (avctx->qmin >= 0) {
  903. q->extco2.MinQPI = avctx->qmin > 51 ? 51 : avctx->qmin;
  904. q->extco2.MinQPP = q->extco2.MinQPB = q->extco2.MinQPI;
  905. }
  906. q->old_qmin = avctx->qmin;
  907. if (avctx->qmax >= 0) {
  908. q->extco2.MaxQPI = avctx->qmax > 51 ? 51 : avctx->qmax;
  909. q->extco2.MaxQPP = q->extco2.MaxQPB = q->extco2.MaxQPI;
  910. }
  911. q->old_qmax = avctx->qmax;
  912. if (q->min_qp_i >= 0)
  913. q->extco2.MinQPI = q->min_qp_i > 51 ? 51 : q->min_qp_i;
  914. q->old_min_qp_i = q->min_qp_i;
  915. if (q->max_qp_i >= 0)
  916. q->extco2.MaxQPI = q->max_qp_i > 51 ? 51 : q->max_qp_i;
  917. q->old_max_qp_i = q->max_qp_i;
  918. if (q->min_qp_p >= 0)
  919. q->extco2.MinQPP = q->min_qp_p > 51 ? 51 : q->min_qp_p;
  920. q->old_min_qp_p = q->min_qp_p;
  921. if (q->max_qp_p >= 0)
  922. q->extco2.MaxQPP = q->max_qp_p > 51 ? 51 : q->max_qp_p;
  923. q->old_max_qp_p = q->max_qp_p;
  924. if (q->min_qp_b >= 0)
  925. q->extco2.MinQPB = q->min_qp_b > 51 ? 51 : q->min_qp_b;
  926. q->old_min_qp_b = q->min_qp_b;
  927. if (q->max_qp_b >= 0)
  928. q->extco2.MaxQPB = q->max_qp_b > 51 ? 51 : q->max_qp_b;
  929. q->old_max_qp_b = q->max_qp_b;
  930. if (q->mbbrc >= 0)
  931. q->extco2.MBBRC = q->mbbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  932. if (q->skip_frame >= 0)
  933. q->extco2.SkipFrame = q->skip_frame;
  934. q->extco2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
  935. q->extco2.Header.BufferSz = sizeof(q->extco2);
  936. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  937. } else if (avctx->codec_id == AV_CODEC_ID_AV1) {
  938. if (q->extbrc >= 0)
  939. q->extco2.ExtBRC = q->extbrc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  940. if (q->b_strategy >= 0)
  941. q->extco2.BRefType = q->b_strategy ? MFX_B_REF_PYRAMID : MFX_B_REF_OFF;
  942. if (q->adaptive_i >= 0)
  943. q->extco2.AdaptiveI = q->adaptive_i ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  944. if (q->adaptive_b >= 0)
  945. q->extco2.AdaptiveB = q->adaptive_b ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  946. if (q->max_frame_size >= 0)
  947. q->extco2.MaxFrameSize = q->max_frame_size;
  948. q->extco2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
  949. q->extco2.Header.BufferSz = sizeof(q->extco2);
  950. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco2;
  951. }
  952. if (avctx->codec_id == AV_CODEC_ID_H264) {
  953. #if QSV_HAVE_MF
  954. if (QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 25)) {
  955. q->extmfp.Header.BufferId = MFX_EXTBUFF_MULTI_FRAME_PARAM;
  956. q->extmfp.Header.BufferSz = sizeof(q->extmfp);
  957. q->extmfp.MFMode = q->mfmode;
  958. av_log(avctx,AV_LOG_VERBOSE,"MFMode:%d\n", q->extmfp.MFMode);
  959. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extmfp;
  960. }
  961. #endif
  962. }
  963. q->extco3.Header.BufferId = MFX_EXTBUFF_CODING_OPTION3;
  964. q->extco3.Header.BufferSz = sizeof(q->extco3);
  965. if (avctx->codec_id == AV_CODEC_ID_HEVC ||
  966. avctx->codec_id == AV_CODEC_ID_H264) {
  967. switch (q->p_strategy) {
  968. case 0:
  969. q->extco3.PRefType = MFX_P_REF_DEFAULT;
  970. break;
  971. case 1:
  972. q->extco3.PRefType = MFX_P_REF_SIMPLE;
  973. break;
  974. case 2:
  975. q->extco3.PRefType = MFX_P_REF_PYRAMID;
  976. break;
  977. default:
  978. q->extco3.PRefType = MFX_P_REF_DEFAULT;
  979. av_log(avctx, AV_LOG_WARNING,
  980. "invalid p_strategy, set to default\n");
  981. break;
  982. }
  983. if (q->extco3.PRefType == MFX_P_REF_PYRAMID &&
  984. avctx->max_b_frames != 0) {
  985. av_log(avctx, AV_LOG_WARNING,
  986. "Please set max_b_frames(-bf) to 0 to enable P-pyramid\n");
  987. }
  988. if (q->int_ref_cycle_dist >= 0)
  989. q->extco3.IntRefCycleDist = q->int_ref_cycle_dist;
  990. q->old_int_ref_cycle_dist = q->int_ref_cycle_dist;
  991. if (q->low_delay_brc >= 0)
  992. q->extco3.LowDelayBRC = q->low_delay_brc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  993. q->old_low_delay_brc = q->low_delay_brc;
  994. if (q->max_frame_size_i >= 0)
  995. q->extco3.MaxFrameSizeI = q->max_frame_size_i;
  996. if (q->max_frame_size_p >= 0)
  997. q->extco3.MaxFrameSizeP = q->max_frame_size_p;
  998. if (sw_format == AV_PIX_FMT_BGRA &&
  999. (q->profile == MFX_PROFILE_HEVC_REXT ||
  1000. q->profile == MFX_PROFILE_UNKNOWN))
  1001. q->extco3.TargetChromaFormatPlus1 = MFX_CHROMAFORMAT_YUV444 + 1;
  1002. q->extco3.ScenarioInfo = q->scenario;
  1003. } else if (avctx->codec_id == AV_CODEC_ID_AV1) {
  1004. if (q->low_delay_brc >= 0)
  1005. q->extco3.LowDelayBRC = q->low_delay_brc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  1006. q->old_low_delay_brc = q->low_delay_brc;
  1007. }
  1008. if (avctx->codec_id == AV_CODEC_ID_HEVC) {
  1009. if (q->transform_skip >= 0)
  1010. q->extco3.TransformSkip = q->transform_skip ? MFX_CODINGOPTION_ON :
  1011. MFX_CODINGOPTION_OFF;
  1012. else
  1013. q->extco3.TransformSkip = MFX_CODINGOPTION_UNKNOWN;
  1014. q->extco3.GPB = q->gpb ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  1015. }
  1016. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extco3;
  1017. }
  1018. if (avctx->codec_id == AV_CODEC_ID_VP9) {
  1019. q->extvp9param.Header.BufferId = MFX_EXTBUFF_VP9_PARAM;
  1020. q->extvp9param.Header.BufferSz = sizeof(q->extvp9param);
  1021. q->extvp9param.WriteIVFHeaders = MFX_CODINGOPTION_OFF;
  1022. #if QSV_HAVE_EXT_VP9_TILES
  1023. q->extvp9param.NumTileColumns = q->tile_cols;
  1024. q->extvp9param.NumTileRows = q->tile_rows;
  1025. #endif
  1026. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extvp9param;
  1027. }
  1028. #if QSV_HAVE_EXT_AV1_PARAM
  1029. if (avctx->codec_id == AV_CODEC_ID_AV1) {
  1030. if (QSV_RUNTIME_VERSION_ATLEAST(q->ver, 2, 5)) {
  1031. q->extav1tileparam.Header.BufferId = MFX_EXTBUFF_AV1_TILE_PARAM;
  1032. q->extav1tileparam.Header.BufferSz = sizeof(q->extav1tileparam);
  1033. q->extav1tileparam.NumTileColumns = q->tile_cols;
  1034. q->extav1tileparam.NumTileRows = q->tile_rows;
  1035. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extav1tileparam;
  1036. q->extav1bsparam.Header.BufferId = MFX_EXTBUFF_AV1_BITSTREAM_PARAM;
  1037. q->extav1bsparam.Header.BufferSz = sizeof(q->extav1bsparam);
  1038. q->extav1bsparam.WriteIVFHeaders = MFX_CODINGOPTION_OFF;
  1039. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extav1bsparam;
  1040. } else {
  1041. av_log(avctx, AV_LOG_ERROR,
  1042. "This version of runtime doesn't support AV1 encoding\n");
  1043. return AVERROR_UNKNOWN;
  1044. }
  1045. }
  1046. #endif
  1047. if (avctx->codec_id == AV_CODEC_ID_HEVC) {
  1048. q->exthevctiles.Header.BufferId = MFX_EXTBUFF_HEVC_TILES;
  1049. q->exthevctiles.Header.BufferSz = sizeof(q->exthevctiles);
  1050. q->exthevctiles.NumTileColumns = q->tile_cols;
  1051. q->exthevctiles.NumTileRows = q->tile_rows;
  1052. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->exthevctiles;
  1053. }
  1054. q->extvsi.VideoFullRange = (avctx->color_range == AVCOL_RANGE_JPEG);
  1055. q->extvsi.ColourDescriptionPresent = 0;
  1056. if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  1057. avctx->color_trc != AVCOL_TRC_UNSPECIFIED ||
  1058. avctx->colorspace != AVCOL_SPC_UNSPECIFIED) {
  1059. q->extvsi.ColourDescriptionPresent = 1;
  1060. q->extvsi.ColourPrimaries = avctx->color_primaries;
  1061. q->extvsi.TransferCharacteristics = avctx->color_trc;
  1062. if (avctx->colorspace == AVCOL_SPC_RGB)
  1063. // RGB will be converted to YUV, so RGB colorspace is not supported
  1064. q->extvsi.MatrixCoefficients = AVCOL_SPC_UNSPECIFIED;
  1065. else
  1066. q->extvsi.MatrixCoefficients = avctx->colorspace;
  1067. }
  1068. if ((avctx->codec_id != AV_CODEC_ID_VP9) && (q->extvsi.VideoFullRange || q->extvsi.ColourDescriptionPresent)) {
  1069. q->extvsi.Header.BufferId = MFX_EXTBUFF_VIDEO_SIGNAL_INFO;
  1070. q->extvsi.Header.BufferSz = sizeof(q->extvsi);
  1071. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->extvsi;
  1072. }
  1073. #if QSV_HAVE_HE
  1074. if (q->dual_gfx) {
  1075. if (QSV_RUNTIME_VERSION_ATLEAST(q->ver, 2, 4)) {
  1076. mfxIMPL impl;
  1077. MFXQueryIMPL(q->session, &impl);
  1078. if (MFX_IMPL_VIA_MASK(impl) != MFX_IMPL_VIA_D3D11) {
  1079. av_log(avctx, AV_LOG_ERROR, "Dual GFX mode requires D3D11VA \n");
  1080. return AVERROR_UNKNOWN;
  1081. }
  1082. if (q->param.mfx.LowPower != MFX_CODINGOPTION_ON) {
  1083. av_log(avctx, AV_LOG_ERROR, "Dual GFX mode supports only low-power encoding mode \n");
  1084. return AVERROR_UNKNOWN;
  1085. }
  1086. if (q->param.mfx.CodecId != MFX_CODEC_AVC && q->param.mfx.CodecId != MFX_CODEC_HEVC) {
  1087. av_log(avctx, AV_LOG_ERROR, "Not supported encoder for dual GFX mode. "
  1088. "Supported: h264_qsv and hevc_qsv \n");
  1089. return AVERROR_UNKNOWN;
  1090. }
  1091. if (q->param.mfx.RateControlMethod != MFX_RATECONTROL_VBR &&
  1092. q->param.mfx.RateControlMethod != MFX_RATECONTROL_CQP &&
  1093. q->param.mfx.RateControlMethod != MFX_RATECONTROL_ICQ) {
  1094. av_log(avctx, AV_LOG_WARNING, "Not supported BRC for dual GFX mode. "
  1095. "Supported: VBR, CQP and ICQ \n");
  1096. }
  1097. if ((q->param.mfx.CodecId == MFX_CODEC_AVC && q->param.mfx.IdrInterval != 0) ||
  1098. (q->param.mfx.CodecId == MFX_CODEC_HEVC && q->param.mfx.IdrInterval != 1)) {
  1099. av_log(avctx, AV_LOG_WARNING, "Dual GFX mode requires closed GOP for AVC and strict GOP for HEVC, -idr_interval 0 \n");
  1100. }
  1101. if (q->param.mfx.GopPicSize < 30) {
  1102. av_log(avctx, AV_LOG_WARNING, "For better performance in dual GFX mode GopPicSize must be >= 30 \n");
  1103. }
  1104. if (q->param.AsyncDepth < 30) {
  1105. av_log(avctx, AV_LOG_WARNING, "For better performance in dual GFX mode AsyncDepth must be >= 30 \n");
  1106. }
  1107. q->exthypermodeparam.Header.BufferId = MFX_EXTBUFF_HYPER_MODE_PARAM;
  1108. q->exthypermodeparam.Header.BufferSz = sizeof(q->exthypermodeparam);
  1109. q->exthypermodeparam.Mode = q->dual_gfx;
  1110. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->exthypermodeparam;
  1111. } else {
  1112. av_log(avctx, AV_LOG_ERROR,
  1113. "This version of runtime doesn't support Hyper Encode\n");
  1114. return AVERROR_UNKNOWN;
  1115. }
  1116. }
  1117. #endif
  1118. if (!check_enc_param(avctx,q)) {
  1119. av_log(avctx, AV_LOG_ERROR,
  1120. "some encoding parameters are not supported by the QSV "
  1121. "runtime. Please double check the input parameters.\n");
  1122. return AVERROR(ENOSYS);
  1123. }
  1124. return 0;
  1125. }
  1126. static int qsv_retrieve_enc_jpeg_params(AVCodecContext *avctx, QSVEncContext *q)
  1127. {
  1128. int ret = 0;
  1129. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  1130. if (ret < 0)
  1131. return ff_qsv_print_error(avctx, ret,
  1132. "Error calling GetVideoParam");
  1133. q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
  1134. // for qsv mjpeg the return value maybe 0 so alloc the buffer
  1135. if (q->packet_size == 0)
  1136. q->packet_size = q->param.mfx.FrameInfo.Height * q->param.mfx.FrameInfo.Width * 4;
  1137. dump_video_mjpeg_param(avctx, q);
  1138. return 0;
  1139. }
  1140. static int qsv_retrieve_enc_vp9_params(AVCodecContext *avctx, QSVEncContext *q)
  1141. {
  1142. int ret = 0;
  1143. mfxExtVP9Param vp9_extend_buf = {
  1144. .Header.BufferId = MFX_EXTBUFF_VP9_PARAM,
  1145. .Header.BufferSz = sizeof(vp9_extend_buf),
  1146. };
  1147. mfxExtCodingOption2 co2 = {
  1148. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  1149. .Header.BufferSz = sizeof(co2),
  1150. };
  1151. mfxExtCodingOption3 co3 = {
  1152. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  1153. .Header.BufferSz = sizeof(co3),
  1154. };
  1155. mfxExtBuffer *ext_buffers[3];
  1156. int ext_buf_num = 0;
  1157. q->co2_idx = q->co3_idx = q->vp9_idx = -1;
  1158. // It is possible the runtime doesn't support the given ext buffer
  1159. if (QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 6)) {
  1160. q->co2_idx = ext_buf_num;
  1161. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&co2;
  1162. }
  1163. if (QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 11)) {
  1164. q->co3_idx = ext_buf_num;
  1165. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&co3;
  1166. }
  1167. if (QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 26)) {
  1168. q->vp9_idx = ext_buf_num;
  1169. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&vp9_extend_buf;
  1170. }
  1171. q->param.ExtParam = ext_buffers;
  1172. q->param.NumExtParam = ext_buf_num;
  1173. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  1174. if (ret < 0)
  1175. return ff_qsv_print_error(avctx, ret,
  1176. "Error calling GetVideoParam");
  1177. q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
  1178. dump_video_vp9_param(avctx, q, ext_buffers);
  1179. return 0;
  1180. }
  1181. static int qsv_retrieve_enc_av1_params(AVCodecContext *avctx, QSVEncContext *q)
  1182. {
  1183. #if QSV_HAVE_EXT_AV1_PARAM
  1184. int ret = 0;
  1185. mfxExtAV1TileParam av1_extend_tile_buf = {
  1186. .Header.BufferId = MFX_EXTBUFF_AV1_TILE_PARAM,
  1187. .Header.BufferSz = sizeof(av1_extend_tile_buf),
  1188. };
  1189. mfxExtAV1BitstreamParam av1_bs_param = {
  1190. .Header.BufferId = MFX_EXTBUFF_AV1_BITSTREAM_PARAM,
  1191. .Header.BufferSz = sizeof(av1_bs_param),
  1192. };
  1193. mfxExtCodingOption2 co2 = {
  1194. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  1195. .Header.BufferSz = sizeof(co2),
  1196. };
  1197. mfxExtCodingOption3 co3 = {
  1198. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  1199. .Header.BufferSz = sizeof(co3),
  1200. };
  1201. mfxExtBuffer *ext_buffers[] = {
  1202. (mfxExtBuffer*)&av1_extend_tile_buf,
  1203. (mfxExtBuffer*)&av1_bs_param,
  1204. (mfxExtBuffer*)&co2,
  1205. (mfxExtBuffer*)&co3,
  1206. };
  1207. if (!QSV_RUNTIME_VERSION_ATLEAST(q->ver, 2, 5)) {
  1208. av_log(avctx, AV_LOG_ERROR,
  1209. "This version of runtime doesn't support AV1 encoding\n");
  1210. return AVERROR_UNKNOWN;
  1211. }
  1212. q->param.ExtParam = ext_buffers;
  1213. q->param.NumExtParam = FF_ARRAY_ELEMS(ext_buffers);
  1214. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  1215. if (ret < 0)
  1216. return ff_qsv_print_error(avctx, ret,
  1217. "Error calling GetVideoParam");
  1218. q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
  1219. dump_video_av1_param(avctx, q, ext_buffers);
  1220. #endif
  1221. return 0;
  1222. }
  1223. static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
  1224. {
  1225. AVCPBProperties *cpb_props;
  1226. uint8_t sps_buf[512];
  1227. uint8_t pps_buf[128];
  1228. mfxExtCodingOptionSPSPPS extradata = {
  1229. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_SPSPPS,
  1230. .Header.BufferSz = sizeof(extradata),
  1231. .SPSBuffer = sps_buf, .SPSBufSize = sizeof(sps_buf),
  1232. .PPSBuffer = pps_buf, .PPSBufSize = sizeof(pps_buf)
  1233. };
  1234. mfxExtCodingOption co = {
  1235. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION,
  1236. .Header.BufferSz = sizeof(co),
  1237. };
  1238. mfxExtCodingOption2 co2 = {
  1239. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION2,
  1240. .Header.BufferSz = sizeof(co2),
  1241. };
  1242. mfxExtCodingOption3 co3 = {
  1243. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION3,
  1244. .Header.BufferSz = sizeof(co3),
  1245. };
  1246. uint8_t vps_buf[128];
  1247. mfxExtCodingOptionVPS extradata_vps = {
  1248. .Header.BufferId = MFX_EXTBUFF_CODING_OPTION_VPS,
  1249. .Header.BufferSz = sizeof(extradata_vps),
  1250. .VPSBuffer = vps_buf,
  1251. .VPSBufSize = sizeof(vps_buf),
  1252. };
  1253. mfxExtHEVCTiles hevc_tile_buf = {
  1254. .Header.BufferId = MFX_EXTBUFF_HEVC_TILES,
  1255. .Header.BufferSz = sizeof(hevc_tile_buf),
  1256. };
  1257. #if QSV_HAVE_HE
  1258. mfxExtHyperModeParam hyper_mode_param_buf = {
  1259. .Header.BufferId = MFX_EXTBUFF_HYPER_MODE_PARAM,
  1260. .Header.BufferSz = sizeof(hyper_mode_param_buf),
  1261. };
  1262. #endif
  1263. mfxExtBuffer *ext_buffers[6 + QSV_HAVE_HE];
  1264. int need_pps = avctx->codec_id != AV_CODEC_ID_MPEG2VIDEO;
  1265. int ret, ext_buf_num = 0, extradata_offset = 0;
  1266. q->co2_idx = q->co3_idx = q->exthevctiles_idx = q->exthypermodeparam_idx = -1;
  1267. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&extradata;
  1268. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&co;
  1269. // It is possible the runtime doesn't support the given ext buffer
  1270. if (QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 6)) {
  1271. q->co2_idx = ext_buf_num;
  1272. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&co2;
  1273. }
  1274. if (QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 11)) {
  1275. q->co3_idx = ext_buf_num;
  1276. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&co3;
  1277. }
  1278. q->hevc_vps = ((avctx->codec_id == AV_CODEC_ID_HEVC) && QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 17));
  1279. if (q->hevc_vps)
  1280. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&extradata_vps;
  1281. if (avctx->codec_id == AV_CODEC_ID_HEVC && QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 13)) {
  1282. q->exthevctiles_idx = ext_buf_num;
  1283. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&hevc_tile_buf;
  1284. }
  1285. #if QSV_HAVE_HE
  1286. if (q->dual_gfx && QSV_RUNTIME_VERSION_ATLEAST(q->ver, 2, 4)) {
  1287. q->exthypermodeparam_idx = ext_buf_num;
  1288. ext_buffers[ext_buf_num++] = (mfxExtBuffer*)&hyper_mode_param_buf;
  1289. }
  1290. #endif
  1291. q->param.ExtParam = ext_buffers;
  1292. q->param.NumExtParam = ext_buf_num;
  1293. ret = MFXVideoENCODE_GetVideoParam(q->session, &q->param);
  1294. if (ret < 0)
  1295. return ff_qsv_print_error(avctx, ret,
  1296. "Error calling GetVideoParam");
  1297. q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
  1298. if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)
  1299. || (q->hevc_vps && !extradata_vps.VPSBufSize)
  1300. ) {
  1301. av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx.\n");
  1302. return AVERROR_UNKNOWN;
  1303. }
  1304. avctx->extradata_size = extradata.SPSBufSize + need_pps * extradata.PPSBufSize;
  1305. avctx->extradata_size += q->hevc_vps * extradata_vps.VPSBufSize;
  1306. avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
  1307. if (!avctx->extradata)
  1308. return AVERROR(ENOMEM);
  1309. if (q->hevc_vps) {
  1310. memcpy(avctx->extradata, vps_buf, extradata_vps.VPSBufSize);
  1311. extradata_offset += extradata_vps.VPSBufSize;
  1312. }
  1313. memcpy(avctx->extradata + extradata_offset, sps_buf, extradata.SPSBufSize);
  1314. extradata_offset += extradata.SPSBufSize;
  1315. if (need_pps) {
  1316. memcpy(avctx->extradata + extradata_offset, pps_buf, extradata.PPSBufSize);
  1317. extradata_offset += extradata.PPSBufSize;
  1318. }
  1319. memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  1320. cpb_props = ff_encode_add_cpb_side_data(avctx);
  1321. if (!cpb_props)
  1322. return AVERROR(ENOMEM);
  1323. cpb_props->max_bitrate = avctx->rc_max_rate;
  1324. cpb_props->min_bitrate = avctx->rc_min_rate;
  1325. cpb_props->avg_bitrate = avctx->bit_rate;
  1326. cpb_props->buffer_size = avctx->rc_buffer_size;
  1327. dump_video_param(avctx, q, ext_buffers);
  1328. return 0;
  1329. }
  1330. #if QSV_HAVE_OPAQUE
  1331. static int qsv_init_opaque_alloc(AVCodecContext *avctx, QSVEncContext *q)
  1332. {
  1333. AVQSVContext *qsv = avctx->hwaccel_context;
  1334. mfxFrameSurface1 *surfaces;
  1335. int nb_surfaces, i;
  1336. nb_surfaces = qsv->nb_opaque_surfaces + q->req.NumFrameSuggested;
  1337. q->opaque_alloc_buf = av_buffer_allocz(sizeof(*surfaces) * nb_surfaces);
  1338. if (!q->opaque_alloc_buf)
  1339. return AVERROR(ENOMEM);
  1340. q->opaque_surfaces = av_malloc_array(nb_surfaces, sizeof(*q->opaque_surfaces));
  1341. if (!q->opaque_surfaces)
  1342. return AVERROR(ENOMEM);
  1343. surfaces = (mfxFrameSurface1*)q->opaque_alloc_buf->data;
  1344. for (i = 0; i < nb_surfaces; i++) {
  1345. surfaces[i].Info = q->req.Info;
  1346. q->opaque_surfaces[i] = surfaces + i;
  1347. }
  1348. q->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
  1349. q->opaque_alloc.Header.BufferSz = sizeof(q->opaque_alloc);
  1350. q->opaque_alloc.In.Surfaces = q->opaque_surfaces;
  1351. q->opaque_alloc.In.NumSurface = nb_surfaces;
  1352. q->opaque_alloc.In.Type = q->req.Type;
  1353. q->extparam_internal[q->nb_extparam_internal++] = (mfxExtBuffer *)&q->opaque_alloc;
  1354. qsv->nb_opaque_surfaces = nb_surfaces;
  1355. qsv->opaque_surfaces = q->opaque_alloc_buf;
  1356. qsv->opaque_alloc_type = q->req.Type;
  1357. return 0;
  1358. }
  1359. #endif
  1360. static int qsvenc_init_session(AVCodecContext *avctx, QSVEncContext *q)
  1361. {
  1362. int ret;
  1363. if (avctx->hwaccel_context) {
  1364. AVQSVContext *qsv = avctx->hwaccel_context;
  1365. q->session = qsv->session;
  1366. } else if (avctx->hw_frames_ctx) {
  1367. q->frames_ctx.hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
  1368. if (!q->frames_ctx.hw_frames_ctx)
  1369. return AVERROR(ENOMEM);
  1370. ret = ff_qsv_init_session_frames(avctx, &q->internal_qs.session,
  1371. &q->frames_ctx, q->load_plugins,
  1372. #if QSV_HAVE_OPAQUE
  1373. q->param.IOPattern == MFX_IOPATTERN_IN_OPAQUE_MEMORY,
  1374. #else
  1375. 0,
  1376. #endif
  1377. MFX_GPUCOPY_OFF);
  1378. if (ret < 0) {
  1379. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  1380. return ret;
  1381. }
  1382. q->session = q->internal_qs.session;
  1383. } else if (avctx->hw_device_ctx) {
  1384. ret = ff_qsv_init_session_device(avctx, &q->internal_qs.session,
  1385. avctx->hw_device_ctx, q->load_plugins,
  1386. MFX_GPUCOPY_OFF);
  1387. if (ret < 0)
  1388. return ret;
  1389. q->session = q->internal_qs.session;
  1390. } else {
  1391. ret = ff_qsv_init_internal_session(avctx, &q->internal_qs,
  1392. q->load_plugins, MFX_GPUCOPY_OFF);
  1393. if (ret < 0)
  1394. return ret;
  1395. q->session = q->internal_qs.session;
  1396. }
  1397. return 0;
  1398. }
  1399. int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)
  1400. {
  1401. int iopattern = 0;
  1402. int opaque_alloc = 0;
  1403. int ret;
  1404. void *tmp;
  1405. #if HAVE_STRUCT_MFXCONFIGINTERFACE
  1406. mfxExtBuffer ext_buf;
  1407. mfxConfigInterface *iface = NULL;
  1408. const AVDictionaryEntry *param = NULL;
  1409. #endif
  1410. q->param.AsyncDepth = q->async_depth;
  1411. q->async_fifo = av_fifo_alloc2(q->async_depth, sizeof(QSVPacket), AV_FIFO_FLAG_AUTO_GROW);
  1412. if (!q->async_fifo)
  1413. return AVERROR(ENOMEM);
  1414. if (avctx->hwaccel_context) {
  1415. AVQSVContext *qsv = avctx->hwaccel_context;
  1416. iopattern = qsv->iopattern;
  1417. opaque_alloc = qsv->opaque_alloc;
  1418. }
  1419. if (avctx->hw_frames_ctx) {
  1420. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1421. AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
  1422. if (!iopattern) {
  1423. #if QSV_HAVE_OPAQUE
  1424. if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
  1425. iopattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY;
  1426. else if (frames_hwctx->frame_type &
  1427. (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))
  1428. iopattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
  1429. #else
  1430. if (frames_hwctx->frame_type &
  1431. (MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET))
  1432. iopattern = MFX_IOPATTERN_IN_VIDEO_MEMORY;
  1433. #endif
  1434. }
  1435. }
  1436. if (!iopattern)
  1437. iopattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
  1438. q->param.IOPattern = iopattern;
  1439. ff_qsv_print_iopattern(avctx, iopattern, "Encoder");
  1440. ret = qsvenc_init_session(avctx, q);
  1441. if (ret < 0)
  1442. return ret;
  1443. ret = MFXQueryVersion(q->session,&q->ver);
  1444. if (ret < 0) {
  1445. return ff_qsv_print_error(avctx, ret,
  1446. "Error querying mfx version");
  1447. }
  1448. // in the mfxInfoMFX struct, JPEG is different from other codecs
  1449. switch (avctx->codec_id) {
  1450. case AV_CODEC_ID_MJPEG:
  1451. ret = init_video_param_jpeg(avctx, q);
  1452. break;
  1453. default:
  1454. ret = init_video_param(avctx, q);
  1455. break;
  1456. }
  1457. if (ret < 0)
  1458. return ret;
  1459. tmp = av_realloc_array(q->extparam, q->nb_extparam_internal, sizeof(*q->extparam));
  1460. if (!tmp)
  1461. return AVERROR(ENOMEM);
  1462. q->extparam = tmp;
  1463. q->nb_extparam = q->nb_extparam_internal;
  1464. memcpy(q->extparam, q->extparam_internal, q->nb_extparam * sizeof(*q->extparam));
  1465. if (avctx->hwaccel_context) {
  1466. AVQSVContext *qsv = avctx->hwaccel_context;
  1467. int i, j;
  1468. for (i = 0; i < qsv->nb_ext_buffers; i++) {
  1469. for (j = 0; j < q->nb_extparam_internal; j++) {
  1470. if (qsv->ext_buffers[i]->BufferId == q->extparam_internal[j]->BufferId) {
  1471. q->extparam[j] = qsv->ext_buffers[i];
  1472. break;
  1473. }
  1474. }
  1475. if (j == q->nb_extparam_internal) {
  1476. tmp = av_realloc_array(q->extparam, q->nb_extparam + 1, sizeof(*q->extparam));
  1477. if (!tmp)
  1478. return AVERROR(ENOMEM);
  1479. q->extparam = tmp;
  1480. q->extparam[q->nb_extparam++] = qsv->ext_buffers[i];
  1481. }
  1482. }
  1483. }
  1484. q->param.ExtParam = q->extparam;
  1485. q->param.NumExtParam = q->nb_extparam;
  1486. #if HAVE_STRUCT_MFXCONFIGINTERFACE
  1487. ret = MFXVideoCORE_GetHandle(q->session, MFX_HANDLE_CONFIG_INTERFACE, (mfxHDL *)(&iface));
  1488. if (ret < 0)
  1489. return ff_qsv_print_error(avctx, ret,
  1490. "Error getting mfx config interface handle");
  1491. while ((param = av_dict_get(q->qsv_params, "", param, AV_DICT_IGNORE_SUFFIX))) {
  1492. const char *param_key = param->key;
  1493. const char *param_value = param->value;
  1494. mfxExtBuffer *new_ext_buf;
  1495. void *tmp;
  1496. av_log(avctx, AV_LOG_VERBOSE, "Parameter key: %s, value: %s\n", param_key, param_value);
  1497. // Set encoding parameters using MFXSetParameter
  1498. for (int i = 0; i < 2; i++) {
  1499. ret = iface->SetParameter(iface, (mfxU8*)param_key, (mfxU8*)param_value, MFX_STRUCTURE_TYPE_VIDEO_PARAM, &q->param, &ext_buf);
  1500. if (ret == MFX_ERR_NONE) {
  1501. break;
  1502. } else if (i == 0 && ret == MFX_ERR_MORE_EXTBUFFER) {
  1503. tmp = av_realloc_array(q->extparam_str, q->nb_extparam_str + 1, sizeof(*q->extparam_str));
  1504. if (!tmp)
  1505. return AVERROR(ENOMEM);
  1506. q->extparam_str = tmp;
  1507. tmp = av_realloc_array(q->extparam, q->nb_extparam + 1, sizeof(*q->extparam));
  1508. if (!tmp)
  1509. return AVERROR(ENOMEM);
  1510. q->extparam = tmp;
  1511. new_ext_buf = (mfxExtBuffer*)av_mallocz(ext_buf.BufferSz);
  1512. if (!new_ext_buf)
  1513. return AVERROR(ENOMEM);
  1514. new_ext_buf->BufferId = ext_buf.BufferId;
  1515. new_ext_buf->BufferSz = ext_buf.BufferSz;
  1516. q->extparam_str[q->nb_extparam_str++] = new_ext_buf;
  1517. q->extparam[q->nb_extparam++] = new_ext_buf;
  1518. q->param.ExtParam = q->extparam;
  1519. q->param.NumExtParam = q->nb_extparam;
  1520. } else {
  1521. av_log(avctx, AV_LOG_ERROR, "Failed to set parameter: %s\n", param_key);
  1522. return AVERROR_UNKNOWN;
  1523. }
  1524. }
  1525. }
  1526. #else
  1527. if (q->qsv_params) {
  1528. av_log(avctx, AV_LOG_WARNING, "MFX string API is not supported, ignore qsv_params option\n");
  1529. }
  1530. #endif
  1531. ret = MFXVideoENCODE_Query(q->session, &q->param, &q->param);
  1532. if (ret == MFX_WRN_PARTIAL_ACCELERATION) {
  1533. av_log(avctx, AV_LOG_WARNING, "Encoder will work with partial HW acceleration\n");
  1534. } else if (ret < 0) {
  1535. return ff_qsv_print_error(avctx, ret,
  1536. "Error querying encoder params");
  1537. }
  1538. ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);
  1539. if (ret < 0)
  1540. return ff_qsv_print_error(avctx, ret,
  1541. "Error querying (IOSurf) the encoding parameters");
  1542. if (opaque_alloc) {
  1543. #if QSV_HAVE_OPAQUE
  1544. ret = qsv_init_opaque_alloc(avctx, q);
  1545. if (ret < 0)
  1546. return ret;
  1547. #else
  1548. av_log(avctx, AV_LOG_ERROR, "User is requesting to allocate OPAQUE surface, "
  1549. "however libmfx %d.%d doesn't support OPAQUE memory.\n",
  1550. q->ver.Major, q->ver.Minor);
  1551. return AVERROR_UNKNOWN;
  1552. #endif
  1553. }
  1554. ret = MFXVideoENCODE_Init(q->session, &q->param);
  1555. if (ret < 0)
  1556. return ff_qsv_print_error(avctx, ret,
  1557. "Error initializing the encoder");
  1558. else if (ret > 0)
  1559. ff_qsv_print_warning(avctx, ret,
  1560. "Warning in encoder initialization");
  1561. switch (avctx->codec_id) {
  1562. case AV_CODEC_ID_MJPEG:
  1563. ret = qsv_retrieve_enc_jpeg_params(avctx, q);
  1564. break;
  1565. case AV_CODEC_ID_VP9:
  1566. ret = qsv_retrieve_enc_vp9_params(avctx, q);
  1567. break;
  1568. case AV_CODEC_ID_AV1:
  1569. ret = qsv_retrieve_enc_av1_params(avctx, q);
  1570. break;
  1571. default:
  1572. ret = qsv_retrieve_enc_params(avctx, q);
  1573. break;
  1574. }
  1575. if (ret < 0) {
  1576. av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");
  1577. return ret;
  1578. }
  1579. q->avctx = avctx;
  1580. return 0;
  1581. }
  1582. static void free_encoder_ctrl(mfxEncodeCtrl* enc_ctrl)
  1583. {
  1584. if (enc_ctrl) {
  1585. for (int i = 0; i < enc_ctrl->NumPayload && i < QSV_MAX_ENC_PAYLOAD; i++)
  1586. av_freep(&enc_ctrl->Payload[i]);
  1587. for (int i = 0; i < enc_ctrl->NumExtParam && i < QSV_MAX_ENC_EXTPARAM; i++)
  1588. av_freep(&enc_ctrl->ExtParam[i]);
  1589. enc_ctrl->NumPayload = 0;
  1590. enc_ctrl->NumExtParam = 0;
  1591. }
  1592. }
  1593. static void clear_unused_frames(QSVEncContext *q)
  1594. {
  1595. QSVFrame *cur = q->work_frames;
  1596. while (cur) {
  1597. if (cur->used && !cur->surface.Data.Locked) {
  1598. free_encoder_ctrl(&cur->enc_ctrl);
  1599. //do not reuse enc_ctrl from previous frame
  1600. memset(&cur->enc_ctrl, 0, sizeof(cur->enc_ctrl));
  1601. cur->enc_ctrl.Payload = cur->payloads;
  1602. cur->enc_ctrl.ExtParam = cur->extparam;
  1603. if (cur->frame->format == AV_PIX_FMT_QSV) {
  1604. av_frame_unref(cur->frame);
  1605. }
  1606. cur->used = 0;
  1607. }
  1608. cur = cur->next;
  1609. }
  1610. }
  1611. static int get_free_frame(QSVEncContext *q, QSVFrame **f)
  1612. {
  1613. QSVFrame *frame, **last;
  1614. clear_unused_frames(q);
  1615. frame = q->work_frames;
  1616. last = &q->work_frames;
  1617. while (frame) {
  1618. if (!frame->used) {
  1619. *f = frame;
  1620. frame->used = 1;
  1621. return 0;
  1622. }
  1623. last = &frame->next;
  1624. frame = frame->next;
  1625. }
  1626. frame = av_mallocz(sizeof(*frame));
  1627. if (!frame)
  1628. return AVERROR(ENOMEM);
  1629. frame->frame = av_frame_alloc();
  1630. if (!frame->frame) {
  1631. av_freep(&frame);
  1632. return AVERROR(ENOMEM);
  1633. }
  1634. frame->enc_ctrl.Payload = frame->payloads;
  1635. frame->enc_ctrl.ExtParam = frame->extparam;
  1636. *last = frame;
  1637. *f = frame;
  1638. frame->used = 1;
  1639. return 0;
  1640. }
  1641. static int qsvenc_fill_padding_area(AVFrame *frame, int new_w, int new_h)
  1642. {
  1643. const AVPixFmtDescriptor *desc;
  1644. int max_step[4], filled[4] = { 0 };
  1645. desc = av_pix_fmt_desc_get(frame->format);
  1646. av_assert0(desc);
  1647. av_image_fill_max_pixsteps(max_step, NULL, desc);
  1648. for (int i = 0; i < desc->nb_components; i++) {
  1649. const AVComponentDescriptor *comp = &desc->comp[i];
  1650. int sheight, dheight, plane = comp->plane;
  1651. ptrdiff_t swidth = av_image_get_linesize(frame->format,
  1652. frame->width,
  1653. plane);
  1654. ptrdiff_t dwidth = av_image_get_linesize(frame->format,
  1655. new_w,
  1656. plane);
  1657. if (swidth < 0 || dwidth < 0) {
  1658. av_log(NULL, AV_LOG_ERROR, "av_image_get_linesize failed\n");
  1659. return AVERROR(EINVAL);
  1660. }
  1661. if (filled[plane])
  1662. continue;
  1663. sheight = frame->height;
  1664. dheight = new_h;
  1665. if (plane) {
  1666. sheight = AV_CEIL_RSHIFT(frame->height, desc->log2_chroma_h);
  1667. dheight = AV_CEIL_RSHIFT(new_h, desc->log2_chroma_h);
  1668. }
  1669. // Fill right padding
  1670. if (new_w > frame->width) {
  1671. for (int j = 0; j < sheight; j++) {
  1672. void *line_ptr = frame->data[plane] + j * frame->linesize[plane] + swidth;
  1673. av_memcpy_backptr(line_ptr,
  1674. max_step[plane],
  1675. new_w - frame->width);
  1676. }
  1677. }
  1678. // Fill bottom padding
  1679. for (int j = sheight; j < dheight; j++)
  1680. memcpy(frame->data[plane] + j * frame->linesize[plane],
  1681. frame->data[plane] + (sheight - 1) * frame->linesize[plane],
  1682. dwidth);
  1683. filled[plane] = 1;
  1684. }
  1685. return 0;
  1686. }
  1687. /* frame width / height have been aligned with the alignment */
  1688. static int qsvenc_get_continuous_buffer(AVFrame *frame)
  1689. {
  1690. int total_size;
  1691. switch (frame->format) {
  1692. case AV_PIX_FMT_NV12:
  1693. frame->linesize[0] = frame->width;
  1694. frame->linesize[1] = frame->linesize[0];
  1695. total_size = frame->linesize[0] * frame->height + frame->linesize[1] * frame->height / 2;
  1696. break;
  1697. case AV_PIX_FMT_P010:
  1698. case AV_PIX_FMT_P012:
  1699. frame->linesize[0] = 2 * frame->width;
  1700. frame->linesize[1] = frame->linesize[0];
  1701. total_size = frame->linesize[0] * frame->height + frame->linesize[1] * frame->height / 2;
  1702. break;
  1703. case AV_PIX_FMT_YUYV422:
  1704. frame->linesize[0] = 2 * frame->width;
  1705. frame->linesize[1] = 0;
  1706. total_size = frame->linesize[0] * frame->height;
  1707. break;
  1708. case AV_PIX_FMT_Y210:
  1709. case AV_PIX_FMT_VUYX:
  1710. case AV_PIX_FMT_XV30:
  1711. case AV_PIX_FMT_BGRA:
  1712. case AV_PIX_FMT_X2RGB10:
  1713. frame->linesize[0] = 4 * frame->width;
  1714. frame->linesize[1] = 0;
  1715. total_size = frame->linesize[0] * frame->height;
  1716. break;
  1717. default:
  1718. // This should never be reached
  1719. av_assert0(0);
  1720. return AVERROR(EINVAL);
  1721. }
  1722. frame->buf[0] = av_buffer_alloc(total_size);
  1723. if (!frame->buf[0])
  1724. return AVERROR(ENOMEM);
  1725. frame->data[0] = frame->buf[0]->data;
  1726. frame->extended_data = frame->data;
  1727. if (frame->format == AV_PIX_FMT_NV12 ||
  1728. frame->format == AV_PIX_FMT_P010 ||
  1729. frame->format == AV_PIX_FMT_P012)
  1730. frame->data[1] = frame->data[0] + frame->linesize[0] * frame->height;
  1731. return 0;
  1732. }
  1733. static int submit_frame(QSVEncContext *q, const AVFrame *frame,
  1734. QSVFrame **new_frame)
  1735. {
  1736. QSVFrame *qf;
  1737. int ret;
  1738. ret = get_free_frame(q, &qf);
  1739. if (ret < 0)
  1740. return ret;
  1741. if (frame->format == AV_PIX_FMT_QSV) {
  1742. ret = av_frame_ref(qf->frame, frame);
  1743. if (ret < 0)
  1744. return ret;
  1745. qf->surface = *(mfxFrameSurface1*)qf->frame->data[3];
  1746. if (q->frames_ctx.mids) {
  1747. ret = ff_qsv_find_surface_idx(&q->frames_ctx, qf);
  1748. if (ret < 0)
  1749. return ret;
  1750. qf->surface.Data.MemId = &q->frames_ctx.mids[ret];
  1751. }
  1752. } else {
  1753. /* make a copy if the input is not padded as libmfx requires */
  1754. /* and to make allocation continuous for data[0]/data[1] */
  1755. if ((frame->height & (q->height_align - 1) || frame->linesize[0] & (q->width_align - 1)) ||
  1756. ((frame->format == AV_PIX_FMT_NV12 || frame->format == AV_PIX_FMT_P010 || frame->format == AV_PIX_FMT_P012) &&
  1757. (frame->data[1] - frame->data[0] != frame->linesize[0] * FFALIGN(qf->frame->height, q->height_align)))) {
  1758. int tmp_w, tmp_h;
  1759. qf->frame->height = tmp_h = FFALIGN(frame->height, q->height_align);
  1760. qf->frame->width = tmp_w = FFALIGN(frame->width, q->width_align);
  1761. qf->frame->format = frame->format;
  1762. if (!qf->frame->data[0]) {
  1763. ret = qsvenc_get_continuous_buffer(qf->frame);
  1764. if (ret < 0)
  1765. return ret;
  1766. }
  1767. qf->frame->height = frame->height;
  1768. qf->frame->width = frame->width;
  1769. ret = av_frame_copy(qf->frame, frame);
  1770. if (ret < 0) {
  1771. av_frame_unref(qf->frame);
  1772. return ret;
  1773. }
  1774. ret = qsvenc_fill_padding_area(qf->frame, tmp_w, tmp_h);
  1775. if (ret < 0) {
  1776. av_frame_unref(qf->frame);
  1777. return ret;
  1778. }
  1779. } else {
  1780. ret = av_frame_replace(qf->frame, frame);
  1781. if (ret < 0)
  1782. return ret;
  1783. }
  1784. qf->surface.Info = q->param.mfx.FrameInfo;
  1785. qf->surface.Info.PicStruct =
  1786. !(frame->flags & AV_FRAME_FLAG_INTERLACED) ? MFX_PICSTRUCT_PROGRESSIVE :
  1787. (frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST) ? MFX_PICSTRUCT_FIELD_TFF :
  1788. MFX_PICSTRUCT_FIELD_BFF;
  1789. if (frame->repeat_pict == 1)
  1790. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
  1791. else if (frame->repeat_pict == 2)
  1792. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
  1793. else if (frame->repeat_pict == 4)
  1794. qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
  1795. ret = ff_qsv_map_frame_to_surface(qf->frame, &qf->surface);
  1796. if (ret < 0) {
  1797. av_log(q->avctx, AV_LOG_ERROR, "map frame to surface failed.\n");
  1798. return ret;
  1799. }
  1800. }
  1801. qf->surface.Data.TimeStamp = av_rescale_q(frame->pts, q->avctx->time_base, (AVRational){1, 90000});
  1802. *new_frame = qf;
  1803. return 0;
  1804. }
  1805. static void print_interlace_msg(AVCodecContext *avctx, QSVEncContext *q)
  1806. {
  1807. if (q->param.mfx.CodecId == MFX_CODEC_AVC) {
  1808. if (q->param.mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
  1809. q->param.mfx.CodecLevel < MFX_LEVEL_AVC_21 ||
  1810. q->param.mfx.CodecLevel > MFX_LEVEL_AVC_41)
  1811. av_log(avctx, AV_LOG_WARNING,
  1812. "Interlaced coding is supported"
  1813. " at Main/High Profile Level 2.2-4.0\n");
  1814. }
  1815. }
  1816. static int set_roi_encode_ctrl(AVCodecContext *avctx, const AVFrame *frame,
  1817. mfxEncodeCtrl *enc_ctrl)
  1818. {
  1819. AVFrameSideData *sd = NULL;
  1820. int mb_size;
  1821. if (avctx->codec_id == AV_CODEC_ID_H264)
  1822. mb_size = 16;
  1823. else if (avctx->codec_id == AV_CODEC_ID_H265)
  1824. mb_size = 32;
  1825. else
  1826. return 0;
  1827. if (frame)
  1828. sd = av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
  1829. if (sd) {
  1830. mfxExtEncoderROI *enc_roi = NULL;
  1831. AVRegionOfInterest *roi;
  1832. uint32_t roi_size;
  1833. int nb_roi, i;
  1834. roi = (AVRegionOfInterest *)sd->data;
  1835. roi_size = roi->self_size;
  1836. if (!roi_size || sd->size % roi_size) {
  1837. av_log(avctx, AV_LOG_ERROR, "Invalid ROI Data.\n");
  1838. return AVERROR(EINVAL);
  1839. }
  1840. nb_roi = sd->size / roi_size;
  1841. if (nb_roi > QSV_MAX_ROI_NUM) {
  1842. av_log(avctx, AV_LOG_WARNING, "More ROIs set than "
  1843. "supported by driver (%d > %d).\n",
  1844. nb_roi, QSV_MAX_ROI_NUM);
  1845. nb_roi = QSV_MAX_ROI_NUM;
  1846. }
  1847. enc_roi = av_mallocz(sizeof(*enc_roi));
  1848. if (!enc_roi)
  1849. return AVERROR(ENOMEM);
  1850. enc_roi->Header.BufferId = MFX_EXTBUFF_ENCODER_ROI;
  1851. enc_roi->Header.BufferSz = sizeof(*enc_roi);
  1852. enc_roi->NumROI = nb_roi;
  1853. enc_roi->ROIMode = MFX_ROI_MODE_QP_DELTA;
  1854. for (i = 0; i < nb_roi; i++) {
  1855. roi = (AVRegionOfInterest *)(sd->data + roi_size * i);
  1856. enc_roi->ROI[i].Top = FFALIGN(roi->top, mb_size);
  1857. enc_roi->ROI[i].Bottom = FFALIGN(roi->bottom, mb_size);
  1858. enc_roi->ROI[i].Left = FFALIGN(roi->left, mb_size);
  1859. enc_roi->ROI[i].Right = FFALIGN(roi->right, mb_size);
  1860. enc_roi->ROI[i].DeltaQP =
  1861. roi->qoffset.num * 51 / roi->qoffset.den;
  1862. av_log(avctx, AV_LOG_DEBUG, "ROI: (%d,%d)-(%d,%d) -> %+d.\n",
  1863. roi->top, roi->left, roi->bottom, roi->right,
  1864. enc_roi->ROI[i].DeltaQP);
  1865. }
  1866. enc_ctrl->ExtParam[enc_ctrl->NumExtParam] = (mfxExtBuffer *)enc_roi;
  1867. enc_ctrl->NumExtParam++;
  1868. }
  1869. return 0;
  1870. }
  1871. static void set_skip_frame_encode_ctrl(AVCodecContext *avctx, const AVFrame *frame,
  1872. mfxEncodeCtrl *enc_ctrl)
  1873. {
  1874. AVDictionaryEntry* skip_frame_dict = NULL;
  1875. if (!frame->metadata)
  1876. return;
  1877. skip_frame_dict = av_dict_get(frame->metadata, "qsv_skip_frame", NULL, 0);
  1878. if (!skip_frame_dict)
  1879. return;
  1880. enc_ctrl->SkipFrame = strtol(skip_frame_dict->value, NULL, 10);
  1881. return;
  1882. }
  1883. static int update_qp(AVCodecContext *avctx, QSVEncContext *q)
  1884. {
  1885. int updated = 0, new_qp = 0;
  1886. if (avctx->codec_id != AV_CODEC_ID_H264 && avctx->codec_id != AV_CODEC_ID_HEVC)
  1887. return 0;
  1888. if (q->param.mfx.RateControlMethod == MFX_RATECONTROL_CQP) {
  1889. UPDATE_PARAM(q->old_global_quality, avctx->global_quality);
  1890. UPDATE_PARAM(q->old_i_quant_factor, avctx->i_quant_factor);
  1891. UPDATE_PARAM(q->old_i_quant_offset, avctx->i_quant_offset);
  1892. UPDATE_PARAM(q->old_b_quant_factor, avctx->b_quant_factor);
  1893. UPDATE_PARAM(q->old_b_quant_offset, avctx->b_quant_offset);
  1894. if (!updated)
  1895. return 0;
  1896. new_qp = avctx->global_quality / FF_QP2LAMBDA;
  1897. q->param.mfx.QPI = av_clip(new_qp * fabs(avctx->i_quant_factor) +
  1898. avctx->i_quant_offset, 0, 51);
  1899. q->param.mfx.QPP = av_clip(new_qp, 0, 51);
  1900. q->param.mfx.QPB = av_clip(new_qp * fabs(avctx->b_quant_factor) +
  1901. avctx->b_quant_offset, 0, 51);
  1902. av_log(avctx, AV_LOG_DEBUG,
  1903. "Reset qp = %d/%d/%d for idr/p/b frames\n",
  1904. q->param.mfx.QPI, q->param.mfx.QPP, q->param.mfx.QPB);
  1905. }
  1906. return updated;
  1907. }
  1908. static int update_max_frame_size(AVCodecContext *avctx, QSVEncContext *q)
  1909. {
  1910. int updated = 0;
  1911. if (avctx->codec_id != AV_CODEC_ID_H264 && avctx->codec_id != AV_CODEC_ID_HEVC)
  1912. return 0;
  1913. UPDATE_PARAM(q->old_max_frame_size, q->max_frame_size);
  1914. if (!updated)
  1915. return 0;
  1916. q->extco2.MaxFrameSize = FFMAX(0, q->max_frame_size);
  1917. av_log(avctx, AV_LOG_DEBUG,
  1918. "Reset MaxFrameSize: %d;\n", q->extco2.MaxFrameSize);
  1919. return updated;
  1920. }
  1921. static int update_gop_size(AVCodecContext *avctx, QSVEncContext *q)
  1922. {
  1923. int updated = 0;
  1924. UPDATE_PARAM(q->old_gop_size, avctx->gop_size);
  1925. if (!updated)
  1926. return 0;
  1927. q->param.mfx.GopPicSize = FFMAX(0, avctx->gop_size);
  1928. av_log(avctx, AV_LOG_DEBUG, "reset GopPicSize to %d\n",
  1929. q->param.mfx.GopPicSize);
  1930. return updated;
  1931. }
  1932. static int update_rir(AVCodecContext *avctx, QSVEncContext *q)
  1933. {
  1934. int updated = 0;
  1935. if (avctx->codec_id != AV_CODEC_ID_H264 && avctx->codec_id != AV_CODEC_ID_HEVC)
  1936. return 0;
  1937. UPDATE_PARAM(q->old_int_ref_type, q->int_ref_type);
  1938. UPDATE_PARAM(q->old_int_ref_cycle_size, q->int_ref_cycle_size);
  1939. UPDATE_PARAM(q->old_int_ref_qp_delta, q->int_ref_qp_delta);
  1940. UPDATE_PARAM(q->old_int_ref_cycle_dist, q->int_ref_cycle_dist);
  1941. if (!updated)
  1942. return 0;
  1943. q->extco2.IntRefType = FFMAX(0, q->int_ref_type);
  1944. q->extco2.IntRefCycleSize = FFMAX(0, q->int_ref_cycle_size);
  1945. q->extco2.IntRefQPDelta =
  1946. q->int_ref_qp_delta != INT16_MIN ? q->int_ref_qp_delta : 0;
  1947. q->extco3.IntRefCycleDist = FFMAX(0, q->int_ref_cycle_dist);
  1948. av_log(avctx, AV_LOG_DEBUG,
  1949. "Reset IntRefType: %d; IntRefCycleSize: %d; "
  1950. "IntRefQPDelta: %d; IntRefCycleDist: %d\n",
  1951. q->extco2.IntRefType, q->extco2.IntRefCycleSize,
  1952. q->extco2.IntRefQPDelta, q->extco3.IntRefCycleDist);
  1953. return updated;
  1954. }
  1955. static int update_min_max_qp(AVCodecContext *avctx, QSVEncContext *q)
  1956. {
  1957. int updated = 0;
  1958. if (avctx->codec_id != AV_CODEC_ID_H264)
  1959. return 0;
  1960. UPDATE_PARAM(q->old_qmin, avctx->qmin);
  1961. UPDATE_PARAM(q->old_qmax, avctx->qmax);
  1962. UPDATE_PARAM(q->old_min_qp_i, q->min_qp_i);
  1963. UPDATE_PARAM(q->old_max_qp_i, q->max_qp_i);
  1964. UPDATE_PARAM(q->old_min_qp_p, q->min_qp_p);
  1965. UPDATE_PARAM(q->old_max_qp_p, q->max_qp_p);
  1966. UPDATE_PARAM(q->old_min_qp_b, q->min_qp_b);
  1967. UPDATE_PARAM(q->old_max_qp_b, q->max_qp_b);
  1968. if (!updated)
  1969. return 0;
  1970. if ((avctx->qmin >= 0 && avctx->qmax >= 0 && avctx->qmin > avctx->qmax) ||
  1971. (q->max_qp_i >= 0 && q->min_qp_i >= 0 && q->min_qp_i > q->max_qp_i) ||
  1972. (q->max_qp_p >= 0 && q->min_qp_p >= 0 && q->min_qp_p > q->max_qp_p) ||
  1973. (q->max_qp_b >= 0 && q->min_qp_b >= 0 && q->min_qp_b > q->max_qp_b)) {
  1974. av_log(avctx, AV_LOG_ERROR,
  1975. "qmin and or qmax are set but invalid,"
  1976. " please make sure min <= max\n");
  1977. return AVERROR(EINVAL);
  1978. }
  1979. q->extco2.MinQPI = 0;
  1980. q->extco2.MaxQPI = 0;
  1981. q->extco2.MinQPP = 0;
  1982. q->extco2.MaxQPP = 0;
  1983. q->extco2.MinQPB = 0;
  1984. q->extco2.MaxQPB = 0;
  1985. if (avctx->qmin >= 0) {
  1986. q->extco2.MinQPI = avctx->qmin > 51 ? 51 : avctx->qmin;
  1987. q->extco2.MinQPB = q->extco2.MinQPP = q->extco2.MinQPI;
  1988. }
  1989. if (avctx->qmax >= 0) {
  1990. q->extco2.MaxQPI = avctx->qmax > 51 ? 51 : avctx->qmax;
  1991. q->extco2.MaxQPB = q->extco2.MaxQPP = q->extco2.MaxQPI;
  1992. }
  1993. if (q->min_qp_i >= 0)
  1994. q->extco2.MinQPI = q->min_qp_i > 51 ? 51 : q->min_qp_i;
  1995. if (q->max_qp_i >= 0)
  1996. q->extco2.MaxQPI = q->max_qp_i > 51 ? 51 : q->max_qp_i;
  1997. if (q->min_qp_p >= 0)
  1998. q->extco2.MinQPP = q->min_qp_p > 51 ? 51 : q->min_qp_p;
  1999. if (q->max_qp_p >= 0)
  2000. q->extco2.MaxQPP = q->max_qp_p > 51 ? 51 : q->max_qp_p;
  2001. if (q->min_qp_b >= 0)
  2002. q->extco2.MinQPB = q->min_qp_b > 51 ? 51 : q->min_qp_b;
  2003. if (q->max_qp_b >= 0)
  2004. q->extco2.MaxQPB = q->max_qp_b > 51 ? 51 : q->max_qp_b;
  2005. av_log(avctx, AV_LOG_VERBOSE, "Reset MinQPI: %d; MaxQPI: %d; "
  2006. "MinQPP: %d; MaxQPP: %d; "
  2007. "MinQPB: %d; MaxQPB: %d\n",
  2008. q->extco2.MinQPI, q->extco2.MaxQPI,
  2009. q->extco2.MinQPP, q->extco2.MaxQPP,
  2010. q->extco2.MinQPB, q->extco2.MaxQPB);
  2011. return updated;
  2012. }
  2013. static int update_low_delay_brc(AVCodecContext *avctx, QSVEncContext *q)
  2014. {
  2015. int updated = 0;
  2016. if (avctx->codec_id != AV_CODEC_ID_H264 &&
  2017. avctx->codec_id != AV_CODEC_ID_HEVC &&
  2018. avctx->codec_id != AV_CODEC_ID_AV1)
  2019. return 0;
  2020. UPDATE_PARAM(q->old_low_delay_brc, q->low_delay_brc);
  2021. if (!updated)
  2022. return 0;
  2023. q->extco3.LowDelayBRC = MFX_CODINGOPTION_UNKNOWN;
  2024. if (q->low_delay_brc >= 0)
  2025. q->extco3.LowDelayBRC = q->low_delay_brc ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF;
  2026. av_log(avctx, AV_LOG_DEBUG, "Reset LowDelayBRC: %s\n",
  2027. print_threestate(q->extco3.LowDelayBRC));
  2028. return updated;
  2029. }
  2030. static int update_frame_rate(AVCodecContext *avctx, QSVEncContext *q)
  2031. {
  2032. int updated = 0;
  2033. UPDATE_PARAM(q->old_framerate.num, avctx->framerate.num);
  2034. UPDATE_PARAM(q->old_framerate.den, avctx->framerate.den);
  2035. if (!updated)
  2036. return 0;
  2037. if (avctx->framerate.den > 0 && avctx->framerate.num > 0) {
  2038. q->param.mfx.FrameInfo.FrameRateExtN = avctx->framerate.num;
  2039. q->param.mfx.FrameInfo.FrameRateExtD = avctx->framerate.den;
  2040. } else {
  2041. q->param.mfx.FrameInfo.FrameRateExtN = avctx->time_base.den;
  2042. q->param.mfx.FrameInfo.FrameRateExtD = avctx->time_base.num;
  2043. }
  2044. av_log(avctx, AV_LOG_DEBUG, "Reset framerate: %d/%d (%.2f fps).\n",
  2045. q->param.mfx.FrameInfo.FrameRateExtN,
  2046. q->param.mfx.FrameInfo.FrameRateExtD,
  2047. (double)q->param.mfx.FrameInfo.FrameRateExtN / q->param.mfx.FrameInfo.FrameRateExtD);
  2048. return updated;
  2049. }
  2050. static int update_bitrate(AVCodecContext *avctx, QSVEncContext *q)
  2051. {
  2052. int updated = 0;
  2053. int target_bitrate_kbps, max_bitrate_kbps, brc_param_multiplier;
  2054. int buffer_size_in_kilobytes, initial_delay_in_kilobytes;
  2055. UPDATE_PARAM(q->old_rc_buffer_size, avctx->rc_buffer_size);
  2056. UPDATE_PARAM(q->old_rc_initial_buffer_occupancy, avctx->rc_initial_buffer_occupancy);
  2057. UPDATE_PARAM(q->old_bit_rate, avctx->bit_rate);
  2058. UPDATE_PARAM(q->old_rc_max_rate, avctx->rc_max_rate);
  2059. if (!updated)
  2060. return 0;
  2061. buffer_size_in_kilobytes = avctx->rc_buffer_size / 8000;
  2062. initial_delay_in_kilobytes = avctx->rc_initial_buffer_occupancy / 8000;
  2063. target_bitrate_kbps = avctx->bit_rate / 1000;
  2064. max_bitrate_kbps = avctx->rc_max_rate / 1000;
  2065. brc_param_multiplier = (FFMAX(FFMAX3(target_bitrate_kbps, max_bitrate_kbps, buffer_size_in_kilobytes),
  2066. initial_delay_in_kilobytes) + 0x10000) / 0x10000;
  2067. q->param.mfx.BufferSizeInKB = buffer_size_in_kilobytes / brc_param_multiplier;
  2068. q->param.mfx.InitialDelayInKB = initial_delay_in_kilobytes / brc_param_multiplier;
  2069. q->param.mfx.TargetKbps = target_bitrate_kbps / brc_param_multiplier;
  2070. q->param.mfx.MaxKbps = max_bitrate_kbps / brc_param_multiplier;
  2071. q->param.mfx.BRCParamMultiplier = brc_param_multiplier;
  2072. av_log(avctx, AV_LOG_VERBOSE,
  2073. "Reset BufferSizeInKB: %d; InitialDelayInKB: %d; "
  2074. "TargetKbps: %d; MaxKbps: %d; BRCParamMultiplier: %d\n",
  2075. q->param.mfx.BufferSizeInKB, q->param.mfx.InitialDelayInKB,
  2076. q->param.mfx.TargetKbps, q->param.mfx.MaxKbps, q->param.mfx.BRCParamMultiplier);
  2077. return updated;
  2078. }
  2079. static int update_pic_timing_sei(AVCodecContext *avctx, QSVEncContext *q)
  2080. {
  2081. int updated = 0;
  2082. if (avctx->codec_id != AV_CODEC_ID_H264 && avctx->codec_id != AV_CODEC_ID_HEVC)
  2083. return 0;
  2084. UPDATE_PARAM(q->old_pic_timing_sei, q->pic_timing_sei);
  2085. if (!updated)
  2086. return 0;
  2087. q->extco.PicTimingSEI = q->pic_timing_sei ?
  2088. MFX_CODINGOPTION_ON : MFX_CODINGOPTION_UNKNOWN;
  2089. av_log(avctx, AV_LOG_DEBUG, "Reset PicTimingSEI: %s\n",
  2090. print_threestate(q->extco.PicTimingSEI));
  2091. return updated;
  2092. }
  2093. static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,
  2094. const AVFrame *frame)
  2095. {
  2096. QSVPacket pkt = { { 0 } };
  2097. mfxExtAVCEncodedFrameInfo *enc_info = NULL;
  2098. mfxExtBuffer **enc_buf = NULL;
  2099. mfxFrameSurface1 *surf = NULL;
  2100. QSVFrame *qsv_frame = NULL;
  2101. mfxEncodeCtrl* enc_ctrl = NULL;
  2102. int ret;
  2103. if (frame) {
  2104. ret = submit_frame(q, frame, &qsv_frame);
  2105. if (ret < 0) {
  2106. av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");
  2107. return ret;
  2108. }
  2109. }
  2110. if (qsv_frame) {
  2111. surf = &qsv_frame->surface;
  2112. enc_ctrl = &qsv_frame->enc_ctrl;
  2113. if (frame->pict_type == AV_PICTURE_TYPE_I) {
  2114. enc_ctrl->FrameType = MFX_FRAMETYPE_I | MFX_FRAMETYPE_REF;
  2115. if ((frame->flags & AV_FRAME_FLAG_KEY) || q->forced_idr)
  2116. enc_ctrl->FrameType |= MFX_FRAMETYPE_IDR;
  2117. }
  2118. }
  2119. ret = av_new_packet(&pkt.pkt, q->packet_size);
  2120. if (ret < 0) {
  2121. av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");
  2122. return ret;
  2123. }
  2124. pkt.bs = av_mallocz(sizeof(*pkt.bs));
  2125. if (!pkt.bs)
  2126. goto nomem;
  2127. pkt.bs->Data = pkt.pkt.data;
  2128. pkt.bs->MaxLength = pkt.pkt.size;
  2129. if (avctx->codec_id == AV_CODEC_ID_H264) {
  2130. enc_info = av_mallocz(sizeof(*enc_info));
  2131. if (!enc_info)
  2132. goto nomem;
  2133. enc_info->Header.BufferId = MFX_EXTBUFF_ENCODED_FRAME_INFO;
  2134. enc_info->Header.BufferSz = sizeof (*enc_info);
  2135. pkt.bs->NumExtParam = 1;
  2136. enc_buf = av_mallocz(sizeof(mfxExtBuffer *));
  2137. if (!enc_buf)
  2138. goto nomem;
  2139. enc_buf[0] = (mfxExtBuffer *)enc_info;
  2140. pkt.bs->ExtParam = enc_buf;
  2141. }
  2142. if (q->set_encode_ctrl_cb && enc_ctrl) {
  2143. q->set_encode_ctrl_cb(avctx, frame, enc_ctrl);
  2144. }
  2145. if ((avctx->codec_id == AV_CODEC_ID_H264 ||
  2146. avctx->codec_id == AV_CODEC_ID_H265) &&
  2147. enc_ctrl && QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 8)) {
  2148. ret = set_roi_encode_ctrl(avctx, frame, enc_ctrl);
  2149. if (ret < 0)
  2150. goto free;
  2151. }
  2152. if ((avctx->codec_id == AV_CODEC_ID_H264 ||
  2153. avctx->codec_id == AV_CODEC_ID_H265) &&
  2154. q->skip_frame != MFX_SKIPFRAME_NO_SKIP &&
  2155. enc_ctrl && QSV_RUNTIME_VERSION_ATLEAST(q->ver, 1, 13))
  2156. set_skip_frame_encode_ctrl(avctx, frame, enc_ctrl);
  2157. pkt.sync = av_mallocz(sizeof(*pkt.sync));
  2158. if (!pkt.sync)
  2159. goto nomem;
  2160. do {
  2161. ret = MFXVideoENCODE_EncodeFrameAsync(q->session, enc_ctrl, surf, pkt.bs, pkt.sync);
  2162. if (ret == MFX_WRN_DEVICE_BUSY)
  2163. av_usleep(500);
  2164. } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
  2165. if (ret > 0)
  2166. ff_qsv_print_warning(avctx, ret, "Warning during encoding");
  2167. if (ret < 0) {
  2168. ret = (ret == MFX_ERR_MORE_DATA) ?
  2169. AVERROR(EAGAIN) : ff_qsv_print_error(avctx, ret, "Error during encoding");
  2170. goto free;
  2171. }
  2172. if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame && (frame->flags & AV_FRAME_FLAG_INTERLACED))
  2173. print_interlace_msg(avctx, q);
  2174. ret = 0;
  2175. if (*pkt.sync) {
  2176. ret = av_fifo_write(q->async_fifo, &pkt, 1);
  2177. if (ret < 0)
  2178. goto free;
  2179. } else {
  2180. free:
  2181. av_freep(&pkt.sync);
  2182. av_packet_unref(&pkt.pkt);
  2183. av_freep(&pkt.bs);
  2184. if (avctx->codec_id == AV_CODEC_ID_H264) {
  2185. av_freep(&enc_info);
  2186. av_freep(&enc_buf);
  2187. }
  2188. }
  2189. return ret;
  2190. nomem:
  2191. ret = AVERROR(ENOMEM);
  2192. goto free;
  2193. }
  2194. static int update_parameters(AVCodecContext *avctx, QSVEncContext *q,
  2195. const AVFrame *frame)
  2196. {
  2197. int needReset = 0, ret = 0;
  2198. if (!frame || avctx->codec_id == AV_CODEC_ID_MJPEG)
  2199. return 0;
  2200. needReset = update_qp(avctx, q);
  2201. needReset |= update_max_frame_size(avctx, q);
  2202. needReset |= update_gop_size(avctx, q);
  2203. needReset |= update_rir(avctx, q);
  2204. needReset |= update_low_delay_brc(avctx, q);
  2205. needReset |= update_frame_rate(avctx, q);
  2206. needReset |= update_bitrate(avctx, q);
  2207. needReset |= update_pic_timing_sei(avctx, q);
  2208. ret = update_min_max_qp(avctx, q);
  2209. if (ret < 0)
  2210. return ret;
  2211. needReset |= ret;
  2212. if (!needReset)
  2213. return 0;
  2214. if (avctx->hwaccel_context) {
  2215. AVQSVContext *qsv = avctx->hwaccel_context;
  2216. int i, j;
  2217. q->param.ExtParam = q->extparam;
  2218. for (i = 0; i < qsv->nb_ext_buffers; i++)
  2219. q->param.ExtParam[i] = qsv->ext_buffers[i];
  2220. q->param.NumExtParam = qsv->nb_ext_buffers;
  2221. for (i = 0; i < q->nb_extparam_internal; i++) {
  2222. for (j = 0; j < qsv->nb_ext_buffers; j++) {
  2223. if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)
  2224. break;
  2225. }
  2226. if (j < qsv->nb_ext_buffers)
  2227. continue;
  2228. q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];
  2229. }
  2230. } else {
  2231. q->param.ExtParam = q->extparam_internal;
  2232. q->param.NumExtParam = q->nb_extparam_internal;
  2233. }
  2234. // Flush codec before reset configuration.
  2235. while (ret != AVERROR(EAGAIN)) {
  2236. ret = encode_frame(avctx, q, NULL);
  2237. if (ret < 0 && ret != AVERROR(EAGAIN))
  2238. return ret;
  2239. }
  2240. av_log(avctx, AV_LOG_DEBUG, "Parameter change, call msdk reset.\n");
  2241. ret = MFXVideoENCODE_Reset(q->session, &q->param);
  2242. if (ret < 0)
  2243. return ff_qsv_print_error(avctx, ret, "Error during resetting");
  2244. return 0;
  2245. }
  2246. int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,
  2247. AVPacket *pkt, const AVFrame *frame, int *got_packet)
  2248. {
  2249. int ret;
  2250. ret = update_parameters(avctx, q, frame);
  2251. if (ret < 0)
  2252. return ret;
  2253. ret = encode_frame(avctx, q, frame);
  2254. if (ret < 0 && ret != AVERROR(EAGAIN))
  2255. return ret;
  2256. if ((av_fifo_can_read(q->async_fifo) >= q->async_depth) ||
  2257. (!frame && av_fifo_can_read(q->async_fifo))) {
  2258. QSVPacket qpkt;
  2259. mfxExtAVCEncodedFrameInfo *enc_info;
  2260. mfxExtBuffer **enc_buf;
  2261. enum AVPictureType pict_type;
  2262. av_fifo_read(q->async_fifo, &qpkt, 1);
  2263. do {
  2264. ret = MFXVideoCORE_SyncOperation(q->session, *qpkt.sync, 1000);
  2265. } while (ret == MFX_WRN_IN_EXECUTION);
  2266. qpkt.pkt.dts = av_rescale_q(qpkt.bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
  2267. qpkt.pkt.pts = av_rescale_q(qpkt.bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
  2268. qpkt.pkt.size = qpkt.bs->DataLength;
  2269. if (qpkt.bs->FrameType & MFX_FRAMETYPE_IDR || qpkt.bs->FrameType & MFX_FRAMETYPE_xIDR) {
  2270. qpkt.pkt.flags |= AV_PKT_FLAG_KEY;
  2271. pict_type = AV_PICTURE_TYPE_I;
  2272. } else if (qpkt.bs->FrameType & MFX_FRAMETYPE_I || qpkt.bs->FrameType & MFX_FRAMETYPE_xI) {
  2273. if (avctx->codec_id == AV_CODEC_ID_VP9)
  2274. qpkt.pkt.flags |= AV_PKT_FLAG_KEY;
  2275. pict_type = AV_PICTURE_TYPE_I;
  2276. } else if (qpkt.bs->FrameType & MFX_FRAMETYPE_P || qpkt.bs->FrameType & MFX_FRAMETYPE_xP)
  2277. pict_type = AV_PICTURE_TYPE_P;
  2278. else if (qpkt.bs->FrameType & MFX_FRAMETYPE_B || qpkt.bs->FrameType & MFX_FRAMETYPE_xB)
  2279. pict_type = AV_PICTURE_TYPE_B;
  2280. else if (qpkt.bs->FrameType == MFX_FRAMETYPE_UNKNOWN && qpkt.bs->DataLength) {
  2281. pict_type = AV_PICTURE_TYPE_NONE;
  2282. av_log(avctx, AV_LOG_WARNING, "Unknown FrameType, set pict_type to AV_PICTURE_TYPE_NONE.\n");
  2283. } else {
  2284. av_log(avctx, AV_LOG_ERROR, "Invalid FrameType:%d.\n", qpkt.bs->FrameType);
  2285. return AVERROR_INVALIDDATA;
  2286. }
  2287. if (avctx->codec_id == AV_CODEC_ID_H264) {
  2288. enc_buf = qpkt.bs->ExtParam;
  2289. enc_info = (mfxExtAVCEncodedFrameInfo *)(*enc_buf);
  2290. ff_side_data_set_encoder_stats(&qpkt.pkt,
  2291. enc_info->QP * FF_QP2LAMBDA, NULL, 0, pict_type);
  2292. av_freep(&enc_info);
  2293. av_freep(&enc_buf);
  2294. }
  2295. av_freep(&qpkt.bs);
  2296. av_freep(&qpkt.sync);
  2297. av_packet_move_ref(pkt, &qpkt.pkt);
  2298. *got_packet = 1;
  2299. }
  2300. return 0;
  2301. }
  2302. int ff_qsv_enc_close(AVCodecContext *avctx, QSVEncContext *q)
  2303. {
  2304. QSVFrame *cur;
  2305. if (q->session)
  2306. MFXVideoENCODE_Close(q->session);
  2307. q->session = NULL;
  2308. ff_qsv_close_internal_session(&q->internal_qs);
  2309. av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
  2310. av_refstruct_unref(&q->frames_ctx.mids);
  2311. cur = q->work_frames;
  2312. while (cur) {
  2313. q->work_frames = cur->next;
  2314. av_frame_free(&cur->frame);
  2315. free_encoder_ctrl(&cur->enc_ctrl);
  2316. av_freep(&cur);
  2317. cur = q->work_frames;
  2318. }
  2319. if (q->async_fifo) {
  2320. QSVPacket pkt;
  2321. while (av_fifo_read(q->async_fifo, &pkt, 1) >= 0) {
  2322. if (avctx->codec_id == AV_CODEC_ID_H264) {
  2323. mfxExtBuffer **enc_buf = pkt.bs->ExtParam;
  2324. mfxExtAVCEncodedFrameInfo *enc_info = (mfxExtAVCEncodedFrameInfo *)(*enc_buf);
  2325. av_freep(&enc_info);
  2326. av_freep(&enc_buf);
  2327. }
  2328. av_freep(&pkt.sync);
  2329. av_freep(&pkt.bs);
  2330. av_packet_unref(&pkt.pkt);
  2331. }
  2332. av_fifo_freep2(&q->async_fifo);
  2333. }
  2334. #if QSV_HAVE_OPAQUE
  2335. av_freep(&q->opaque_surfaces);
  2336. av_buffer_unref(&q->opaque_alloc_buf);
  2337. #endif
  2338. for (int i = 0; i < q->nb_extparam_str; i++)
  2339. av_free(q->extparam_str[i]);
  2340. av_freep(&q->extparam_str);
  2341. av_freep(&q->extparam);
  2342. return 0;
  2343. }
  2344. const AVCodecHWConfigInternal *const ff_qsv_enc_hw_configs[] = {
  2345. HW_CONFIG_ENCODER_FRAMES(QSV, QSV),
  2346. HW_CONFIG_ENCODER_DEVICE(NV12, QSV),
  2347. HW_CONFIG_ENCODER_DEVICE(P010, QSV),
  2348. NULL,
  2349. };