@@ -517,6 +517,13 @@ def test_profiles(self) -> None:
517517}
518518
519519
520+ def get_hwaccel_format (encoder : str , device_type : str ) -> str :
521+ for config in av .Codec (encoder , "w" ).hardware_configs :
522+ if config .device_type .name == device_type and config .format is not None :
523+ return config .format .name
524+ pytest .skip (f"No hardware format for { device_type } on { encoder } " )
525+
526+
520527def test_hardware_encode () -> None :
521528 hwdevices_available = av .codec .hwaccel .hwdevices_available ()
522529 if "HWACCEL_DEVICE_TYPE" not in os .environ :
@@ -569,3 +576,42 @@ def test_hardware_encode() -> None:
569576 with av .open (file , "r" ) as in_container :
570577 decoded = sum (1 for _ in in_container .decode (video = 0 ))
571578 assert decoded == n_frames
579+
580+
581+ def test_hardware_encode_honors_sw_format () -> None :
582+ hwdevices_available = av .codec .hwaccel .hwdevices_available ()
583+ if "HWACCEL_DEVICE_TYPE" not in os .environ :
584+ pytest .skip (
585+ "Set the HWACCEL_DEVICE_TYPE to run this test. "
586+ f"Options are { ' ' .join (hwdevices_available )} "
587+ )
588+
589+ device_type = os .environ ["HWACCEL_DEVICE_TYPE" ]
590+ assert device_type in hwdevices_available , f"{ device_type } not available"
591+
592+ encoder = _HWACCEL_ENCODERS .get (device_type )
593+ if encoder is None :
594+ pytest .skip (f"No hardware encoder mapped for { device_type } " )
595+ hw_format = get_hwaccel_format (encoder , device_type )
596+
597+ hwaccel = av .codec .hwaccel .HWAccel (
598+ device_type = device_type , allow_software_fallback = False
599+ )
600+ container = av .open (io .BytesIO (), mode = "w" , format = "mp4" )
601+ stream = container .add_stream (encoder , rate = 30 , hwaccel = hwaccel )
602+ stream .width = 320
603+ stream .height = 240
604+ stream .pix_fmt = hw_format
605+ stream .codec_context .sw_format = "yuv420p"
606+
607+ assert stream .codec_context .sw_format .name == "yuv420p"
608+
609+ frame = VideoFrame (320 , 240 , "rgb24" )
610+ for packet in stream .encode (frame ):
611+ container .mux (packet )
612+
613+ assert stream .codec_context .pix_fmt == hw_format
614+ assert stream .codec_context .sw_format .name == "yuv420p"
615+ for packet in stream .encode ():
616+ container .mux (packet )
617+ container .close ()
0 commit comments