Truly independent web browser
LibMedia: Decode AAC through Windows Media Foundation
Zaggy102464279cb7f789
diff --git a/Libraries/LibMedia/CMakeLists.txt b/Libraries/LibMedia/CMakeLists.txtindex 634d6a354cd..2f986435392 100644--- a/Libraries/LibMedia/CMakeLists.txt+++ b/Libraries/LibMedia/CMakeLists.txt@@ -82,6 +82,12 @@ if (APPLE))endif()+if (WIN32)+ list(APPEND SOURCES+ WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.cpp+ )+endif()+compile_ipc(VideoPresentation/VideoPresentationClient.ipc VideoPresentation/VideoPresentationClientEndpoint.h)compile_ipc(VideoPresentation/VideoPresentationServer.ipc VideoPresentation/VideoPresentationServerEndpoint.h)@@ -93,6 +99,10 @@ if (APPLE)target_link_libraries(LibMedia PRIVATE "-framework AudioToolbox")endif()+if (WIN32)+ target_link_libraries(LibMedia PRIVATE mfplat mfuuid)+endif()+target_sources(LibMedia PRIVATEFFmpeg/FFmpegAudioConverter.cppFFmpeg/FFmpegAudioDecoder.cppdiff --git a/Libraries/LibMedia/DecoderRegistrations.cpp b/Libraries/LibMedia/DecoderRegistrations.cppindex 2400ee2b895..b44824c5db4 100644--- a/Libraries/LibMedia/DecoderRegistrations.cpp+++ b/Libraries/LibMedia/DecoderRegistrations.cpp@@ -15,6 +15,9 @@#ifdef AK_OS_LINUX# include <LibMedia/FFmpeg/SystemFFmpegDecoders.h>#endif+#ifdef AK_OS_WINDOWS+# include <LibMedia/WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.h>+#endifnamespace Media {@@ -59,11 +62,21 @@ static DecoderErrorOr<NonnullOwnPtr<AudioDecoder>> create_audiotoolbox_audio_dec}#endif+#ifdef AK_OS_WINDOWS+static DecoderErrorOr<NonnullOwnPtr<AudioDecoder>> create_windows_media_foundation_audio_decoder(CodecID codec_id, Audio::SampleSpecification const& sample_specification, ReadonlyBytes codec_initialization_data)+{+ return NonnullOwnPtr<AudioDecoder> { TRY(WindowsMediaFoundation::WindowsMediaFoundationAudioDecoder::try_create(codec_id, sample_specification, codec_initialization_data)) };+}+#endif+ReadonlySpan<AudioDecoderRegistration> audio_decoders(){static constexpr Array decoders {#ifdef AK_OS_MACOSAudioDecoderRegistration { AudioToolbox::AudioToolboxAudioDecoder::capabilities, create_audiotoolbox_audio_decoder },+#endif+#ifdef AK_OS_WINDOWS+ AudioDecoderRegistration { WindowsMediaFoundation::WindowsMediaFoundationAudioDecoder::capabilities, create_windows_media_foundation_audio_decoder },#endifAudioDecoderRegistration { FFmpeg::FFmpegAudioDecoder::capabilities, create_ffmpeg_audio_decoder },#ifdef AK_OS_LINUXdiff --git a/Libraries/LibMedia/WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.cpp b/Libraries/LibMedia/WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.cppnew file mode 100644index 00000000000..f57cce65907--- /dev/null+++ b/Libraries/LibMedia/WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.cpp@@ -0,0 +1,417 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Array.h>+#include <AK/GenericShorthands.h>+#include <AK/NeverDestroyed.h>+#include <AK/NumericLimits.h>+#include <AK/ScopeGuard.h>+#include <LibAudio/WindowsChannelMask.h>+#include <LibMedia/WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.h>+#include <LibMediaCodecs/AudioBlock.h>+#include <LibMediaCodecs/Codecs/AAC.h>+#include <LibMediaCodecs/CodedFrame.h>+#include <LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundation.h>++namespace Media::WindowsMediaFoundation {++struct WindowsMediaFoundationAudioDecoder::Transform {+ AK_ALLOC_WITH_KMALLOC;++ ~Transform()+ {+ if (output_stream_info.has_value())+ transform->ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0);+ }++ ComPtr<IMFTransform> transform;+ // Absent until the transform has accepted an output type.+ Optional<OutputStreamInfo> output_stream_info;+ Audio::SampleSpecification output_sample_specification;+ bool outputs_float { true };++ // A packet the transform refused until it has output what it is holding.+ ComPtr<IMFSample> pending_input;+ bool drain_requested { false };+ bool next_input_is_discontinuous { false };+ Vector<AK::Duration, 4> pending_coded_frame_timestamps;+};++namespace {++bool aac_audio_object_type_is_supported(ParsedCodec const& codec)+{+ auto parameters = codec.aac_parameters();+ if (!parameters.has_value())+ return true;+ if (parameters->object_type_indication == Codecs::AAC::MPEG2_LOW_COMPLEXITY_OBJECT_TYPE_INDICATION)+ return true;+ if (parameters->object_type_indication != Codecs::AAC::MPEG4_AUDIO_OBJECT_TYPE_INDICATION)+ return false;+ if (!parameters->audio_object_type.has_value())+ return true;+ return first_is_one_of(*parameters->audio_object_type,+ Codecs::AAC::LOW_COMPLEXITY_AUDIO_OBJECT_TYPE,+ Codecs::AAC::SPECTRAL_BAND_REPLICATION_AUDIO_OBJECT_TYPE,+ Codecs::AAC::PARAMETRIC_STEREO_AUDIO_OBJECT_TYPE);+}++DecoderErrorOr<ComPtr<IMFMediaType>> create_aac_input_type(Audio::SampleSpecification const& container_sample_specification, ReadonlyBytes audio_specific_config)+{+ // The transform takes the fields of HEAACWAVEINFO that follow its WAVEFORMATEX, then the AudioSpecificConfig. A+ // payload type of zero says that packets are raw access units.+ static constexpr u16 NO_AUDIO_PROFILE_SPECIFIED = 0xFE;+ Vector<u8, 64> user_data;+ user_data.resize(12);+ user_data[2] = NO_AUDIO_PROFILE_SPECIFIED;+ DECODER_TRY_ALLOC(user_data.try_append(audio_specific_config.data(), audio_specific_config.size()));++ ComPtr<IMFMediaType> type;+ if (FAILED(MFCreateMediaType(&type))+ || FAILED(type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio))+ || FAILED(type->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_AAC))+ || FAILED(type->SetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, container_sample_specification.sample_rate()))+ || FAILED(type->SetUINT32(MF_MT_AUDIO_NUM_CHANNELS, container_sample_specification.channel_count()))+ || FAILED(type->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 16))+ || FAILED(type->SetUINT32(MF_MT_AAC_PAYLOAD_TYPE, 0))+ || FAILED(type->SetBlob(MF_MT_USER_DATA, user_data.data(), user_data.size())))+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to create a Media Foundation media type"sv);+ return type;+}++DecoderErrorOr<Audio::ChannelMap> output_channel_map(IMFMediaType& output_type, u32 channel_count)+{+ UINT32 channel_mask = 0;+ if (FAILED(output_type.GetUINT32(MF_MT_AUDIO_CHANNEL_MASK, &channel_mask))) {+ if (channel_count == 1)+ return Audio::ChannelMap::mono();+ if (channel_count == 2)+ return Audio::ChannelMap::stereo();+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "Media Foundation output {} channels without saying where they go", channel_count);+ }++ auto channel_map_or_error = Audio::windows_channel_mask_to_channel_map(channel_mask);+ if (channel_map_or_error.is_error())+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "Media Foundation output an unsupported channel layout: {}", channel_map_or_error.error());+ auto channel_map = channel_map_or_error.release_value();+ if (channel_map.channel_count() != channel_count)+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "Media Foundation output a channel layout that does not match its channel count"sv);+ return channel_map;+}++DecoderErrorOr<void> negotiate_output_format(WindowsMediaFoundationAudioDecoder::Transform& transform)+{+ auto& media_transform = *transform.transform.Get();+ auto output_type_or_error = set_first_acceptable_output_type(media_transform, [](GUID const& subtype) { return subtype == MFAudioFormat_Float; });+ if (output_type_or_error.is_error()) {+ output_type_or_error = set_first_acceptable_output_type(media_transform, [](GUID const& subtype) { return subtype == MFAudioFormat_PCM; });+ if (output_type_or_error.is_error())+ return output_type_or_error.release_error();+ }+ auto output_type = output_type_or_error.release_value();++ GUID subtype = GUID_NULL;+ UINT32 bits_per_sample = 0;+ UINT32 sample_rate = 0;+ UINT32 channel_count = 0;+ output_type->GetGUID(MF_MT_SUBTYPE, &subtype);+ output_type->GetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, &bits_per_sample);+ if (FAILED(output_type->GetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, &sample_rate)) || sample_rate == 0)+ return DecoderError::with_description(DecoderErrorCategory::Corrupted, "Media Foundation output no sample rate"sv);+ if (FAILED(output_type->GetUINT32(MF_MT_AUDIO_NUM_CHANNELS, &channel_count)) || channel_count == 0 || channel_count > Audio::ChannelMap::capacity())+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "Media Foundation cannot output {} channels", channel_count);++ auto outputs_float = subtype == MFAudioFormat_Float;+ if (bits_per_sample != (outputs_float ? 32 : 16))+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "Media Foundation output {}-bit samples", bits_per_sample);++ auto channel_map = TRY(output_channel_map(*output_type.Get(), channel_count));+ auto stream_info = TRY(output_stream_info(media_transform));++ auto was_streaming = transform.output_stream_info.has_value();+ transform.output_stream_info = stream_info;+ transform.output_sample_specification = Audio::SampleSpecification { sample_rate, channel_map };+ transform.outputs_float = outputs_float;+ if (!was_streaming && FAILED(media_transform.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)))+ return DecoderError::with_description(DecoderErrorCategory::Unknown, "Media Foundation decoder refused to start streaming"sv);+ return {};+}++DecoderErrorOr<void> submit_input(WindowsMediaFoundationAudioDecoder::Transform& transform, ComPtr<IMFSample> sample)+{+ auto result = transform.transform->ProcessInput(0, sample.Get(), 0);+ if (result == MF_E_NOTACCEPTING) {+ transform.pending_input = move(sample);+ return {};+ }+ if (FAILED(result))+ return DecoderError::format(DecoderErrorCategory::Corrupted, "Media Foundation decoder rejected a packet with result {:#x}", static_cast<u32>(result));+ return {};+}++void drain_unless_input_is_pending(WindowsMediaFoundationAudioDecoder::Transform& transform)+{+ if (transform.pending_input || !transform.drain_requested)+ return;+ transform.transform->ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0);+ transform.transform->ProcessMessage(MFT_MESSAGE_COMMAND_DRAIN, 0);+}++void request_drain(WindowsMediaFoundationAudioDecoder::Transform& transform)+{+ transform.drain_requested = true;+ drain_unless_input_is_pending(transform);+}++}++Optional<DecoderCapabilities> WindowsMediaFoundationAudioDecoder::capabilities(ParsedCodec const& codec)+{+ if (codec.codec_id() != CodecID::AAC || !aac_audio_object_type_is_supported(codec))+ return {};++ // Activating a transform to answer this costs enough that the answer is worth keeping.+ static bool const transform_is_available = [] {+ Audio::SampleSpecification sample_specification { 48'000, Audio::ChannelMap::stereo() };+ auto configuration = Codecs::AAC::create_configuration_record(Codecs::AAC::LOW_COMPLEXITY_AUDIO_OBJECT_TYPE, sample_specification.sample_rate(), sample_specification.channel_count());+ if (configuration.is_error())+ return false;+ auto input_type = create_aac_input_type(sample_specification, configuration.value().span());+ if (input_type.is_error())+ return false;+ return !create_decoder_transform(CodecID::AAC, *input_type.value().Get()).is_error();+ }();+ if (!transform_is_available)+ return {};+ return DecoderCapabilities { .smooth = true, .power_efficient = true };+}++DecoderErrorOr<NonnullOwnPtr<WindowsMediaFoundationAudioDecoder>> WindowsMediaFoundationAudioDecoder::try_create(CodecID codec_id, Audio::SampleSpecification const& sample_specification, ReadonlyBytes codec_initialization_data)+{+ if (codec_id != CodecID::AAC)+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "Media Foundation has no audio decoder for codec {}", codec_id);++ auto codec_configuration = DECODER_TRY_ALLOC(FixedArray<u8>::create(codec_initialization_data));+ return DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) WindowsMediaFoundationAudioDecoder(codec_id, sample_specification, move(codec_configuration))));+}++WindowsMediaFoundationAudioDecoder::WindowsMediaFoundationAudioDecoder(CodecID codec_id, Audio::SampleSpecification const& sample_specification, FixedArray<u8>&& codec_configuration)+ : m_codec_id(codec_id)+ , m_container_sample_specification(sample_specification)+ , m_codec_configuration(move(codec_configuration))+{+}++WindowsMediaFoundationAudioDecoder::~WindowsMediaFoundationAudioDecoder() = default;++DecoderErrorOr<void> WindowsMediaFoundationAudioDecoder::ensure_transform_for_frame(CodedFrame const& coded_frame)+{+ auto new_configuration = coded_frame.new_codec_configuration();+ auto configuration_changed = new_configuration.has_value() && !new_configuration->is_empty() && *new_configuration != m_codec_configuration.span();+ if (m_transform != nullptr && !configuration_changed)+ return {};++ auto configuration = configuration_changed ? *new_configuration : m_codec_configuration.span();+ if (configuration.is_empty())+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "Media Foundation cannot decode AAC without an Audio Specific Config"sv);++ auto input_type = TRY(create_aac_input_type(m_container_sample_specification, configuration));+ auto transform = DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) Transform));+ transform->transform = TRY(create_decoder_transform(m_codec_id, *input_type.Get()));+ // Some decoders refuse every output format until they have seen input, so this is retried when they ask.+ (void)negotiate_output_format(*transform);++ if (configuration_changed)+ m_codec_configuration = DECODER_TRY_ALLOC(FixedArray<u8>::create(configuration));++ if (m_transform == nullptr) {+ m_transform = move(transform);+ return {};+ }+ request_drain(*m_transform);+ m_replacement_transform = move(transform);+ return {};+}++DecoderErrorOr<void> WindowsMediaFoundationAudioDecoder::receive_coded_data(CodedFrame const& coded_frame)+{+ if (m_end_of_stream_signaled)+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "Media Foundation decoder has been drained"sv);+ if (m_replacement_transform != nullptr || (m_transform != nullptr && m_transform->pending_input))+ return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Media Foundation decoder has not taken the previous packet yet"sv);+ if (coded_frame.data().size() > NumericLimits<DWORD>::max())+ return DecoderError::corrupted("Coded frame is too large for Media Foundation"sv);++ TRY(ensure_transform_for_frame(coded_frame));++ auto& transform = m_replacement_transform != nullptr ? *m_replacement_transform : *m_transform;+ auto sample = TRY(create_input_sample(coded_frame.data(), coded_frame.decoded_start_timestamp(), coded_frame.duration() + coded_frame.leading_discard() + coded_frame.trailing_discard()));+ if (transform.next_input_is_discontinuous)+ sample->SetUINT32(MFSampleExtension_Discontinuity, TRUE);+ TRY(submit_input(transform, move(sample)));+ transform.next_input_is_discontinuous = false;+ DECODER_TRY_ALLOC(transform.pending_coded_frame_timestamps.try_append(coded_frame.decoded_start_timestamp()));+ m_discard_intervals.add_intervals_for_frame(coded_frame);+ return {};+}++void WindowsMediaFoundationAudioDecoder::signal_end_of_stream()+{+ m_end_of_stream_signaled = true;+ if (m_replacement_transform != nullptr)+ request_drain(*m_replacement_transform);+ else if (m_transform != nullptr)+ request_drain(*m_transform);+}++void WindowsMediaFoundationAudioDecoder::switch_to_replacement_transform()+{+ m_transform = m_replacement_transform.release_nonnull();+}++DecoderErrorOr<void> WindowsMediaFoundationAudioDecoder::copy_output_sample(Transform& transform, IMFSample& sample)+{+ // The sample is copied, since a block may take only part of it.+ ComPtr<IMFMediaBuffer> buffer;+ if (FAILED(sample.ConvertToContiguousBuffer(&buffer)))+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to read a Media Foundation output sample"sv);+ BYTE* data = nullptr;+ DWORD length = 0;+ if (FAILED(buffer->Lock(&data, nullptr, &length)))+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to lock a Media Foundation output buffer"sv);+ ScopeGuard unlock_buffer = [&] { buffer->Unlock(); };++ auto const& sample_specification = transform.output_sample_specification;+ auto sample_size = transform.outputs_float ? sizeof(float) : sizeof(i16);+ auto frame_count = length / (sample_size * sample_specification.channel_count());+ auto sample_count = frame_count * sample_specification.channel_count();++ Optional<AK::Duration> previous_output_end;+ if (m_output_timeline_start.has_value())+ previous_output_end = *m_output_timeline_start + AK::Duration::from_time_units(m_frames_output_on_timeline, 1, m_output_sample_specification.sample_rate());+ auto output_start = previous_output_end;+ LONGLONG sample_time = 0;+ if (SUCCEEDED(sample.GetSampleTime(&sample_time)))+ output_start = duration_from_sample_time(sample_time);+ if (!output_start.has_value())+ return DecoderError::with_description(DecoderErrorCategory::Corrupted, "Media Foundation decoder output a sample with no time"sv);++ // The MFT output's time can be slightly off our input time in both directions, so stamp our output with the latest+ // time before the MFT output's midpoint. Anything before that time is dropped, since the output is monotonic.+ auto output_midpoint = *output_start + AK::Duration::from_time_units(static_cast<i64>(frame_count), 1, sample_specification.sample_rate() * 2);+ Optional<AK::Duration> packet_start;+ while (!transform.pending_coded_frame_timestamps.is_empty() && transform.pending_coded_frame_timestamps.first() <= output_midpoint)+ packet_start = transform.pending_coded_frame_timestamps.take_first();++ if (packet_start.has_value()) {+ m_output_timeline_start = packet_start.release_value();+ m_frames_output_on_timeline = 0;+ } else if (!previous_output_end.has_value()) {+ return DecoderError::with_description(DecoderErrorCategory::Corrupted, "Media Foundation decoder produced a sample that matches no packet"sv);+ } else if (m_output_sample_specification.sample_rate() != sample_specification.sample_rate()) {+ m_output_timeline_start = previous_output_end;+ m_frames_output_on_timeline = 0;+ }++ m_output_samples.clear_with_capacity();+ DECODER_TRY_ALLOC(m_output_samples.try_resize(sample_count));+ if (transform.outputs_float) {+ memcpy(m_output_samples.data(), data, sample_count * sizeof(float));+ } else {+ for (size_t index = 0; index < sample_count; index++) {+ i16 value;+ memcpy(&value, data + (index * sizeof(i16)), sizeof(value));+ m_output_samples[index] = static_cast<float>(value) / 32768.0f;+ }+ }++ m_output_sample_specification = sample_specification;+ m_output_frames_written = 0;+ return {};+}++void WindowsMediaFoundationAudioDecoder::write_output_into_block(AudioBlock& block)+{+ auto const& sample_specification = m_output_sample_specification;+ auto channel_count = sample_specification.channel_count();+ auto sample_rate = sample_specification.sample_rate();+ auto timestamp = *m_output_timeline_start + AK::Duration::from_time_units(m_frames_output_on_timeline, 1, sample_rate);++ auto available_frame_count = (m_output_samples.size() / channel_count) - m_output_frames_written;+ auto frame_count = min(available_frame_count, AudioBlock::max_frame_count(channel_count));+ frame_count = m_discard_intervals.frames_until_next_boundary(timestamp, sample_rate, frame_count);+ block.initialize(sample_specification, timestamp, frame_count);++ for (u8 channel = 0; channel < channel_count; channel++) {+ auto channel_data = block.channel_data(channel);+ for (size_t frame = 0; frame < frame_count; frame++)+ channel_data[frame] = m_output_samples[((m_output_frames_written + frame) * channel_count) + channel];+ }+ m_output_frames_written += frame_count;+ m_frames_output_on_timeline += static_cast<i64>(frame_count);+}++DecoderErrorOr<void> WindowsMediaFoundationAudioDecoder::write_next_block(AudioBlock& block)+{+ while (m_transform != nullptr) {+ auto has_unwritten_output = m_output_sample_specification.is_valid() && m_output_frames_written < m_output_samples.size() / m_output_sample_specification.channel_count();+ if (has_unwritten_output) {+ write_output_into_block(block);+ if (m_discard_intervals.should_discard(block))+ continue;+ return {};+ }++ auto& transform = *m_transform;+ auto output = TRY(process_output(*transform.transform.Get(), transform.output_stream_info));+ if (output.has<ComPtr<IMFSample>>()) {+ TRY(copy_output_sample(transform, *output.get<ComPtr<IMFSample>>().Get()));+ continue;+ }+ if (output.has<OutputTypeNeeded>()) {+ TRY(negotiate_output_format(transform));+ continue;+ }++ if (transform.pending_input) {+ TRY(submit_input(transform, move(transform.pending_input)));+ drain_unless_input_is_pending(transform);+ continue;+ }+ // A transform that was asked to drain has now output everything it withheld.+ if (transform.drain_requested && m_replacement_transform != nullptr) {+ switch_to_replacement_transform();+ continue;+ }+ break;+ }++ if (m_end_of_stream_signaled)+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "Media Foundation decoder has been drained"sv);+ return DecoderError::with_description(DecoderErrorCategory::NeedsMoreInput, "Media Foundation decoder needs more input"sv);+}++void WindowsMediaFoundationAudioDecoder::flush()+{+ if (m_replacement_transform != nullptr)+ switch_to_replacement_transform();+ if (m_transform != nullptr) {+ m_transform->transform->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0);+ m_transform->pending_input = nullptr;+ m_transform->drain_requested = false;+ m_transform->next_input_is_discontinuous = true;+ m_transform->pending_coded_frame_timestamps.clear();+ }++ m_end_of_stream_signaled = false;+ m_output_samples.clear_with_capacity();+ m_output_frames_written = 0;+ m_output_timeline_start.clear();+ m_frames_output_on_timeline = 0;+ m_discard_intervals.clear();+}++}diff --git a/Libraries/LibMedia/WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.h b/Libraries/LibMedia/WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.hnew file mode 100644index 00000000000..005cc8cc2f6--- /dev/null+++ b/Libraries/LibMedia/WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.h@@ -0,0 +1,75 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/FixedArray.h>+#include <AK/NonnullOwnPtr.h>+#include <AK/OwnPtr.h>+#include <AK/Time.h>+#include <AK/Vector.h>+#include <LibAudio/SampleSpecification.h>+#include <LibMedia/AudioDiscardIntervals.h>+#include <LibMedia/Export.h>+#include <LibMediaCodecs/AudioDecoder.h>+#include <LibMediaCodecs/CodecID.h>+#include <LibMediaCodecs/CodecParameters.h>+#include <LibMediaCodecs/DecoderCapabilities.h>++struct IMFSample;++namespace Media::WindowsMediaFoundation {++// Decodes the audio codecs we cannot ship decoders for through the ones Windows provides as Media Foundation+// transforms.+class MEDIA_API WindowsMediaFoundationAudioDecoder final : public AudioDecoder {+public:+ AK_ALLOC_WITH_KMALLOC;++ static Optional<DecoderCapabilities> capabilities(ParsedCodec const&);+ static DecoderErrorOr<NonnullOwnPtr<WindowsMediaFoundationAudioDecoder>> try_create(CodecID, Audio::SampleSpecification const&, ReadonlyBytes codec_initialization_data);++ virtual ~WindowsMediaFoundationAudioDecoder() override;++ virtual DecoderErrorOr<void> receive_coded_data(CodedFrame const&) override;+ virtual void signal_end_of_stream() override;+ virtual DecoderErrorOr<void> write_next_block(AudioBlock&) override;++ virtual void flush() override;++ // Holds everything that names a Media Foundation type, so that the Windows headers stay out of this one.+ struct Transform;++private:+ WindowsMediaFoundationAudioDecoder(CodecID, Audio::SampleSpecification const&, FixedArray<u8>&& codec_configuration);++ DecoderErrorOr<void> ensure_transform_for_frame(CodedFrame const&);+ DecoderErrorOr<void> copy_output_sample(Transform&, IMFSample&);+ void write_output_into_block(AudioBlock&);+ void switch_to_replacement_transform();++ CodecID const m_codec_id;+ Audio::SampleSpecification const m_container_sample_specification;+ FixedArray<u8> m_codec_configuration;++ OwnPtr<Transform> m_transform;+ // Takes over once the transform it replaces has drained what it withheld.+ OwnPtr<Transform> m_replacement_transform;+ bool m_end_of_stream_signaled { false };++ // Each output sample is timed from the packet it was decoded from, and its frames are counted from there.+ Optional<AK::Duration> m_output_timeline_start;+ i64 m_frames_output_on_timeline { 0 };++ // The interleaved samples of the output being written out.+ Vector<float> m_output_samples;+ Audio::SampleSpecification m_output_sample_specification;+ size_t m_output_frames_written { 0 };++ AudioDiscardIntervals m_discard_intervals;+};++}diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txtindex 443e8a6da55..3d947830afd 100644--- a/Tests/LibMedia/CMakeLists.txt+++ b/Tests/LibMedia/CMakeLists.txt@@ -54,6 +54,7 @@ if (APPLE)endif()if (WIN32)list(APPEND TEST_SOURCES+ TestWindowsMediaFoundationAudioDecode.cppTestWindowsMediaFoundationDecode.cpp)endif()diff --git a/Tests/LibMedia/TestWindowsMediaFoundationAudioDecode.cpp b/Tests/LibMedia/TestWindowsMediaFoundationAudioDecode.cppnew file mode 100644index 00000000000..9b666aaa67f--- /dev/null+++ b/Tests/LibMedia/TestWindowsMediaFoundationAudioDecode.cpp@@ -0,0 +1,298 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Vector.h>+#include <LibCore/File.h>+#include <LibMedia/Demuxer.h>+#include <LibMedia/DemuxerRegistry.h>+#include <LibMedia/IncrementallyPopulatedStream.h>+#include <LibMedia/Track.h>+#include <LibMedia/WindowsMediaFoundation/WindowsMediaFoundationAudioDecoder.h>+#include <LibMediaCodecs/AudioBlock.h>+#include <LibMediaCodecs/CodedFrame.h>+#include <LibTest/TestCase.h>++namespace {++// Matroska stores timestamps in milliseconds, so output timed from them can land up to one away from exact.+constexpr auto TIMESTAMP_TOLERANCE = AK::Duration::from_milliseconds(1);++struct CodedStream {+ Media::Track track;+ Vector<Media::CodedFrame> samples;+};++struct DecodedBlock {+ Audio::SampleSpecification sample_specification;+ AK::Duration start;+ AK::Duration end;+ size_t frame_count { 0 };+};++CodedStream read_coded_stream(StringView path)+{+ 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::Audio));+ VERIFY(track.has_value());+ MUST(demuxer->create_context_for_track(*track));++ Vector<Media::CodedFrame> samples;+ while (true) {+ auto sample = demuxer->get_next_sample_for_track(*track);+ if (sample.is_error()) {+ VERIFY(sample.error().category() == Media::DecoderErrorCategory::EndOfStream);+ break;+ }+ samples.append(sample.release_value());+ }+ return { track.release_value(), move(samples) };+}++NonnullOwnPtr<Media::WindowsMediaFoundation::WindowsMediaFoundationAudioDecoder> create_decoder(Media::Track const& track)+{+ return MUST(Media::WindowsMediaFoundation::WindowsMediaFoundationAudioDecoder::try_create(Media::CodecID::AAC, track.audio_data().sample_specification, {}));+}++// Returns the error category that stopped the decoder.+Media::DecoderErrorCategory write_available_blocks(Media::AudioDecoder& decoder, Vector<DecodedBlock>& blocks, Vector<Vector<float>>* channel_samples = nullptr)+{+ Media::AudioBlock block;+ while (true) {+ auto result = decoder.write_next_block(block);+ if (result.is_error())+ return result.error().category();++ blocks.append({ block.sample_specification(), block.media_time_start(), block.media_time_end(), block.frame_count() });+ if (channel_samples == nullptr)+ continue;+ channel_samples->resize(block.channel_count());+ for (u8 channel = 0; channel < block.channel_count(); channel++)+ channel_samples->at(channel).append(block.channel_data(channel).data(), block.frame_count());+ }+}++Vector<DecodedBlock> decode_entire_stream(Media::AudioDecoder& decoder, CodedStream const& stream, Vector<Vector<float>>* channel_samples = nullptr)+{+ Vector<DecodedBlock> blocks;+ for (auto const& sample : stream.samples) {+ MUST(decoder.receive_coded_data(sample));+ EXPECT_EQ(write_available_blocks(decoder, blocks, channel_samples), Media::DecoderErrorCategory::NeedsMoreInput);+ }+ decoder.signal_end_of_stream();+ EXPECT_EQ(write_available_blocks(decoder, blocks, channel_samples), Media::DecoderErrorCategory::EndOfStream);+ return blocks;+}++bool is_within_tolerance(AK::Duration actual, AK::Duration expected)+{+ return actual >= expected - TIMESTAMP_TOLERANCE && actual <= expected + TIMESTAMP_TOLERANCE;+}++void expect_contiguous_output(Vector<DecodedBlock> const& blocks, AK::Duration start)+{+ EXPECT(!blocks.is_empty());+ auto expected_start = start;+ for (auto const& block : blocks) {+ EXPECT(is_within_tolerance(block.start, expected_start));+ expected_start = block.end;+ }+}++// Each channel of the surround source is a tone of a different frequency.+Optional<u32> source_frequency_for_channel(Audio::Channel channel)+{+ switch (channel) {+ case Audio::Channel::FrontLeft:+ return 400;+ case Audio::Channel::FrontRight:+ return 800;+ case Audio::Channel::FrontCenter:+ return 200;+ case Audio::Channel::LowFrequency:+ return 100;+ case Audio::Channel::BackLeft:+ return 3200;+ case Audio::Channel::BackRight:+ return 6400;+ default:+ return {};+ }+}++size_t total_frame_count(Vector<DecodedBlock> const& blocks)+{+ size_t frame_count = 0;+ for (auto const& block : blocks)+ frame_count += block.frame_count;+ return frame_count;+}++}++TEST_CASE(decodes_aac_lc)+{+ auto stream = read_coded_stream("./aac_lc_in_matroska.mka"sv);+ auto decoder = create_decoder(stream.track);++ auto blocks = decode_entire_stream(*decoder, stream);++ for (auto const& block : blocks)+ EXPECT_EQ(block.sample_specification, Audio::SampleSpecification(48'000, Audio::ChannelMap::stereo()));+ expect_contiguous_output(blocks, stream.samples.first().presentation_timestamp());+ EXPECT_EQ(total_frame_count(blocks), stream.samples.size() * 1024);+}++TEST_CASE(discarded_output_is_dropped)+{+ auto stream = read_coded_stream("./aac_lc_in_matroska.mka"sv);+ auto baseline_decoder = create_decoder(stream.track);+ auto baseline_blocks = decode_entire_stream(*baseline_decoder, stream);++ // Trim the stream as appending it with an append window would: the presented span of the first and last frames+ // shrinks, and the output outside of it is discarded.+ auto sample_rate = baseline_blocks.first().sample_specification.sample_rate();+ constexpr i64 leading_frame_count = 100;+ constexpr i64 trailing_frame_count = 300;+ auto leading_discard = AK::Duration::from_time_units(leading_frame_count, 1, sample_rate);+ auto trailing_discard = AK::Duration::from_time_units(trailing_frame_count, 1, sample_rate);+ auto& first_sample = stream.samples.first();+ first_sample.set_leading_discard(leading_discard);+ first_sample.set_presentation_timestamp(first_sample.presentation_timestamp() + leading_discard);+ first_sample.set_duration(first_sample.duration() - leading_discard);+ auto& last_sample = stream.samples.last();+ last_sample.set_trailing_discard(trailing_discard);+ last_sample.set_duration(last_sample.duration() - trailing_discard);++ auto decoder = create_decoder(stream.track);+ auto blocks = decode_entire_stream(*decoder, stream);++ expect_contiguous_output(blocks, baseline_blocks.first().start + leading_discard);+ auto expected_frame_count = static_cast<i64>(total_frame_count(baseline_blocks)) - leading_frame_count - trailing_frame_count;+ auto frame_count_difference = static_cast<i64>(total_frame_count(blocks)) - expected_frame_count;+ // Millisecond timestamps can put a discard boundary up to a frame away on either end.+ EXPECT(frame_count_difference >= -2 && frame_count_difference <= 2);+}++TEST_CASE(he_aac_output_stays_contiguous_across_the_frames_that_sbr_delays)+{+ auto stream = read_coded_stream("./he_aac_in_matroska.mka"sv);+ auto decoder = create_decoder(stream.track);++ auto blocks = decode_entire_stream(*decoder, stream);++ // SBR doubles the core coder's sample rate and frame count.+ for (auto const& block : blocks)+ EXPECT_EQ(block.sample_specification, Audio::SampleSpecification(48'000, Audio::ChannelMap::stereo()));+ expect_contiguous_output(blocks, stream.samples.first().presentation_timestamp());+ EXPECT_EQ(total_frame_count(blocks), stream.samples.size() * 2048);+}++TEST_CASE(flushing_restarts_output_at_the_next_packet)+{+ auto stream = read_coded_stream("./he_aac_in_matroska.mka"sv);+ auto decoder = create_decoder(stream.track);++ Vector<DecodedBlock> blocks;+ for (size_t index = 0; index < 4; index++) {+ TRY_OR_FAIL(decoder->receive_coded_data(stream.samples[index]));+ EXPECT_EQ(write_available_blocks(*decoder, blocks), Media::DecoderErrorCategory::NeedsMoreInput);+ }++ decoder->flush();+ blocks.clear();++ // Windows' decoder outputs each packet once it has the next one.+ auto const& resumed_sample = stream.samples[8];+ for (size_t index = 8; index < 10; index++) {+ TRY_OR_FAIL(decoder->receive_coded_data(stream.samples[index]));+ EXPECT_EQ(write_available_blocks(*decoder, blocks), Media::DecoderErrorCategory::NeedsMoreInput);+ }+ expect_contiguous_output(blocks, resumed_sample.presentation_timestamp());+}++TEST_CASE(a_new_configuration_takes_over_once_the_previous_output_is_written)+{+ static constexpr size_t he_aac_sample_count = 4;++ auto he_aac_stream = read_coded_stream("./he_aac_in_matroska.mka"sv);+ auto lc_stream = read_coded_stream("./aac_lc_in_matroska.mka"sv);+ auto decoder = create_decoder(he_aac_stream.track);++ Vector<DecodedBlock> blocks;+ for (size_t index = 0; index < he_aac_sample_count; index++) {+ TRY_OR_FAIL(decoder->receive_coded_data(he_aac_stream.samples[index]));+ EXPECT_EQ(write_available_blocks(*decoder, blocks), Media::DecoderErrorCategory::NeedsMoreInput);+ }++ auto lc_sample = lc_stream.samples.first();+ EXPECT(lc_sample.new_codec_configuration().has_value());+ lc_sample.set_presentation_timestamp(he_aac_stream.samples[he_aac_sample_count].presentation_timestamp());+ TRY_OR_FAIL(decoder->receive_coded_data(lc_sample));+ EXPECT_EQ(write_available_blocks(*decoder, blocks), Media::DecoderErrorCategory::NeedsMoreInput);+ // Windows' decoder outputs a packet once it has the next one, or once it is drained.+ decoder->signal_end_of_stream();+ EXPECT_EQ(write_available_blocks(*decoder, blocks), Media::DecoderErrorCategory::EndOfStream);++ // The frames that the HE-AAC decoder delayed are written before the LC decoder's first packet.+ expect_contiguous_output(blocks, he_aac_stream.samples.first().presentation_timestamp());+ EXPECT_EQ(total_frame_count(blocks), (he_aac_sample_count * 2048) + 1024);+}++TEST_CASE(surround_channels_are_written_in_the_order_of_their_channel_map)+{+ auto stream = read_coded_stream("./aac_5_1_in_matroska.mka"sv);+ auto decoder = create_decoder(stream.track);++ Vector<Vector<float>> channel_samples;+ auto blocks = decode_entire_stream(*decoder, stream, &channel_samples);+ auto const& channel_map = blocks.first().sample_specification.channel_map();+ EXPECT_EQ(channel_map.channel_count(), 6);++ // Skip the encoder's priming, and count zero crossings for a quarter second.+ static constexpr size_t first_frame = 4096;+ static constexpr size_t frame_count = 12'000;+ for (u8 channel = 0; channel < channel_map.channel_count(); channel++) {+ auto expected_frequency = source_frequency_for_channel(channel_map.channel_at(channel));+ EXPECT(expected_frequency.has_value());++ auto samples = channel_samples[channel].span().slice(first_frame, frame_count);+ size_t zero_crossing_count = 0;+ for (size_t index = 1; index < samples.size(); index++) {+ if ((samples[index - 1] < 0) != (samples[index] < 0))+ zero_crossing_count++;+ }+ auto measured_frequency = static_cast<double>(zero_crossing_count) / 2 * 48'000 / frame_count;+ EXPECT_APPROXIMATE_WITH_ERROR(measured_frequency, static_cast<double>(expected_frequency.value()), expected_frequency.value() * 0.05);+ }+}++TEST_CASE(aac_without_a_configuration_is_left_to_another_decoder)+{+ auto decoder = MUST(Media::WindowsMediaFoundation::WindowsMediaFoundationAudioDecoder::try_create(Media::CodecID::AAC, Audio::SampleSpecification { 48'000, Audio::ChannelMap::stereo() }, {}));++ Media::CodedFrame frame { Media::CodecID::AAC, AK::Duration::zero(), AK::Duration::zero(), AK::Duration::zero(), Media::FrameFlags::Keyframe, MUST(FixedArray<u8>::create({ 0x21, 0x10, 0x04 })), FixedArray<u8> {} };+ auto result = decoder->receive_coded_data(frame);+ EXPECT(result.is_error());+ EXPECT_EQ(result.error().category(), Media::DecoderErrorCategory::NotImplemented);+}++TEST_CASE(input_after_the_end_of_stream_is_rejected_until_flushed)+{+ auto stream = read_coded_stream("./aac_lc_in_matroska.mka"sv);+ auto decoder = create_decoder(stream.track);++ MUST(decoder->receive_coded_data(stream.samples[0]));+ decoder->signal_end_of_stream();++ auto result = decoder->receive_coded_data(stream.samples[1]);+ EXPECT(result.is_error());+ EXPECT_EQ(result.error().category(), Media::DecoderErrorCategory::EndOfStream);++ decoder->flush();+ MUST(decoder->receive_coded_data(stream.samples[0]));+}