@@ -63,6 +63,15 @@ using AVHWFramesConstraints_uniq = std::unique_ptr<AVHWFramesConstraints, delete
6363
6464constexpr int DEFAULT_SURFACES = 20 ;
6565
66+ AVPixelFormat get_nv12_or_first (const AVPixelFormat *fmts){
67+ for (int i = 0 ; fmts[i] != AV_PIX_FMT_NONE ; i++){
68+ if (fmts[i] == AV_PIX_FMT_NV12 ){
69+ return AV_PIX_FMT_NV12 ;
70+ }
71+ }
72+ return fmts[0 ];
73+ }
74+
6675/* *
6776 * Returns first SW format from valid_sw_formats. This is usually
6877 * AV_PIX_FMT_YUV420P or AV_PIX_FMT_NV12.
@@ -72,12 +81,10 @@ constexpr int DEFAULT_SURFACES = 20;
7281 * namely from function try_format_config().
7382 */
7483AVPixelFormat get_sw_format (AVBufferRef *device_ref){
75- AVPixelFormat ret = AV_PIX_FMT_NONE ;
76-
7784 AVHWFramesConstraints_uniq fc (av_hwdevice_get_hwframe_constraints (device_ref, nullptr ));
7885 if (!fc) {
7986 MSG (ERROR , " failed to retrieve libavutil frame constraints\n " );
80- return ret ;
87+ return AV_PIX_FMT_NONE ;
8188 }
8289
8390 /*
@@ -89,31 +96,28 @@ AVPixelFormat get_sw_format(AVBufferRef *device_ref){
8996 AVBufferRef_uniq fref (av_hwframe_ctx_alloc (device_ref));
9097 if (!fref) {
9198 MSG (ERROR , " failed to alloc libavutil frame context\n " );
92- return ret ;
99+ return AV_PIX_FMT_NONE ;
93100 }
94101 auto fctx = reinterpret_cast <AVHWFramesContext *>(fref->data );
95102 constexpr int dummy_size = 128 ; // /< just some valid size
96103 fctx->format = AV_PIX_FMT_VAAPI ;
97- fctx->sw_format = fc->valid_sw_formats [ 0 ] ;
104+ fctx->sw_format = get_nv12_or_first ( fc->valid_sw_formats ) ;
98105 fctx->width = dummy_size;
99106 fctx->height = dummy_size;
100107 if (av_hwframe_ctx_init (fref.get ()) < 0 ) {
101108 MSG (ERROR , " failed to init libavutil frame context\n " );
102- return ret ;
109+ return AV_PIX_FMT_NONE ;
103110 }
104111
105- AVPixelFormat *fmts = nullptr ;
112+ std::unique_ptr< AVPixelFormat, deleter_from_fcn<av_free>> fmts ;
106113 int rc = av_hwframe_transfer_get_formats (
107- fref.get (), AV_HWFRAME_TRANSFER_DIRECTION_FROM , & fmts, 0 );
114+ fref.get (), AV_HWFRAME_TRANSFER_DIRECTION_FROM , out_ptr ( fmts) , 0 );
108115 if (rc){
109116 MSG (ERROR , " failed to get libavutil frame context supported formats\n " );
110- return ret ;
117+ return AV_PIX_FMT_NONE ;
111118 }
112- MSG (DEBUG , " Available HW layouts: %s\n " , get_avpixfmts_names (fmts));
113- ret = fmts[0 ];
114- av_free (fmts);
115-
116- return ret;
119+ MSG (DEBUG , " Available HW layouts: %s\n " , get_avpixfmts_names (fmts.get ()));
120+ return get_nv12_or_first (fmts.get ());
117121}
118122
119123}
0 commit comments