Truly independent web browser
LibMediaCodecs: Replace Vulkan codec contexts instead of renegotiating
Zaggy1024a3742069a482
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cppindex 83a335fe8cb..587d9297cc2 100644--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp@@ -418,42 +418,19 @@ DecoderErrorOr<NonnullOwnPtr<FFmpegVulkanVideoDecoder>> FFmpegVulkanVideoDecoderauto const& functions = *ffmpeg;auto* device_context = TRY(device_context_for(functions, *device));+ if (vulkan_capable_decoder(functions, codec_id) == nullptr)+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "FFmpeg cannot decode codec {} through Vulkan", codec_id);+ auto codec_configuration = DECODER_TRY_ALLOC(FixedArray<u8>::create(codec_initialization_data));- AVCodecContext* codec_context = nullptr;AVPacket* packet = nullptr;AVFrame* frame = nullptr;ArmedScopeGuard memory_guard {[&] {- functions.avcodec_free_context(&codec_context);functions.av_packet_free(&packet);functions.av_frame_free(&frame);}};- auto const* codec = vulkan_capable_decoder(functions, codec_id);- if (codec == nullptr)- return DecoderError::format(DecoderErrorCategory::NotImplemented, "FFmpeg cannot decode codec {} through Vulkan", codec_id);-- codec_context = functions.avcodec_alloc_context3(codec);- if (codec_context == nullptr)- return DecoderError::format(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg codec context for codec {}", codec_id);-- TRY(set_codec_initialization_data(functions, *codec_context, codec_id, codec_initialization_data));- // The device already decodes several frames at a time, and frame threading would only hold frames back.- VERIFY(functions.av_opt_set_int(codec_context, "threads", 1, 0) == 0);- codec_context->max_pixels = MAX_VIDEO_FRAME_AREA;- codec_context->hw_device_ctx = functions.av_buffer_ref(device_context);- if (codec_context->hw_device_ctx == nullptr)- return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to reference the FFmpeg Vulkan device context"sv);- codec_context->get_format = negotiate_pixel_format;- codec_context->get_buffer2 = get_buffer;- // Only the bundled FFmpeg decodes AV1, and it is patched to know this flag.- if (codec_id == CodecID::AV1 && !PlatformFeatures::ProcessFeatures::the().is_enabled(PlatformFeatures::Feature::VulkanVideoBundledFFmpegAV1KeepSequenceHeaderEnableRefMVsFlag))- codec_context->hwaccel_flags |= AV_HWACCEL_FLAG_LADYBIRD_CLEAR_UNUSED_REF_FRAME_MVS;-- if (functions.avcodec_open2(codec_context, codec, nullptr) < 0)- return DecoderError::format(DecoderErrorCategory::Unknown, "Unknown error occurred when opening FFmpeg codec {}", codec_id);-packet = functions.av_packet_alloc();if (packet == nullptr)return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg packet"sv);@@ -463,8 +440,8 @@ DecoderErrorOr<NonnullOwnPtr<FFmpegVulkanVideoDecoder>> FFmpegVulkanVideoDecoderreturn DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg frame"sv);memory_guard.disarm();- auto decoder = DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) FFmpegVulkanVideoDecoder(functions, *device, codec_context, packet, frame)));- codec_context->opaque = decoder.ptr();+ auto decoder = DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) FFmpegVulkanVideoDecoder(functions, *device, codec_id, device_context, move(codec_configuration), packet, frame)));+ decoder->m_codec_context = TRY(decoder->create_codec_context());decoder->m_completion_thread = DECODER_TRY_ALLOC(Threading::Thread::try_create("VulkanDecode"sv, [decoder = decoder.ptr()] -> intptr_t {decoder->complete_frames_until_exit();@@ -474,15 +451,67 @@ DecoderErrorOr<NonnullOwnPtr<FFmpegVulkanVideoDecoder>> FFmpegVulkanVideoDecoderreturn decoder;}-FFmpegVulkanVideoDecoder::FFmpegVulkanVideoDecoder(FFmpegFunctions const& functions, VulkanVideoDevice& device, AVCodecContext* codec_context, AVPacket* packet, AVFrame* received_frame)+FFmpegVulkanVideoDecoder::FFmpegVulkanVideoDecoder(FFmpegFunctions const& functions, VulkanVideoDevice& device, CodecID codec_id, AVBufferRef* device_context, FixedArray<u8> codec_configuration, AVPacket* packet, AVFrame* received_frame): m_functions(functions), m_device(device)- , m_codec_context(codec_context)+ , m_codec_id(codec_id)+ , m_device_context(device_context), m_packet(packet), m_received_frame(received_frame)+ , m_codec_configuration(move(codec_configuration)){}+DecoderErrorOr<AVCodecContext*> FFmpegVulkanVideoDecoder::create_codec_context()+{+ auto const* codec = vulkan_capable_decoder(m_functions, m_codec_id);+ VERIFY(codec != nullptr);++ auto* codec_context = m_functions.avcodec_alloc_context3(codec);+ if (codec_context == nullptr)+ return DecoderError::format(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg codec context for codec {}", m_codec_id);+ ArmedScopeGuard free_codec_context = [&] { m_functions.avcodec_free_context(&codec_context); };++ TRY(set_codec_initialization_data(m_functions, *codec_context, m_codec_id, m_codec_configuration.span()));+ // The device already decodes several frames at a time, and frame threading would only hold frames back.+ VERIFY(m_functions.av_opt_set_int(codec_context, "threads", 1, 0) == 0);+ codec_context->max_pixels = MAX_VIDEO_FRAME_AREA;+ codec_context->hw_device_ctx = m_functions.av_buffer_ref(m_device_context);+ if (codec_context->hw_device_ctx == nullptr)+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to reference the FFmpeg Vulkan device context"sv);+ codec_context->get_format = negotiate_pixel_format;+ codec_context->get_buffer2 = get_buffer;+ codec_context->opaque = this;+ // Only the bundled FFmpeg decodes AV1, and it is patched to know this flag.+ if (m_codec_id == CodecID::AV1 && !PlatformFeatures::ProcessFeatures::the().is_enabled(PlatformFeatures::Feature::VulkanVideoBundledFFmpegAV1KeepSequenceHeaderEnableRefMVsFlag))+ codec_context->hwaccel_flags |= AV_HWACCEL_FLAG_LADYBIRD_CLEAR_UNUSED_REF_FRAME_MVS;++ if (m_functions.avcodec_open2(codec_context, codec, nullptr) < 0)+ return DecoderError::format(DecoderErrorCategory::Unknown, "Unknown error occurred when opening FFmpeg codec {}", m_codec_id);++ free_codec_context.disarm();+ return codec_context;+}++DecoderErrorOr<void> FFmpegVulkanVideoDecoder::replace_codec_context()+{+ // The frames the old context still holds back for reordering come out before the new one starts.+ m_packet->data = nullptr;+ m_packet->size = 0;+ m_packet->pts = 0;+ m_packet->dts = 0;+ if (m_functions.avcodec_send_packet(m_codec_context, m_packet) == 0)+ TRY(receive_decoded_frames(EndOfStreamIsFinal::No));++ auto* codec_context = TRY(create_codec_context());+ m_functions.avcodec_free_context(&m_codec_context);+ m_functions.av_buffer_unref(&m_codec_frames_context);+ m_codec_context = codec_context;+ m_codec_context_has_negotiated = false;+ m_codec_context_must_be_replaced = false;+ return {};+}+FFmpegVulkanVideoDecoder::~FFmpegVulkanVideoDecoder(){Vector<DecodingFrame> decoding_frames;@@ -501,17 +530,24 @@ FFmpegVulkanVideoDecoder::~FFmpegVulkanVideoDecoder()// A stalled copy may still be pending on its command buffer.if (m_copy_command_pool != VK_NULL_HANDLE && !m_copy_stalled)vkDestroyCommandPool(m_device.logical_device(), m_copy_command_pool, nullptr);+ m_surfaces_by_image.clear();+ m_functions.av_buffer_unref(&m_frames_context_of_surfaces);m_functions.av_buffer_unref(&m_exportable_frames_context);m_functions.av_buffer_unref(&m_frames_context_copied_from);m_functions.av_packet_free(&m_packet);m_functions.av_frame_free(&m_received_frame);m_functions.avcodec_free_context(&m_codec_context);+ m_functions.av_buffer_unref(&m_codec_frames_context);}AVPixelFormat FFmpegVulkanVideoDecoder::negotiate_pixel_format(AVCodecContext* codec_context, AVPixelFormat const* pixel_formats){auto& decoder = *static_cast<FFmpegVulkanVideoDecoder*>(codec_context->opaque);+ if (decoder.m_codec_context_has_negotiated) {+ decoder.m_codec_context_must_be_replaced = true;+ return AV_PIX_FMT_NONE;+ }for (auto const* pixel_format = pixel_formats; *pixel_format != AV_PIX_FMT_NONE; pixel_format++) {if (*pixel_format != AV_PIX_FMT_VULKAN)continue;@@ -520,6 +556,7 @@ AVPixelFormat FFmpegVulkanVideoDecoder::negotiate_pixel_format(AVCodecContext* cdecoder.m_pixel_format_error = result.release_error();return AV_PIX_FMT_NONE;}+ decoder.m_codec_context_has_negotiated = true;return AV_PIX_FMT_VULKAN;}decoder.m_pixel_format_error = DecoderError::with_description(DecoderErrorCategory::NotImplemented, "FFmpeg cannot decode this stream through Vulkan"sv);@@ -571,6 +608,10 @@ DecoderErrorOr<void> FFmpegVulkanVideoDecoder::create_frames_context()if (m_functions.av_hwframe_ctx_init(frames_reference) < 0)return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "FFmpeg could not create Vulkan frames"sv);+ VERIFY(m_codec_frames_context == nullptr);+ m_codec_frames_context = m_functions.av_buffer_ref(frames_reference);+ if (m_codec_frames_context == nullptr)+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Could not reference the decoded frames' context"sv);m_functions.av_buffer_unref(&m_codec_context->hw_frames_ctx);m_codec_context->hw_frames_ctx = frames_reference;free_frames_reference.disarm();@@ -582,7 +623,29 @@ DecoderErrorOr<void> FFmpegVulkanVideoDecoder::receive_coded_data(CodedFrame conif (m_pixel_format_error.has_value())return *m_pixel_format_error;+ if (auto configuration = coded_frame.new_codec_configuration(); configuration.has_value() && !configuration->is_empty())+ m_codec_configuration = DECODER_TRY_ALLOC(FixedArray<u8>::create(*configuration));+auto key = TRY(m_frames_awaiting_output.add(coded_frame, intent));+ auto result = decode_coded_frame(coded_frame, key);+ if (!m_codec_context_must_be_replaced)+ return result;++ // A new context lacks the earlier frames, so only a keyframe can start it.+ if (!coded_frame.is_keyframe())+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "The stream changes its format on a frame other than a keyframe"sv);++ TRY(replace_codec_context());+ result = decode_coded_frame(coded_frame, key);+ if (result.is_error() && result.error().category() == DecoderErrorCategory::NotImplemented)+ return result;+ if (result.is_error() || m_codec_context_must_be_replaced)+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "The stream changes its format on a keyframe that a new decoder cannot start from"sv);+ return {};+}++DecoderErrorOr<void> FFmpegVulkanVideoDecoder::decode_coded_frame(CodedFrame const& coded_frame, u64 key)+{auto result = send_coded_frame(m_functions, *m_codec_context, *m_packet, coded_frame, key);// FFmpeg takes no more until the frames it has decoded are taken out.if (result.is_error() && result.error().category() == DecoderErrorCategory::TryAgain) {@@ -612,14 +675,14 @@ void FFmpegVulkanVideoDecoder::signal_end_of_stream()}}-DecoderErrorOr<void> FFmpegVulkanVideoDecoder::receive_decoded_frames()+DecoderErrorOr<void> FFmpegVulkanVideoDecoder::receive_decoded_frames(EndOfStreamIsFinal end_of_stream_is_final){while (true) {auto result = m_functions.avcodec_receive_frame(m_codec_context, m_received_frame);if (result == AVERROR(EAGAIN))return {};if (result == AVERROR_EOF) {- if (!m_received_end_of_stream) {+ if (end_of_stream_is_final == EndOfStreamIsFinal::Yes && !m_received_end_of_stream) {m_received_end_of_stream = true;DecodingFrame end_of_stream;end_of_stream.generation = m_generation;@@ -784,7 +847,7 @@ DecoderErrorOr<void> FFmpegVulkanVideoDecoder::prepare_to_copy_frames_from(AVFraif (m_exportable_drm_format_modifiers.is_empty())return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "No DRM format modifier can export copies of the decoded images"sv);- auto* reference = m_functions.av_hwframe_ctx_alloc(m_codec_context->hw_device_ctx);+ auto* reference = m_functions.av_hwframe_ctx_alloc(m_device_context);if (reference == nullptr)return DecoderError::with_description(DecoderErrorCategory::Memory, "Could not allocate a frames context for exportable frames"sv);ArmedScopeGuard free_reference = [&] { m_functions.av_buffer_unref(&reference); };@@ -972,11 +1035,14 @@ DecoderErrorOr<AVFrame*> FFmpegVulkanVideoDecoder::copy_into_exportable_frame(AVDecoderErrorOr<NonnullRefPtr<VideoSurface>> FFmpegVulkanVideoDecoder::surface_for_exported_frame(AVFrame const& frame, AVFrame const& exported_frame){- auto const& frames_context = frames_context_of(frame);- if (&frames_context != m_frames_context_of_surfaces) {+ if (m_frames_context_of_surfaces == nullptr || m_frames_context_of_surfaces->data != frame.hw_frames_ctx->data) {m_surfaces_by_image.clear();- m_frames_context_of_surfaces = &frames_context;+ m_functions.av_buffer_unref(&m_frames_context_of_surfaces);+ m_frames_context_of_surfaces = m_functions.av_buffer_ref(frame.hw_frames_ctx);+ if (m_frames_context_of_surfaces == nullptr)+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Could not reference the exported frames' context"sv);}+ auto const& frames_context = frames_context_of(frame);auto const& vulkan_frame = *reinterpret_cast<AVVkFrame const*>(frame.data[0]);u64 image_key = 0;diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.hindex 0cad77816b9..0b14574d50e 100644--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h@@ -9,6 +9,7 @@#ifdef USE_VULKAN_DMABUF_IMAGES# include <AK/ConditionVariable.h>+# include <AK/FixedArray.h># include <AK/HashMap.h># include <AK/Mutex.h># include <AK/Queue.h>@@ -77,13 +78,21 @@ private:u8 bit_depth { 0 };};- FFmpegVulkanVideoDecoder(FFmpegFunctions const&, VulkanVideoDevice&, AVCodecContext*, AVPacket*, AVFrame*);+ enum class EndOfStreamIsFinal : u8 {+ Yes,+ No,+ };++ FFmpegVulkanVideoDecoder(FFmpegFunctions const&, VulkanVideoDevice&, CodecID, AVBufferRef* device_context, FixedArray<u8> codec_configuration, AVPacket*, AVFrame*);+ DecoderErrorOr<AVCodecContext*> create_codec_context();+ DecoderErrorOr<void> replace_codec_context();static AVPixelFormat negotiate_pixel_format(AVCodecContext*, AVPixelFormat const*);static int get_buffer(AVCodecContext*, AVFrame*, int flags);DecoderErrorOr<void> create_frames_context();- DecoderErrorOr<void> receive_decoded_frames();+ DecoderErrorOr<void> decode_coded_frame(CodedFrame const&, u64 key);+ DecoderErrorOr<void> receive_decoded_frames(EndOfStreamIsFinal = EndOfStreamIsFinal::Yes);void enqueue_decoding_frame(DecodingFrame);void free_decoding_frames(Vector<DecodingFrame>&);@@ -95,6 +104,9 @@ private:FFmpegFunctions const& m_functions;VulkanVideoDevice& m_device;+ CodecID m_codec_id;+ // The process keeps the device context alive.+ AVBufferRef* m_device_context { nullptr };AVCodecContext* m_codec_context { nullptr };AVPacket* m_packet { nullptr };AVFrame* m_received_frame { nullptr };@@ -103,6 +115,15 @@ private:// Only the caller's thread uses these.VideoFramesAwaitingOutput m_frames_awaiting_output;Optional<DecoderError> m_pixel_format_error;+ // Replacing the codec context starts it from the latest configuration the stream has carried.+ FixedArray<u8> m_codec_configuration;+ // A second negotiation would start a Vulkan session that uses the old one's pictures after FFmpeg frees parts of+ // them, so a context that would negotiate again is replaced instead.+ bool m_codec_context_has_negotiated { false };+ bool m_codec_context_must_be_replaced { false };+ // A refused negotiation drops the codec context's own reference to its frames, so this one keeps them alive until+ // the context's pictures are freed.+ AVBufferRef* m_codec_frames_context { nullptr };bool m_received_end_of_stream { false };Vector<u64> m_drm_format_modifiers;VkImageDrmFormatModifierListCreateInfoEXT m_drm_format_modifier_list {};@@ -125,8 +146,8 @@ private:RefPtr<Threading::Thread> m_completion_thread;// Only the completion thread uses these. A frames context recycles its images, so each one's surface is kept and- // recognized when it comes back.- AVHWFramesContext const* m_frames_context_of_surfaces { nullptr };+ // recognized when it comes back. The context is referenced so that a new one can't take its address.+ AVBufferRef* m_frames_context_of_surfaces { nullptr };HashMap<u64, NonnullRefPtr<VideoSurface>> m_surfaces_by_image;// Only the completion thread uses these. The decoded frames' context is kept because the exportable frames'diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txtindex 35b6150a86a..7a87a71fd69 100644--- a/Tests/LibMedia/CMakeLists.txt+++ b/Tests/LibMedia/CMakeLists.txt@@ -62,6 +62,9 @@ if (WIN32)endif()if (LINUX)list(APPEND TEST_SOURCES TestH264Decode.cpp)+ if (USE_VULKAN_DMABUF_IMAGES)+ list(APPEND TEST_SOURCES TestFFmpegVulkanDecode.cpp)+ endif()# Loads the bundled libavcodec in place of a system one, which needs it to be a shared library.find_library(LADYBIRD_BUNDLED_LIBAVCODEC NAMES ${AVCODEC_LIBRARIES} PATHS ${AVCODEC_LIBRARY_DIRS} NO_DEFAULT_PATH REQUIRED)@@ -73,6 +76,10 @@ endif()target_sources(TestLibMedia PRIVATE ${TEST_SOURCES})target_link_libraries(TestLibMedia PRIVATE LibAudio LibFileSystem LibGfx LibIPC LibMedia LibMediaCodecs LibThreading)+if ("TestFFmpegVulkanDecode.cpp" IN_LIST TEST_SOURCES)+ target_link_libraries(TestLibMedia PRIVATE LibPlatformFeatures Vulkan::Vulkan)+endif()+if ("TestSystemFFmpeg.cpp" IN_LIST TEST_SOURCES)set_property(SOURCE TestSystemFFmpeg.cpp APPEND PROPERTY COMPILE_DEFINITIONS LADYBIRD_BUNDLED_LIBAVCODEC_PATH="${LADYBIRD_BUNDLED_LIBAVCODEC}")endif()diff --git a/Tests/LibMedia/TestFFmpegVulkanDecode.cpp b/Tests/LibMedia/TestFFmpegVulkanDecode.cppnew file mode 100644index 00000000000..3d2e67230db--- /dev/null+++ b/Tests/LibMedia/TestFFmpegVulkanDecode.cpp@@ -0,0 +1,186 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/ScopeGuard.h>+#include <LibGfx/VulkanContext.h>+#include <LibMedia/DemuxerRegistry.h>+#include <LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h>+#include <LibMediaCodecs/FFmpeg/SystemFFmpeg.h>+#include <LibMediaCodecs/VideoFrame.h>+#include <LibMediaCodecs/Vulkan/VulkanVideoDevice.h>+#include <LibPlatformFeatures/ProcessFeatures.h>++#include "TestMediaCommon.h"++namespace {++bool create_process_device()+{+ if (Media::VulkanVideoDevice::the() != nullptr)+ return true;++ // Each suite runs in its own process, so this sets up the process's features once, as VideoDecoderServer would+ // with nothing blocked.+ static auto initialized_process = [] {+ PlatformFeatures::ProcessFeatures::initialize_for_current_process(MUST(PlatformFeatures::ProcessFeatures::from_string(PlatformFeatures::FeatureProcess::VideoDecoderServer,+ "vulkan_video,vulkan_video.bundled_ffmpeg,vulkan_video.bundled_ffmpeg.direct_export,vulkan_video.bundled_ffmpeg.vp9,vulkan_video.bundled_ffmpeg.av1,"+ "vulkan_video.system_ffmpeg,vulkan_video.system_ffmpeg.direct_export,vulkan_video.system_ffmpeg.h264,vulkan_video.system_ffmpeg.h265"sv)));+ Media::FFmpeg::SystemFFmpeg::load();+ return true;+ }();+ (void)initialized_process;++ VkApplicationInfo application_info {};+ application_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;+ application_info.apiVersion = VK_API_VERSION_1_3;+ VkInstanceCreateInfo instance_info {};+ instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;+ instance_info.pApplicationInfo = &application_info;+ VkInstance instance = VK_NULL_HANDLE;+ if (vkCreateInstance(&instance_info, nullptr, &instance) != VK_SUCCESS)+ return false;+ ScopeGuard destroy_instance = [&] { vkDestroyInstance(instance, nullptr); };++ u32 count = 0;+ vkEnumeratePhysicalDevices(instance, &count, nullptr);+ Vector<VkPhysicalDevice> physical_devices;+ physical_devices.resize(count);+ vkEnumeratePhysicalDevices(instance, &count, physical_devices.data());+ for (auto* physical_device : physical_devices) {+ if (!Media::VulkanVideoDevice::create_for_process(Gfx::gpu_device_identity_of(physical_device)).is_error())+ return true;+ }+ return false;+}++struct DecodedFrame {+ AK::Duration timestamp;+ Gfx::Size<u32> size;+};++struct Decoding {+ NonnullOwnPtr<Media::FFmpeg::FFmpegVulkanVideoDecoder> decoder;+ NonnullRefPtr<Media::Demuxer> demuxer;+ Media::Track track;+ mutable size_t accepted_sample_count { 1 };++ Media::DecoderErrorOr<NonnullRefPtr<Media::VideoFrame>> next_frame() const+ {+ while (true) {+ auto frame_result = decoder->take_next_output(track.video_data().cicp);+ if (!frame_result.is_error() || frame_result.error().category() != Media::DecoderErrorCategory::NeedsMoreInput)+ return frame_result;++ auto sample_result = demuxer->get_next_sample_for_track(track);+ if (sample_result.is_error()) {+ decoder->signal_end_of_stream();+ continue;+ }+ TRY(decoder->receive_coded_data(sample_result.release_value(), Media::DecodeIntent::Output));+ accepted_sample_count++;+ }+ }++ Media::DecoderError decode_all(Vector<DecodedFrame>& frames) const+ {+ while (true) {+ auto frame_result = next_frame();+ if (frame_result.is_error())+ return frame_result.release_error();+ auto frame = frame_result.release_value();+ frames.append({ frame->timestamp(), frame->size() });+ }+ }+};++Optional<Decoding> open_decoding(StringView path, Media::CodecID codec_id)+{+ if (!create_process_device()) {+ warnln("No Vulkan device can decode video, skipping");+ return {};+ }++ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));+ auto demuxer = MUST(Media::create_demuxer(stream));+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video));+ VERIFY(track.has_value());+ MUST(demuxer->create_context_for_track(*track));++ auto first_sample = MUST(demuxer->get_next_sample_for_track(*track));+ auto start_decoding = [&] -> Media::DecoderErrorOr<NonnullOwnPtr<Media::FFmpeg::FFmpegVulkanVideoDecoder>> {+ auto decoder = TRY(Media::FFmpeg::FFmpegVulkanVideoDecoder::try_create(codec_id, first_sample.new_codec_configuration().value_or({})));+ // Whether the device can decode and export the stream is only known once the first frame negotiates its format.+ TRY(decoder->receive_coded_data(first_sample, Media::DecodeIntent::Output));+ return decoder;+ };+ auto decoder_result = start_decoding();+ if (decoder_result.is_error()) {+ if (decoder_result.error().category() == Media::DecoderErrorCategory::NotImplemented) {+ warnln("No Vulkan decoder for codec {}, skipping: {}", codec_id, decoder_result.error().description());+ return {};+ }+ FAIL(ByteString::formatted("Could not start Vulkan decoding of codec {}: {}", codec_id, decoder_result.error().description()));+ return {};+ }+ return Decoding { decoder_result.release_value(), move(demuxer), track.release_value() };+}++void expect_every_frame_across_a_size_change(StringView path, Media::CodecID codec_id, size_t frame_count, Gfx::Size<u32> first_size, Gfx::Size<u32> second_size)+{+ auto decoding = open_decoding(path, codec_id);+ if (!decoding.has_value())+ return;++ Vector<DecodedFrame> frames;+ auto error = decoding->decode_all(frames);+ EXPECT_EQ(error.category(), Media::DecoderErrorCategory::EndOfStream);+ EXPECT_EQ(frames.size(), frame_count);++ size_t size_changes = 0;+ for (size_t i = 1; i < frames.size(); i++) {+ EXPECT(frames[i - 1].timestamp < frames[i].timestamp);+ if (frames[i - 1].size != frames[i].size)+ size_changes++;+ }+ EXPECT_EQ(size_changes, 1u);+ if (!frames.is_empty()) {+ EXPECT_EQ(frames.first().size, first_size);+ EXPECT_EQ(frames.last().size, second_size);+ }+}++}++TEST_CASE(vp9_keyframe_size_change_continues_in_a_new_codec_context)+{+ expect_every_frame_across_a_size_change("./vp9_resize.webm"sv, Media::CodecID::VP9, 2, { 320, 240 }, { 640, 480 });+}++TEST_CASE(h264_size_change_keeps_reordered_frames)+{+ expect_every_frame_across_a_size_change("./h264_keyframe_resize.mkv"sv, Media::CodecID::H264, 20, { 320, 240 }, { 160, 120 });+}++TEST_CASE(h265_size_change_keeps_reordered_frames)+{+ expect_every_frame_across_a_size_change("./h265_keyframe_resize.mkv"sv, Media::CodecID::H265, 20, { 320, 240 }, { 256, 160 });+}++TEST_CASE(vp9_inter_frame_size_change_needs_another_decoder)+{+ auto decoding = open_decoding("./vp9_inter_frame_resize.webm"sv, Media::CodecID::VP9);+ if (!decoding.has_value())+ return;++ Vector<DecodedFrame> frames;+ auto error = decoding->decode_all(frames);+ EXPECT_EQ(error.category(), Media::DecoderErrorCategory::NotImplemented);+ // The keyframe decodes, and the inter-frame after it changes the size.+ EXPECT_EQ(decoding->accepted_sample_count, 1u);+ for (auto const& frame : frames)+ EXPECT_EQ(frame.size, Gfx::Size<u32>(1280, 720));+}diff --git a/Tests/LibMedia/h264_keyframe_resize.mkv b/Tests/LibMedia/h264_keyframe_resize.mkvnew file mode 100644index 00000000000..62338786486Binary files /dev/null and b/Tests/LibMedia/h264_keyframe_resize.mkv differdiff --git a/Tests/LibMedia/h265_keyframe_resize.mkv b/Tests/LibMedia/h265_keyframe_resize.mkvnew file mode 100644index 00000000000..0103f7c1d1dBinary files /dev/null and b/Tests/LibMedia/h265_keyframe_resize.mkv differdiff --git a/Tests/LibMedia/vp9_inter_frame_resize.webm b/Tests/LibMedia/vp9_inter_frame_resize.webmnew file mode 100644index 00000000000..c976ec1630bBinary files /dev/null and b/Tests/LibMedia/vp9_inter_frame_resize.webm differ