Title: [270662] trunk/Source/WebCore
Revision
270662
Author
[email protected]
Date
2020-12-10 16:45:46 -0800 (Thu, 10 Dec 2020)

Log Message

[MSE] Refactor SourceBufferParserWebM in preparation for supporting audio
https://bugs.webkit.org/show_bug.cgi?id=219755
<rdar://problem/72192625>

Reviewed by Jer Noble.

Refactor the WebM parser in preparation for supporting audio: move VP9-specific code
into VP9UtilitiesCocoa, convert TrackData from a struct to a class and made derived
classes for audio and video, add stub function to create format descriptions for
Vorbis and Opus audio.

* SourcesCocoa.txt:
* WebCore.xcodeproj/project.pbxproj:

* platform/cocoa/MediaUtilities.cpp:
(WebCore::createAudioFormatDescription): Add optional parameters for magic cookie.
* platform/cocoa/MediaUtilities.h:

* platform/graphics/cocoa/SourceBufferParserWebM.cpp:
(WebCore::SourceBufferParserWebM::isContentTypeSupported):
(WebCore::SourceBufferParserWebM::create):
(WebCore::SourceBufferParserWebM::resetParserState):
(WebCore::SourceBufferParserWebM::trackDataForTrackNumber):
(WebCore::SourceBufferParserWebM::OnTrackEntry):
(WebCore::SourceBufferParserWebM::OnFrame):
(WebCore::SourceBufferParserWebM::provideMediaData):
(WebCore::SourceBufferParserWebM::VideoTrackData::consumeFrameData):
(WebCore::SourceBufferParserWebM::VideoTrackData::createSampleBuffer):
(WebCore::SourceBufferParserWebM::AudioTrackData::consumeFrameData):
(WebCore::SourceBufferParserWebM::AudioTrackData::createSampleBuffer):
(WebCore::SourceBufferParserWebM::flushPendingAudioBuffers):
(WebCore::SourceBufferParserWebM::setMinimumAudioSampleDuration):
(WebCore::convertToColorPrimaries): Deleted.
(WebCore::convertToCMColorPrimaries): Deleted.
(WebCore::convertToTransferCharacteristics): Deleted.
(WebCore::convertToCMTransferFunction): Deleted.
(WebCore::convertToMatrixCoefficients): Deleted.
(WebCore::convertToCMYCbCRMatrix): Deleted.
(WebCore::convertSubsamplingXYToChromaSubsampling): Deleted.
(WebCore::createFormatDescriptionFromVP9HeaderParser): Deleted.
* platform/graphics/cocoa/SourceBufferParserWebM.h:
(isType):

* platform/graphics/cocoa/VP9UtilitiesCocoa.h:
* platform/graphics/cocoa/VP9UtilitiesCocoa.mm:
(WebCore::convertToColorPrimaries):
(WebCore::convertToCMColorPrimaries):
(WebCore::convertToTransferCharacteristics):
(WebCore::convertToCMTransferFunction):
(WebCore::convertToMatrixCoefficients):
(WebCore::convertToCMYCbCRMatrix):
(WebCore::convertSubsamplingXYToChromaSubsampling):
(WebCore::createFormatDescriptionFromVP9HeaderParser):

* platform/graphics/cocoa/WebMAudioUtilitiesCocoa.h: Added.
* platform/graphics/cocoa/WebMAudioUtilitiesCocoa.mm: Added.
(WebCore::registerDecoderFactory):
(WebCore::createAudioFormatDescriptionForFormat):
(WebCore::cookieFromOpusCodecPrivate):
(WebCore::isOpusDecoderAvailable):
(WebCore::createOpusAudioFormatDescription):
(WebCore::cookieFromVorbisCodecPrivate):
(WebCore::isVorbisDecoderAvailable):
(WebCore::createVorbisAudioFormatDescription):

Modified Paths

Added Paths

Diff

Modified: trunk/Source/WebCore/ChangeLog (270661 => 270662)


--- trunk/Source/WebCore/ChangeLog	2020-12-11 00:17:23 UTC (rev 270661)
+++ trunk/Source/WebCore/ChangeLog	2020-12-11 00:45:46 UTC (rev 270662)
@@ -1,3 +1,70 @@
+2020-12-10  Eric Carlson  <[email protected]>
+
+        [MSE] Refactor SourceBufferParserWebM in preparation for supporting audio
+        https://bugs.webkit.org/show_bug.cgi?id=219755
+        <rdar://problem/72192625>
+
+        Reviewed by Jer Noble.
+
+        Refactor the WebM parser in preparation for supporting audio: move VP9-specific code
+        into VP9UtilitiesCocoa, convert TrackData from a struct to a class and made derived
+        classes for audio and video, add stub function to create format descriptions for 
+        Vorbis and Opus audio.
+
+        * SourcesCocoa.txt:
+        * WebCore.xcodeproj/project.pbxproj:
+
+        * platform/cocoa/MediaUtilities.cpp:
+        (WebCore::createAudioFormatDescription): Add optional parameters for magic cookie.
+        * platform/cocoa/MediaUtilities.h:
+
+        * platform/graphics/cocoa/SourceBufferParserWebM.cpp:
+        (WebCore::SourceBufferParserWebM::isContentTypeSupported):
+        (WebCore::SourceBufferParserWebM::create):
+        (WebCore::SourceBufferParserWebM::resetParserState):
+        (WebCore::SourceBufferParserWebM::trackDataForTrackNumber):
+        (WebCore::SourceBufferParserWebM::OnTrackEntry):
+        (WebCore::SourceBufferParserWebM::OnFrame):
+        (WebCore::SourceBufferParserWebM::provideMediaData):
+        (WebCore::SourceBufferParserWebM::VideoTrackData::consumeFrameData):
+        (WebCore::SourceBufferParserWebM::VideoTrackData::createSampleBuffer):
+        (WebCore::SourceBufferParserWebM::AudioTrackData::consumeFrameData):
+        (WebCore::SourceBufferParserWebM::AudioTrackData::createSampleBuffer):
+        (WebCore::SourceBufferParserWebM::flushPendingAudioBuffers):
+        (WebCore::SourceBufferParserWebM::setMinimumAudioSampleDuration):
+        (WebCore::convertToColorPrimaries): Deleted.
+        (WebCore::convertToCMColorPrimaries): Deleted.
+        (WebCore::convertToTransferCharacteristics): Deleted.
+        (WebCore::convertToCMTransferFunction): Deleted.
+        (WebCore::convertToMatrixCoefficients): Deleted.
+        (WebCore::convertToCMYCbCRMatrix): Deleted.
+        (WebCore::convertSubsamplingXYToChromaSubsampling): Deleted.
+        (WebCore::createFormatDescriptionFromVP9HeaderParser): Deleted.
+        * platform/graphics/cocoa/SourceBufferParserWebM.h:
+        (isType):
+
+        * platform/graphics/cocoa/VP9UtilitiesCocoa.h:
+        * platform/graphics/cocoa/VP9UtilitiesCocoa.mm:
+        (WebCore::convertToColorPrimaries):
+        (WebCore::convertToCMColorPrimaries):
+        (WebCore::convertToTransferCharacteristics):
+        (WebCore::convertToCMTransferFunction):
+        (WebCore::convertToMatrixCoefficients):
+        (WebCore::convertToCMYCbCRMatrix):
+        (WebCore::convertSubsamplingXYToChromaSubsampling):
+        (WebCore::createFormatDescriptionFromVP9HeaderParser):
+
+        * platform/graphics/cocoa/WebMAudioUtilitiesCocoa.h: Added.
+        * platform/graphics/cocoa/WebMAudioUtilitiesCocoa.mm: Added.
+        (WebCore::registerDecoderFactory):
+        (WebCore::createAudioFormatDescriptionForFormat):
+        (WebCore::cookieFromOpusCodecPrivate):
+        (WebCore::isOpusDecoderAvailable):
+        (WebCore::createOpusAudioFormatDescription):
+        (WebCore::cookieFromVorbisCodecPrivate):
+        (WebCore::isVorbisDecoderAvailable):
+        (WebCore::createVorbisAudioFormatDescription):
+
 2020-12-10  Wenson Hsieh  <[email protected]>
 
         [GPU Process] Crash when loading drinktrade.com

Modified: trunk/Source/WebCore/SourcesCocoa.txt (270661 => 270662)


--- trunk/Source/WebCore/SourcesCocoa.txt	2020-12-11 00:17:23 UTC (rev 270661)
+++ trunk/Source/WebCore/SourcesCocoa.txt	2020-12-11 00:45:46 UTC (rev 270662)
@@ -376,6 +376,7 @@
 platform/graphics/cocoa/WebCoreDecompressionSession.mm
 platform/graphics/cocoa/WebGLLayer.mm
 platform/graphics/cocoa/WebGPULayer.mm
+platform/graphics/cocoa/WebMUtilitiesCocoa.mm @no-unify
 platform/graphics/cocoa/VideoTrackPrivateWebM.cpp
 platform/graphics/coretext/FontCascadeCoreText.cpp
 platform/graphics/coretext/FontCoreText.cpp

Modified: trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj (270661 => 270662)


--- trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2020-12-11 00:17:23 UTC (rev 270661)
+++ trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2020-12-11 00:45:46 UTC (rev 270662)
@@ -218,6 +218,8 @@
 		07EE76EC1BE96DB000F89133 /* MockRealtimeVideoSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 07EE76EA1BE96DB000F89133 /* MockRealtimeVideoSource.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		07EE76EF1BEA619800F89133 /* MockRealtimeVideoSourceMac.h in Headers */ = {isa = PBXBuildFile; fileRef = 07EE76ED1BEA619800F89133 /* MockRealtimeVideoSourceMac.h */; };
 		07F4E93320B3587F002E3803 /* AVAssetMIMETypeCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 07C8AD121D073D630087C5CE /* AVAssetMIMETypeCache.h */; settings = {ATTRIBUTES = (Private, ); }; };
+		07F5CFF52582A51D00662EF5 /* WebMAudioUtilitiesCocoa.h in Headers */ = {isa = PBXBuildFile; fileRef = 07F5CFF42582A4F800662EF5 /* WebMAudioUtilitiesCocoa.h */; };
+		07F5CFF62582A52900662EF5 /* WebMAudioUtilitiesCocoa.mm in Sources */ = {isa = PBXBuildFile; fileRef = 07F5CFF22582A4F800662EF5 /* WebMAudioUtilitiesCocoa.mm */; };
 		07F876841AD580F900905849 /* MediaPlaybackTargetContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 07F876831AD4A94500905849 /* MediaPlaybackTargetContext.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		07F944161864D046005D31CB /* PlatformMediaSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = CDAE8C081746B95700532D78 /* PlatformMediaSessionManager.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		07FE99DD18807A7D00256648 /* MediaElementSession.h in Headers */ = {isa = PBXBuildFile; fileRef = 07FE99DB18807A7D00256648 /* MediaElementSession.h */; settings = {ATTRIBUTES = (Private, ); }; };
@@ -5875,6 +5877,8 @@
 		07EE76EA1BE96DB000F89133 /* MockRealtimeVideoSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MockRealtimeVideoSource.h; sourceTree = "<group>"; };
 		07EE76ED1BEA619800F89133 /* MockRealtimeVideoSourceMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MockRealtimeVideoSourceMac.h; sourceTree = "<group>"; };
 		07EE76EE1BEA619800F89133 /* MockRealtimeVideoSourceMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MockRealtimeVideoSourceMac.mm; sourceTree = "<group>"; };
+		07F5CFF22582A4F800662EF5 /* WebMAudioUtilitiesCocoa.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = WebMAudioUtilitiesCocoa.mm; sourceTree = "<group>"; };
+		07F5CFF42582A4F800662EF5 /* WebMAudioUtilitiesCocoa.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WebMAudioUtilitiesCocoa.h; sourceTree = "<group>"; };
 		07F876831AD4A94500905849 /* MediaPlaybackTargetContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MediaPlaybackTargetContext.h; sourceTree = "<group>"; };
 		07FE99DA18807A7D00256648 /* MediaElementSession.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MediaElementSession.cpp; sourceTree = "<group>"; };
 		07FE99DB18807A7D00256648 /* MediaElementSession.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MediaElementSession.h; sourceTree = "<group>"; };
@@ -26867,6 +26871,8 @@
 				49FFBF3E11C93EE3006A7118 /* WebGLLayer.mm */,
 				318436DB21B9DAA000ED383E /* WebGPULayer.h */,
 				318436DD21B9DAA000ED383E /* WebGPULayer.mm */,
+				07F5CFF42582A4F800662EF5 /* WebMAudioUtilitiesCocoa.h */,
+				07F5CFF22582A4F800662EF5 /* WebMAudioUtilitiesCocoa.mm */,
 			);
 			path = cocoa;
 			sourceTree = "<group>";
@@ -35256,6 +35262,7 @@
 				494BD7950F55C8EE00747828 /* WebKitPoint.h in Headers */,
 				31C0FF250E4CEB6E007D6FE5 /* WebKitTransitionEvent.h in Headers */,
 				0FCF332F0F2B9A25004B6795 /* WebLayer.h in Headers */,
+				07F5CFF52582A51D00662EF5 /* WebMAudioUtilitiesCocoa.h in Headers */,
 				0709D78F1AE55554004E42F8 /* WebMediaSessionManager.h in Headers */,
 				0709D7951AE55A29004E42F8 /* WebMediaSessionManagerClient.h in Headers */,
 				0709D7931AE5557E004E42F8 /* WebMediaSessionManagerMac.h in Headers */,
@@ -36610,6 +36617,7 @@
 				2D06214D1DA63A8B00A7FB26 /* WebKitMediaKeys.cpp in Sources */,
 				2D06214F1DA63A9100A7FB26 /* WebKitMediaKeySession.cpp in Sources */,
 				7C48A6D0191C9D6500026674 /* WebKitNamespace.cpp in Sources */,
+				07F5CFF62582A52900662EF5 /* WebMAudioUtilitiesCocoa.mm in Sources */,
 				0709D7921AE5557E004E42F8 /* WebMediaSessionManagerMac.cpp in Sources */,
 				1CAF34820A6C405200ABE06E /* WebScriptObject.mm in Sources */,
 				CECDC93C21F2972900976BD1 /* WebVideoFullscreenControllerAVKit.mm in Sources */,

Modified: trunk/Source/WebCore/platform/cocoa/MediaUtilities.cpp (270661 => 270662)


--- trunk/Source/WebCore/platform/cocoa/MediaUtilities.cpp	2020-12-11 00:17:23 UTC (rev 270661)
+++ trunk/Source/WebCore/platform/cocoa/MediaUtilities.cpp	2020-12-11 00:45:46 UTC (rev 270662)
@@ -35,11 +35,11 @@
 
 using namespace PAL;
 
-RetainPtr<CMFormatDescriptionRef> createAudioFormatDescription(const AudioStreamDescription& description)
+RetainPtr<CMFormatDescriptionRef> createAudioFormatDescription(const AudioStreamDescription& description, size_t magicCookieSize, const void* magicCookie)
 {
     auto basicDescription = WTF::get<const AudioStreamBasicDescription*>(description.platformDescription().description);
     CMFormatDescriptionRef format = nullptr;
-    auto error = CMAudioFormatDescriptionCreate(kCFAllocatorDefault, basicDescription, 0, nullptr, 0, nullptr, nullptr, &format);
+    auto error = CMAudioFormatDescriptionCreate(kCFAllocatorDefault, basicDescription, 0, nullptr, magicCookieSize, magicCookie, nullptr, &format);
     if (error) {
         LOG_ERROR("createAudioFormatDescription failed with %d", error);
         return nullptr;

Modified: trunk/Source/WebCore/platform/cocoa/MediaUtilities.h (270661 => 270662)


--- trunk/Source/WebCore/platform/cocoa/MediaUtilities.h	2020-12-11 00:17:23 UTC (rev 270661)
+++ trunk/Source/WebCore/platform/cocoa/MediaUtilities.h	2020-12-11 00:45:46 UTC (rev 270662)
@@ -36,7 +36,7 @@
 class AudioStreamDescription;
 class PlatformAudioData;
 
-RetainPtr<CMFormatDescriptionRef> createAudioFormatDescription(const AudioStreamDescription&);
+RetainPtr<CMFormatDescriptionRef> createAudioFormatDescription(const AudioStreamDescription&, size_t magicCookieSize = 0, const void* magicCookie = nullptr);
 RetainPtr<CMSampleBufferRef> createAudioSampleBuffer(const PlatformAudioData&, const AudioStreamDescription&, CMTime, size_t sampleCount);
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.cpp (270661 => 270662)


--- trunk/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.cpp	2020-12-11 00:17:23 UTC (rev 270661)
+++ trunk/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.cpp	2020-12-11 00:45:46 UTC (rev 270662)
@@ -39,11 +39,13 @@
 #include "SharedBuffer.h"
 #include "VP9UtilitiesCocoa.h"
 #include "VideoTrackPrivateWebM.h"
+#include "WebMAudioUtilitiesCocoa.h"
 #include <_javascript_Core/DataView.h>
 #include <webm/webm_parser.h>
 #include <wtf/Algorithms.h>
 #include <wtf/LoggerHelper.h>
 #include <wtf/NeverDestroyed.h>
+#include <wtf/StdLibExtras.h>
 #include <wtf/StdList.h>
 #include <wtf/cf/TypeCastsCF.h>
 #include <wtf/darwin/WeakLinking.h>
@@ -236,7 +238,6 @@
 
 } // namespace WTF
 
-
 namespace WebCore {
 
 using namespace PAL;
@@ -456,6 +457,7 @@
 
 MediaPlayerEnums::SupportsType SourceBufferParserWebM::isContentTypeSupported(const ContentType& type)
 {
+#if ENABLE(VP9) || ENABLE(VORBIS) || ENABLE(OPUS)
     if (!isWebmParserAvailable())
         return MediaPlayerEnums::SupportsType::IsNotSupported;
 
@@ -467,10 +469,14 @@
     if (!codecsParameter)
         return MediaPlayerEnums::SupportsType::MayBeSupported;
 
-#if ENABLE(VP9)
     auto splitResults = StringView(codecsParameter).split(',');
     for (auto split : splitResults) {
+#if ENABLE(VP9)
         if (split.startsWith("vp09")) {
+
+            if (!isVP9DecoderAvailable())
+                return MediaPlayerEnums::SupportsType::IsNotSupported;
+
             auto codecParameters = parseVPCodecParameters(split);
             if (!codecParameters)
                 return MediaPlayerEnums::SupportsType::IsNotSupported;
@@ -480,16 +486,45 @@
 
             continue;
         }
-        // FIXME: Add Opus Support
-        // FIXME: Add Vorbis Support
+#endif // ENABLE(VP9)
+
+#if ENABLE(VORBIS)
+        if (split == "vorbis") {
+            if (!isVorbisDecoderAvailable())
+                return MediaPlayerEnums::SupportsType::IsNotSupported;
+
+            continue;
+        }
+#endif // ENABLE(VORBIS)
+
+#if ENABLE(OPUS)
+        if (split == "opus") {
+            if (!isOpusDecoderAvailable())
+                return MediaPlayerEnums::SupportsType::IsNotSupported;
+
+            continue;
+        }
+#endif // ENABLE(OPUS)
+
         return MediaPlayerEnums::SupportsType::IsNotSupported;
     }
+
     return MediaPlayerEnums::SupportsType::IsSupported;
+
 #else
+    UNUSED_PARAM(type);
+
     return MediaPlayerEnums::SupportsType::IsNotSupported;
-#endif
+#endif // ENABLE(VP9) || ENABLE(VORBIS) || ENABLE(OPUS)
 }
 
+RefPtr<SourceBufferParserWebM> SourceBufferParserWebM::create(const ContentType& type)
+{
+    if (isContentTypeSupported(type) != MediaPlayerEnums::SupportsType::IsNotSupported)
+        return adoptRef(new SourceBufferParserWebM());
+    return nullptr;
+}
+
 SourceBufferParserWebM::SourceBufferParserWebM()
     : m_reader(WTF::makeUniqueRef<StreamingVectorReader>())
     , m_initializationSegmentIsHandledSemaphore(Box<BinarySemaphore>::create())
@@ -571,7 +606,9 @@
 void SourceBufferParserWebM::resetParserState()
 {
     INFO_LOG_IF_POSSIBLE(LOGIDENTIFIER);
-    m_parser->DidSeek();
+    flushPendingAudioBuffers();
+    if (m_parser)
+        m_parser->DidSeek();
     m_state = State::None;
     m_tracks.clear();
     m_initializationSegment = nullptr;
@@ -604,7 +641,7 @@
 auto SourceBufferParserWebM::trackDataForTrackNumber(uint64_t trackNumber) -> TrackData*
 {
     for (auto& track : m_tracks) {
-        if (track.track.track_number.is_present() && track.track.track_number.value() == trackNumber)
+        if (track->track().track_number.is_present() && track->track().track_number.value() == trackNumber)
             return &track;
     }
     return nullptr;
@@ -748,7 +785,7 @@
 Status SourceBufferParserWebM::OnTrackEntry(const ElementMetadata& metadata, const TrackEntry& trackEntry)
 {
     UNUSED_PARAM(metadata);
-    if (!trackEntry.track_type.is_present())
+    if (!trackEntry.track_type.is_present() || !trackEntry.codec_id.is_present())
         return Status(Status::kOkCompleted);
 
     auto trackType = trackEntry.track_type.value();
@@ -756,8 +793,30 @@
         m_initializationSegment->videoTracks.append({ MediaDescriptionWebM::create(TrackEntry(trackEntry)), VideoTrackPrivateWebM::create(TrackEntry(trackEntry)) });
     else if (trackType == TrackType::kAudio)
         m_initializationSegment->audioTracks.append({ MediaDescriptionWebM::create(TrackEntry(trackEntry)), AudioTrackPrivateWebM::create(TrackEntry(trackEntry)) });
-    m_tracks.append({ TrackEntry(trackEntry), { }, nullptr, nullptr, 0 });
 
+    StringView codecString { trackEntry.codec_id.value().data(), (unsigned)trackEntry.codec_id.value().length() };
+#if ENABLE(VP9)
+    if (codecString == "V_VP9" && isVP9DecoderAvailable()) {
+        m_tracks.append(VideoTrackData::create(CodecType::VP9, trackEntry, *this));
+        return Status(Status::kOkCompleted);
+    }
+#endif
+
+#if ENABLE(VORBIS)
+    if (codecString == "A_VORBIS" && isVorbisDecoderAvailable()) {
+        m_tracks.append(AudioTrackData::create(CodecType::Vorbis, trackEntry, *this, m_minimumAudioSampleDuration));
+        return Status(Status::kOkCompleted);
+    }
+#endif
+
+#if ENABLE(OPUS)
+    if (codecString == "A_OPUS" && isOpusDecoderAvailable()) {
+        m_tracks.append(AudioTrackData::create(CodecType::Opus, trackEntry, *this, m_minimumAudioSampleDuration));
+        return Status(Status::kOkCompleted);
+    }
+#endif
+
+    m_tracks.append(TrackData::create(CodecType::Unsupported, trackEntry, *this));
     return Status(Status::kOkCompleted);
 }
 
@@ -827,406 +886,291 @@
     return Status(Status::kOkCompleted);
 }
 
-#if ENABLE(VP9)
 
-static uint8_t convertToColorPrimaries(const Primaries& coefficients)
+webm::Status SourceBufferParserWebM::OnFrame(const FrameMetadata& metadata, Reader* reader, uint64_t* bytesRemaining)
 {
-    switch (coefficients) {
-    case Primaries::kBt709:
-        return VPConfigurationColorPrimaries::BT_709_6;
-    case Primaries::kUnspecified:
-        return VPConfigurationColorPrimaries::Unspecified;
-    case Primaries::kBt470M:
-        return VPConfigurationColorPrimaries::BT_470_6_M;
-    case Primaries::kBt470Bg:
-        return VPConfigurationColorPrimaries::BT_470_7_BG;
-    case Primaries::kSmpte170M:
-        return VPConfigurationColorPrimaries::BT_601_7;
-    case Primaries::kSmpte240M:
-        return VPConfigurationColorPrimaries::SMPTE_ST_240;
-    case Primaries::kFilm:
-        return VPConfigurationColorPrimaries::Film;
-    case Primaries::kBt2020:
-        return VPConfigurationColorPrimaries::BT_2020_Nonconstant_Luminance;
-    case Primaries::kSmpteSt4281:
-        return VPConfigurationColorPrimaries::SMPTE_ST_428_1;
-    case Primaries::kSmpteRp431:
-        return VPConfigurationColorPrimaries::SMPTE_RP_431_2;
-    case Primaries::kSmpteEg432:
-        return VPConfigurationColorPrimaries::SMPTE_EG_432_1;
-    case Primaries::kJedecP22Phosphors:
-        return VPConfigurationColorPrimaries::EBU_Tech_3213_E;
-    }
-}
+    ASSERT(reader);
+    if (!reader)
+        return Status(Status::kNotEnoughMemory);
 
-static CFStringRef convertToCMColorPrimaries(uint8_t primaries)
-{
-    switch (primaries) {
-    case VPConfigurationColorPrimaries::BT_709_6:
-        return kCVImageBufferColorPrimaries_ITU_R_709_2;
-    case VPConfigurationColorPrimaries::EBU_Tech_3213_E:
-        return kCVImageBufferColorPrimaries_EBU_3213;
-    case VPConfigurationColorPrimaries::BT_601_7:
-    case VPConfigurationColorPrimaries::SMPTE_ST_240:
-        return kCVImageBufferColorPrimaries_SMPTE_C;
-    case VPConfigurationColorPrimaries::SMPTE_RP_431_2:
-        return kCMFormatDescriptionColorPrimaries_DCI_P3;
-    case VPConfigurationColorPrimaries::SMPTE_EG_432_1:
-        return kCMFormatDescriptionColorPrimaries_P3_D65;
-    case VPConfigurationColorPrimaries::BT_2020_Nonconstant_Luminance:
-        return kCMFormatDescriptionColorPrimaries_ITU_R_2020;
-    }
+    if (!m_currentBlock)
+        return Status(Status::kInvalidElementId);
 
-    return nullptr;
-}
+    auto* block = WTF::switchOn(*m_currentBlock, [](Block& block) {
+        return &block;
+    }, [](SimpleBlock& block) -> Block* {
+        return &block;
+    });
+    if (!block)
+        return Status(Status::kInvalidElementId);
 
-static uint8_t convertToTransferCharacteristics(const TransferCharacteristics& characteristics)
-{
-    switch (characteristics) {
-    case TransferCharacteristics::kBt709:
-        return VPConfigurationTransferCharacteristics::BT_709_6;
-    case TransferCharacteristics::kUnspecified:
-        return VPConfigurationTransferCharacteristics::Unspecified;
-    case TransferCharacteristics::kGamma22curve:
-        return VPConfigurationTransferCharacteristics::BT_470_6_M;
-    case TransferCharacteristics::kGamma28curve:
-        return VPConfigurationTransferCharacteristics::BT_470_7_BG;
-    case TransferCharacteristics::kSmpte170M:
-        return VPConfigurationTransferCharacteristics::BT_601_7;
-    case TransferCharacteristics::kSmpte240M:
-        return VPConfigurationTransferCharacteristics::SMPTE_ST_240;
-    case TransferCharacteristics::kLinear:
-        return VPConfigurationTransferCharacteristics::Linear;
-    case TransferCharacteristics::kLog:
-        return VPConfigurationTransferCharacteristics::Logrithmic;
-    case TransferCharacteristics::kLogSqrt:
-        return VPConfigurationTransferCharacteristics::Logrithmic_Sqrt;
-    case TransferCharacteristics::kIec6196624:
-        return VPConfigurationTransferCharacteristics::IEC_61966_2_4;
-    case TransferCharacteristics::kBt1361ExtendedColourGamut:
-        return VPConfigurationTransferCharacteristics::BT_1361_0;
-    case TransferCharacteristics::kIec6196621:
-        return VPConfigurationTransferCharacteristics::IEC_61966_2_1;
-    case TransferCharacteristics::k10BitBt2020:
-        return VPConfigurationTransferCharacteristics::BT_2020_10bit;
-    case TransferCharacteristics::k12BitBt2020:
-        return VPConfigurationTransferCharacteristics::BT_2020_12bit;
-    case TransferCharacteristics::kSmpteSt2084:
-        return VPConfigurationTransferCharacteristics::SMPTE_ST_2084;
-    case TransferCharacteristics::kSmpteSt4281:
-        return VPConfigurationTransferCharacteristics::SMPTE_ST_428_1;
-    case TransferCharacteristics::kAribStdB67Hlg:
-        return VPConfigurationTransferCharacteristics::BT_2100_HLG;
+    auto trackNumber = block->track_number;
+    auto* trackData = trackDataForTrackNumber(trackNumber);
+    if (!trackData) {
+        ERROR_LOG_IF_POSSIBLE(LOGIDENTIFIER, "Ignoring unknown track number ", trackNumber);
+        return Status(Status::kInvalidElementId);
     }
-}
 
-static CFStringRef convertToCMTransferFunction(uint8_t characteristics)
-{
-    switch (characteristics) {
-    case VPConfigurationTransferCharacteristics::BT_709_6:
-        return kCVImageBufferTransferFunction_ITU_R_709_2;
-    case VPConfigurationTransferCharacteristics::SMPTE_ST_240:
-        return kCVImageBufferTransferFunction_SMPTE_240M_1995;
-    case VPConfigurationTransferCharacteristics::SMPTE_ST_2084:
-        return kCMFormatDescriptionTransferFunction_SMPTE_ST_2084_PQ;
-    case VPConfigurationTransferCharacteristics::BT_2020_10bit:
-    case VPConfigurationTransferCharacteristics::BT_2020_12bit:
-        return kCMFormatDescriptionTransferFunction_ITU_R_2020;
-    case VPConfigurationTransferCharacteristics::SMPTE_ST_428_1:
-        return kCMFormatDescriptionTransferFunction_SMPTE_ST_428_1;
-    case VPConfigurationTransferCharacteristics::BT_2100_HLG:
-        return kCMFormatDescriptionTransferFunction_ITU_R_2100_HLG;
-    case VPConfigurationTransferCharacteristics::IEC_61966_2_1:
-        return PAL::canLoad_CoreMedia_kCMFormatDescriptionTransferFunction_sRGB() ? get_CoreMedia_kCMFormatDescriptionTransferFunction_sRGB() : nullptr;
-    case VPConfigurationTransferCharacteristics::Linear:
-        return kCMFormatDescriptionTransferFunction_Linear;
+    switch (trackData->codec()) {
+    case CodecType::VP9:
+    case CodecType::Vorbis:
+    case CodecType::Opus:
+        break;
+
+    case CodecType::Unsupported:
+        return Skip(reader, bytesRemaining);
     }
 
-    return nullptr;
+    return trackData->consumeFrameData(*reader, metadata, bytesRemaining, CMTimeMake(block->timecode + m_currentTimecode, m_timescale), block->num_frames);
 }
 
-static uint8_t convertToMatrixCoefficients(const MatrixCoefficients& coefficients)
+void SourceBufferParserWebM::provideMediaData(RetainPtr<CMSampleBufferRef> sampleBuffer, uint64_t trackID)
 {
-    switch (coefficients) {
-    case MatrixCoefficients::kRgb:
-        return VPConfigurationMatrixCoefficients::Identity;
-    case MatrixCoefficients::kBt709:
-        return VPConfigurationMatrixCoefficients::BT_709_6;
-    case MatrixCoefficients::kUnspecified:
-        return VPConfigurationMatrixCoefficients::Unspecified;
-    case MatrixCoefficients::kFcc:
-        return VPConfigurationMatrixCoefficients::FCC;
-    case MatrixCoefficients::kBt470Bg:
-        return VPConfigurationMatrixCoefficients::BT_470_7_BG;
-    case MatrixCoefficients::kSmpte170M:
-        return VPConfigurationMatrixCoefficients::BT_601_7;
-    case MatrixCoefficients::kSmpte240M:
-        return VPConfigurationMatrixCoefficients::SMPTE_ST_240;
-    case MatrixCoefficients::kYCgCo:
-        return VPConfigurationMatrixCoefficients::YCgCo;
-    case MatrixCoefficients::kBt2020NonconstantLuminance:
-        return VPConfigurationMatrixCoefficients::BT_2020_Nonconstant_Luminance;
-    case MatrixCoefficients::kBt2020ConstantLuminance:
-        return VPConfigurationMatrixCoefficients::BT_2020_Constant_Luminance;
-    }
-}
+    callOnMainThread([this, protectedThis = makeRef(*this), sampleBuffer = WTFMove(sampleBuffer), trackID] () mutable {
+        if (!m_didProvideMediaDataCallback)
+            return;
 
-static CFStringRef convertToCMYCbCRMatrix(uint8_t coefficients)
-{
-    switch (coefficients) {
-    case VPConfigurationMatrixCoefficients::BT_2020_Nonconstant_Luminance:
-        return kCMFormatDescriptionYCbCrMatrix_ITU_R_2020;
-    case VPConfigurationMatrixCoefficients::BT_470_7_BG:
-    case VPConfigurationMatrixCoefficients::BT_601_7:
-        return kCVImageBufferYCbCrMatrix_ITU_R_601_4;
-    case VPConfigurationMatrixCoefficients::BT_709_6:
-        return kCVImageBufferYCbCrMatrix_ITU_R_709_2;
-    case VPConfigurationMatrixCoefficients::SMPTE_ST_240:
-        return kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
-    }
-
-    return nullptr;
+        auto mediaSample = MediaSampleAVFObjC::create(sampleBuffer.get(), trackID);
+        m_didProvideMediaDataCallback(WTFMove(mediaSample), trackID, emptyString());
+    });
 }
 
-static uint8_t convertSubsamplingXYToChromaSubsampling(uint64_t x, uint64_t y)
-{
-    if (x & y)
-        return VPConfigurationChromaSubsampling::Subsampling_420_Colocated;
-    if (x & !y)
-        return VPConfigurationChromaSubsampling::Subsampling_422;
-    if (!x & !y)
-        return VPConfigurationChromaSubsampling::Subsampling_444;
-    // This indicates 4:4:0 subsampling, which is not expressable in the 'vpcC' box. Default to 4:2:0.
-    return VPConfigurationChromaSubsampling::Subsampling_420_Colocated;
-}
+#define PARSER_LOG_ERROR_IF_POSSIBLE(...) if (parser().loggerPtr()) parser().loggerPtr()->error(logChannel(), WTF::Logger::LogSiteIdentifier(logClassName(), __func__, parser().logIdentifier()), __VA_ARGS__)
 
-static RetainPtr<CMFormatDescriptionRef> createFormatDescriptionFromVP9HeaderParser(const vp9_parser::Vp9HeaderParser& parser, const webm::Element<Colour>& color)
+webm::Status SourceBufferParserWebM::VideoTrackData::consumeFrameData(webm::Reader& reader, const FrameMetadata& metadata, uint64_t* bytesRemaining, const CMTime& presentationTime, int sampleCount)
 {
-    // Ref: "VP Codec ISO Media File Format Binding, v1.0, 2017-03-31"
-    // <https://www.webmproject.org/vp9/mp4/>
-    //
-    // class VPCodecConfigurationBox extends FullBox('vpcC', version = 1, 0)
-    // {
-    //     VPCodecConfigurationRecord() vpcConfig;
-    // }
-    //
-    // aligned (8) class VPCodecConfigurationRecord {
-    //     unsigned int (8)     profile;
-    //     unsigned int (8)     level;
-    //     unsigned int (4)     bitDepth;
-    //     unsigned int (3)     chromaSubsampling;
-    //     unsigned int (1)     videoFullRangeFlag;
-    //     unsigned int (8)     colourPrimaries;
-    //     unsigned int (8)     transferCharacteristics;
-    //     unsigned int (8)     matrixCoefficients;
-    //     unsigned int (16)    codecIntializationDataSize;
-    //     unsigned int (8)[]   codecIntializationData;
-    // }
-    //
-    // codecIntializationDataSize​For VP8 and VP9 this field must be 0.
-    // codecIntializationData​binary codec initialization data. Not used for VP8 and VP9.
-    //
-    // FIXME: Convert existing struct to an ISOBox and replace the writing code below
-    // with a subclass of ISOFullBox.
+#if ENABLE(VP9)
+    CMBlockBufferRef rawBlockBuffer = nullptr;
 
-    VPCodecConfigurationRecord record;
+    if (!m_currentBlockBuffer) {
+        auto err = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault, nullptr, metadata.size, kCFAllocatorDefault, nullptr, 0, metadata.size, 0, &rawBlockBuffer);
+        if (err) {
+            PARSER_LOG_ERROR_IF_POSSIBLE("CMBlockBufferCreateWithMemoryBlock failed with error", err);
+            return Skip(&reader, bytesRemaining);
+        }
 
-    record.profile = ""
-    // CoreMedia does nat care about the VP9 codec level; hard-code to Level 1.0 here:
-    record.level = 10;
-    record.bitDepth = parser.bit_depth();
-    record.videoFullRangeFlag = parser.color_range() ? VPConfigurationRange::FullRange : VPConfigurationRange::VideoRange;
-    record.chromaSubsampling = convertSubsamplingXYToChromaSubsampling(parser.subsampling_x(), parser.subsampling_y());
-    record.colorPrimaries = VPConfigurationColorPrimaries::Unspecified;
-    record.transferCharacteristics = VPConfigurationTransferCharacteristics::Unspecified;
-    record.matrixCoefficients = VPConfigurationMatrixCoefficients::Unspecified;
+        m_currentBlockBuffer = adoptCF(rawBlockBuffer);
+        m_currentBlockBufferPosition = 0;
 
-    // Container color values can override per-sample ones:
-    if (color.is_present()) {
-        auto& colorValue = color.value();
-        if (colorValue.chroma_subsampling_x.is_present() && colorValue.chroma_subsampling_y.is_present())
-            record.chromaSubsampling = convertSubsamplingXYToChromaSubsampling(colorValue.chroma_subsampling_x.value(), colorValue.chroma_subsampling_y.value());
-        if (colorValue.range.is_present() && colorValue.range.value() != Range::kUnspecified)
-            record.videoFullRangeFlag = colorValue.range.value() == Range::kFull ? VPConfigurationRange::FullRange : VPConfigurationRange::VideoRange;
-        if (colorValue.bits_per_channel.is_present())
-            record.bitDepth = colorValue.bits_per_channel.value();
-        if (colorValue.transfer_characteristics.is_present())
-            record.transferCharacteristics = convertToTransferCharacteristics(colorValue.transfer_characteristics.value());
-        if (colorValue.matrix_coefficients.is_present())
-            record.matrixCoefficients = convertToMatrixCoefficients(colorValue.matrix_coefficients.value());
-        if (colorValue.primaries.is_present())
-            record.colorPrimaries = convertToColorPrimaries(colorValue.primaries.value());
+        err = CMBlockBufferAssureBlockMemory(m_currentBlockBuffer.get());
+        if (err) {
+            PARSER_LOG_ERROR_IF_POSSIBLE("CMAudioSampleBufferCreateWithPacketDescriptions failed with error", err);
+            return Skip(&reader, bytesRemaining);
+        }
     }
 
-    constexpr size_t VPCodecConfigurationContentsSize = 12;
+    size_t bytesToRead = metadata.size - m_currentBlockBufferPosition;
+    while (bytesToRead) {
+        size_t segmentSizeAtPosition = 0;
+        uint8_t* blockBufferData = nullptr;
+        auto err = CMBlockBufferGetDataPointer(m_currentBlockBuffer.get(), m_currentBlockBufferPosition, &segmentSizeAtPosition, nullptr, (char**)&blockBufferData);
+        if (err) {
+            PARSER_LOG_ERROR_IF_POSSIBLE("CMBlockBufferGetDataPointer failed with error", err);
+            return Skip(&reader, bytesRemaining);
+        }
 
-    uint32_t versionAndFlags = 1 << 24;
-    uint8_t bitDepthChromaAndRange = (0xF & record.bitDepth) << 4 | (0x7 & record.chromaSubsampling) << 1 | (0x1 & record.videoFullRangeFlag);
-    uint16_t codecIntializationDataSize = 0;
+        size_t bytesToReadFromThisSegment = std::min(bytesToRead, segmentSizeAtPosition);
+        uint64_t bytesRead;
 
-    auto view = JSC::DataView::create(ArrayBuffer::create(VPCodecConfigurationContentsSize, 1), 0, VPCodecConfigurationContentsSize);
-    view->set(0, versionAndFlags, false);
-    view->set(4, record.profile, false);
-    view->set(5, record.level, false);
-    view->set(6, bitDepthChromaAndRange, false);
-    view->set(7, record.colorPrimaries, false);
-    view->set(8, record.transferCharacteristics, false);
-    view->set(9, record.matrixCoefficients, false);
-    view->set(10, codecIntializationDataSize, false);
+        auto status = reader.Read(bytesToReadFromThisSegment, (uint8_t*)blockBufferData, &bytesRead);
+        bytesToRead -= bytesRead;
+        *bytesRemaining -= bytesRead;
+        m_currentBlockBufferPosition += bytesRead;
 
-    auto data = "" (const UInt8 *)view->data(), view->byteLength()));
+        // FIXME: We can't yet handle parsing a Frame that doesn't have all its memory available.
+        if (status.code == webm::Status::kOkPartial || status.code == webm::Status::kWouldBlock)
+            return status;
+    }
 
-    CFTypeRef configurationKeys[] = { CFSTR("vpcC") };
-    CFTypeRef configurationValues[] = { data.get() };
-    auto configurationDict = adoptCF(CFDictionaryCreate(kCFAllocatorDefault, configurationKeys, configurationValues, WTF_ARRAY_LENGTH(configurationKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
+    createSampleBuffer(presentationTime, sampleCount);
+#else
+    UNUSED_PARAM(metadata);
+    UNUSED_PARAM(presentationTime);
+    UNUSED_PARAM(sampleCount);
+#endif
 
-    Vector<CFTypeRef> extensionsKeys { kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms };
-    Vector<CFTypeRef> extensionsValues = { configurationDict.get() };
+    return Skip(&reader, bytesRemaining);
+}
 
-    if (record.videoFullRangeFlag == VPConfigurationRange::FullRange) {
-        extensionsKeys.append(kCMFormatDescriptionExtension_FullRangeVideo);
-        extensionsValues.append(kCFBooleanTrue);
+void SourceBufferParserWebM::VideoTrackData::createSampleBuffer(const CMTime& presentationTime, int sampleCount)
+{
+#if ENABLE(VP9)
+    uint8_t* blockBufferData = nullptr;
+    size_t segmentSizeAtPosition = 0;
+    auto err = CMBlockBufferGetDataPointer(m_currentBlockBuffer.get(), 0, &segmentSizeAtPosition, nullptr, (char**)&blockBufferData);
+    if (err) {
+        PARSER_LOG_ERROR_IF_POSSIBLE("CMBlockBufferGetDataPointer failed with error", err);
+        return;
     }
 
-    if (auto cmColorPrimaries = convertToCMColorPrimaries(record.colorPrimaries)) {
-        extensionsKeys.append(kCVImageBufferColorPrimariesKey);
-        extensionsValues.append(cmColorPrimaries);
+    if (!m_headerParser.ParseUncompressedHeader(blockBufferData, segmentSizeAtPosition)) {
+        PARSER_LOG_ERROR_IF_POSSIBLE("ParseUncompressedHeader failed");
+        return;
     }
 
-    if (auto cmTransferFunction = convertToCMTransferFunction(record.transferCharacteristics)) {
-        extensionsKeys.append(kCVImageBufferTransferFunctionKey);
-        extensionsValues.append(cmTransferFunction);
+    // Only update the format description when the header indicates that the sample is
+    // a key-frame, otherwise color information will not be parsed.
+    auto track = this->track();
+    if (m_headerParser.key()) {
+        auto formatDescription = createFormatDescriptionFromVP9HeaderParser(m_headerParser, track.video.value().colour);
+        if (!formatDescription) {
+            PARSER_LOG_ERROR_IF_POSSIBLE("failed to create format description from VP9 header");
+            return;
+        }
+        setFormatDescription(WTFMove(formatDescription));
     }
 
-    if (auto cmMatrix = convertToCMYCbCRMatrix(record.matrixCoefficients)) {
-        extensionsKeys.append(kCVImageBufferYCbCrMatrixKey);
-        extensionsValues.append(cmMatrix);
-    }
+    // FIXME: A block might contain more than one frame, but only this frame has been read into `currentBlockBuffer`.
+    // Below we create sample buffers for each frame, each with the block's timecode and `num_frames` value.
+    // Shouldn't we create just one sample buffer once all the block's frames have been read into `currentBlockBuffer`?
 
-    auto extensions = adoptCF(CFDictionaryCreate(kCFAllocatorDefault, extensionsKeys.data(), extensionsValues.data(), extensionsKeys.size(), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
+    uint64_t duration = 0;
+    if (track.default_duration.is_present())
+        duration = track.default_duration.value() * presentationTime.timescale / 1000000000;
 
-    CMVideoFormatDescriptionRef formatDescription = nullptr;
-    if (noErr != CMVideoFormatDescriptionCreate(kCFAllocatorDefault, kCMVideoCodecType_VP9, parser.width(), parser.height(), extensions.get(), &formatDescription))
-        return nullptr;
-    return adoptCF(formatDescription);
-}
-#endif
+    CMSampleBufferRef rawSampleBuffer = nullptr;
+    size_t frameSize = CMBlockBufferGetDataLength(m_currentBlockBuffer.get());
+    CMSampleTimingInfo timing = { CMTimeMake(duration, presentationTime.timescale), presentationTime, presentationTime };
+    err = CMSampleBufferCreateReady(kCFAllocatorDefault, m_currentBlockBuffer.get(), formatDescription().get(), sampleCount, 1, &timing, 1, &frameSize, &rawSampleBuffer);
+    if (err) {
+        PARSER_LOG_ERROR_IF_POSSIBLE("CMSampleBufferCreateReady failed with error", err);
+        return;
+    }
+    auto sampleBuffer = adoptCF(rawSampleBuffer);
 
-webm::Status SourceBufferParserWebM::OnFrame(const FrameMetadata& metadata, Reader* reader, uint64_t* bytesRemaining)
-{
-    UNUSED_PARAM(metadata);
-    UNUSED_PARAM(bytesRemaining);
+    m_currentBlockBuffer = nullptr;
+    m_currentBlockBufferPosition = 0;
 
-    ASSERT(reader);
-    if (!reader)
-        return Status(Status::kNotEnoughMemory);
+    if (!m_headerParser.key()) {
+        auto attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer.get(), true);
+        ASSERT(attachmentsArray);
+        if (!attachmentsArray) {
+            PARSER_LOG_ERROR_IF_POSSIBLE("CMSampleBufferGetSampleAttachmentsArray returned NULL");
+            return;
+        }
 
-    if (!m_currentBlock)
-        return Status(Status::kInvalidElementId);
+        for (CFIndex i = 0, count = CFArrayGetCount(attachmentsArray); i < count; ++i) {
+            CFMutableDictionaryRef attachments = checked_cf_cast<CFMutableDictionaryRef>(CFArrayGetValueAtIndex(attachmentsArray, i));
+            CFDictionarySetValue(attachments, kCMSampleAttachmentKey_NotSync, kCFBooleanTrue);
+        }
+    }
 
-    auto* block = WTF::switchOn(*m_currentBlock, [](Block& block) {
-        return &block;
-    }, [](SimpleBlock& block) -> Block* {
-        return &block;
-    });
-    if (!block)
-        return Status(Status::kInvalidElementId);
+    auto trackID = track.track_uid.value();
+    parser().provideMediaData(sampleBuffer.leakRef(), trackID);
+#else
+    UNUSED_PARAM(presentationTime);
+    UNUSED_PARAM(sampleCount);
+#endif // ENABLE(VP9)
+}
 
-    auto trackNumber = block->track_number;
+webm::Status SourceBufferParserWebM::AudioTrackData::consumeFrameData(webm::Reader& reader, const FrameMetadata& metadata, uint64_t* bytesRemaining, const CMTime& presentationTime, int sampleCount)
+{
+    ASSERT_UNUSED(sampleCount, sampleCount == 1);
 
-    auto* trackData = trackDataForTrackNumber(trackNumber);
-    if (!trackData)
-        return Status(Status::kInvalidElementId);
-    auto& track = trackData->track;
+    if (!formatDescription()) {
+        if (!track().codec_private.is_present()) {
+            PARSER_LOG_ERROR_IF_POSSIBLE("Audio track missing magic cookie");
+            return Skip(&reader, bytesRemaining);
+        }
 
-    uint64_t duration = 0;
-    if (track.default_duration.is_present())
-        duration = track.default_duration.value() * m_timescale / 1000000000;
+        RetainPtr<CMFormatDescriptionRef> formatDescription;
+        auto& privateData = track().codec_private.value();
+        if (codec() == CodecType::Vorbis)
+            formatDescription = createVorbisAudioFormatDescription(privateData.size(), privateData.data());
+        else if (codec() == CodecType::Opus)
+            formatDescription = createOpusAudioFormatDescription(privateData.size(), privateData.data());
 
-#if ENABLE(VP9)
-    if (track.codec_id.is_present() && track.codec_id.value() == "V_VP9") {
-        if (!trackData->currentBlockBuffer) {
-            CMBlockBufferRef rawBlockBuffer = nullptr;
-            if (noErr != CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault, nullptr, metadata.size, kCFAllocatorDefault, nullptr, 0, metadata.size, 0, &rawBlockBuffer))
-                return Skip(reader, bytesRemaining);
-            trackData->currentBlockBuffer = adoptCF(rawBlockBuffer);
-            trackData->currentBlockBufferPosition = 0;
+        if (!formatDescription) {
+            PARSER_LOG_ERROR_IF_POSSIBLE("Failed to create format description from audio track header");
+            return Skip(&reader, bytesRemaining);
+        }
 
-            if (noErr != CMBlockBufferAssureBlockMemory(trackData->currentBlockBuffer.get()))
-                return Skip(reader, bytesRemaining);
+        auto streamDescription = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription.get());
+        if (!streamDescription) {
+            PARSER_LOG_ERROR_IF_POSSIBLE("CMAudioFormatDescriptionGetStreamBasicDescription failed");
+            return Skip(&reader, bytesRemaining);
         }
+        m_packetDuration = CMTimeMake(streamDescription->mFramesPerPacket, streamDescription->mSampleRate);
 
-        size_t numToRead = metadata.size - trackData->currentBlockBufferPosition;
-        size_t segmentSizeAtPosition = 0;
-        uint8_t* blockBufferData = nullptr;
+        setFormatDescription(WTFMove(formatDescription));
+    }
 
-        while (numToRead) {
-            if (noErr != CMBlockBufferGetDataPointer(trackData->currentBlockBuffer.get(), trackData->currentBlockBufferPosition, &segmentSizeAtPosition, nullptr, (char**)&blockBufferData))
-                return Skip(reader, bytesRemaining);
+    if (m_packetData.isEmpty()) {
+        m_packetData.resize(metadata.size);
+        m_packetBytesRead = 0;
+        m_byteOffset = metadata.position;
+        m_samplePresentationTime = presentationTime;
+    }
 
-            size_t numToReadFromThisSegment = std::min(numToRead, segmentSizeAtPosition);
-            uint64_t numActuallyWrittenToThisSegment;
+    size_t packetDataOffset = m_packetBytesRead;
+    size_t bytesToRead = metadata.size;
+    while (bytesToRead) {
+        uint64_t bytesRead;
+        auto status = reader.Read(bytesToRead, m_packetData.data() + m_packetBytesRead, &bytesRead);
+        bytesToRead -= bytesRead;
+        *bytesRemaining -= bytesRead;
+        m_packetBytesRead += bytesRead;
 
-            auto status = m_reader->Read(numToReadFromThisSegment, (uint8_t*)blockBufferData, &numActuallyWrittenToThisSegment);
-            numToRead -= numActuallyWrittenToThisSegment;
-            *bytesRemaining -= numActuallyWrittenToThisSegment;
-            trackData->currentBlockBufferPosition += numActuallyWrittenToThisSegment;
+        // FIXME: We can't yet handle parsing a Frame that doesn't have all its memory available.
+        if (status.code == webm::Status::kOkPartial || status.code == webm::Status::kWouldBlock)
+            return status;
+    }
 
-            // FIXME: We can't yet handle parsing a Frame that doesn't have all its memory available.
-            if (status.code == webm::Status::kOkPartial || status.code == webm::Status::kWouldBlock)
-                return status;
-        }
+    m_packetDescriptions.append({ static_cast<int64_t>(packetDataOffset), 0, static_cast<UInt32>(metadata.size) });
+    auto sampleDuration = CMTimeGetSeconds(CMTimeSubtract(presentationTime, m_samplePresentationTime)) + CMTimeGetSeconds(m_packetDuration);
+    if (sampleDuration >= m_minimumSampleDuration)
+        createSampleBuffer();
 
-        if (noErr != CMBlockBufferGetDataPointer(trackData->currentBlockBuffer.get(), 0, &segmentSizeAtPosition, nullptr, (char**)&blockBufferData))
-            return Skip(reader, bytesRemaining);
+    return Skip(&reader, bytesRemaining);
+}
 
-        auto& headerParser = trackData->headerParser;
-        if (!headerParser.ParseUncompressedHeader(blockBufferData, segmentSizeAtPosition))
-            return Skip(reader, bytesRemaining);
+void SourceBufferParserWebM::AudioTrackData::createSampleBuffer()
+{
+    if (m_packetDescriptions.isEmpty())
+        return;
 
-        // Only update the format description when the header indicates that the sample is
-        // a key-frame, otherwise color information will not be parsed.
-        if (headerParser.key())
-            trackData->formatDescription = createFormatDescriptionFromVP9HeaderParser(headerParser, track.video.value().colour);
-        if (!trackData->formatDescription)
-            return Skip(reader, bytesRemaining);
+    ASSERT(!m_packetData.isEmpty());
 
-        auto pts = CMTimeMake(block->timecode + m_currentTimecode, m_timescale);
-        CMSampleTimingInfo timing = { CMTimeMake(duration, m_timescale), pts, pts };
-        size_t size = metadata.size;
+    CMBlockBufferRef blockBuffer = nullptr;
+    auto err = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault, nullptr, m_packetData.sizeInBytes(), kCFAllocatorDefault, nullptr, 0, m_packetData.sizeInBytes(), kCMBlockBufferAssureMemoryNowFlag, &blockBuffer);
+    if (err) {
+        PARSER_LOG_ERROR_IF_POSSIBLE("CMBlockBufferCreateWithMemoryBlock failed with %d", err);
+        return;
+    }
+    auto buffer = adoptCF(blockBuffer);
 
-        auto sampleCount = block->num_frames;
-        CMSampleBufferRef rawSampleBuffer = nullptr;
-        if (noErr != CMSampleBufferCreateReady(kCFAllocatorDefault, trackData->currentBlockBuffer.get(), trackData->formatDescription.get(), sampleCount, 1, &timing, 1, &size, &rawSampleBuffer))
-            return Skip(reader, bytesRemaining);
-        auto sampleBuffer = adoptCF(rawSampleBuffer);
+    err = CMBlockBufferReplaceDataBytes(m_packetData.data(), buffer.get(), 0, m_packetData.sizeInBytes());
+    if (err) {
+        PARSER_LOG_ERROR_IF_POSSIBLE("CMBlockBufferReplaceDataBytes failed with %d", err);
+        return;
+    }
 
-        trackData->currentBlockBuffer = nullptr;
-        trackData->currentBlockBufferPosition = 0;
+    CMSampleBufferRef rawSampleBuffer = nullptr;
+    err = CMAudioSampleBufferCreateReadyWithPacketDescriptions(kCFAllocatorDefault, buffer.get(), formatDescription().get(), m_packetDescriptions.size(), m_samplePresentationTime, m_packetDescriptions.data(), &rawSampleBuffer);
+    if (err) {
+        PARSER_LOG_ERROR_IF_POSSIBLE("CMAudioSampleBufferCreateWithPacketDescriptions failed with %d", err);
+        return;
+    }
+    auto sampleBuffer = adoptCF(rawSampleBuffer);
 
-        if (!headerParser.key()) {
-            auto attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer.get(), true);
-            ASSERT(attachmentsArray);
-            if (!attachmentsArray)
-                return Skip(reader, bytesRemaining);
-            for (CFIndex i = 0, count = CFArrayGetCount(attachmentsArray); i < count; ++i) {
-                CFMutableDictionaryRef attachments = checked_cf_cast<CFMutableDictionaryRef>(CFArrayGetValueAtIndex(attachmentsArray, i));
-                CFDictionarySetValue(attachments, kCMSampleAttachmentKey_NotSync, kCFBooleanTrue);
-            }
-        }
+    m_packetData.clear();
+    m_packetDescriptions.clear();
 
-        auto trackID = track.track_uid.value();
+    auto trackID = track().track_uid.value();
+    parser().provideMediaData(sampleBuffer.leakRef(), trackID);
+}
 
-        callOnMainThread([this, protectedThis = makeRef(*this), sampleBuffer = WTFMove(sampleBuffer), trackID] () mutable {
-            if (!m_didProvideMediaDataCallback)
-                return;
-            auto mediaSample = MediaSampleAVFObjC::create(sampleBuffer.get(), trackID);
-            m_didProvideMediaDataCallback(WTFMove(mediaSample), trackID, emptyString());
-        });
+void SourceBufferParserWebM::flushPendingAudioBuffers()
+{
+    for (auto& track : m_tracks) {
+        if (track->trackType() == SourceBufferParserWebM::TrackData::Type::Audio)
+            downcast<AudioTrackData>(track.get()).createSampleBuffer();
     }
-#endif
+}
 
-    return Skip(reader, bytesRemaining);
+void SourceBufferParserWebM::setMinimumAudioSampleDuration(float duration)
+{
+    m_minimumAudioSampleDuration = duration;
 }
 
 }

Modified: trunk/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.h (270661 => 270662)


--- trunk/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.h	2020-12-11 00:17:23 UTC (rev 270661)
+++ trunk/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.h	2020-12-11 00:45:46 UTC (rev 270662)
@@ -28,6 +28,8 @@
 #if ENABLE(MEDIA_SOURCE)
 
 #include "SourceBufferParser.h"
+#include <CoreAudio/CoreAudioTypes.h>
+#include <CoreMedia/CMTime.h>
 #include <common/vp9_header_parser.h>
 #include <webm/callback.h>
 #include <webm/status.h>
@@ -41,7 +43,6 @@
 #include <wtf/text/WTFString.h>
 #include <wtf/threads/BinarySemaphore.h>
 
-typedef struct opaqueCMSampleBuffer *CMSampleBufferRef;
 typedef const struct opaqueCMFormatDescription* CMFormatDescriptionRef;
 typedef struct OpaqueCMBlockBuffer *CMBlockBufferRef;
 
@@ -51,10 +52,15 @@
 
 namespace WebCore {
 
+class MediaSampleAVFObjC;
+
 class WEBCORE_EXPORT SourceBufferParserWebM : public SourceBufferParser, private webm::Callback {
     WTF_MAKE_FAST_ALLOCATED;
 public:
+    class StreamingVectorReader;
+
     static MediaPlayerEnums::SupportsType isContentTypeSupported(const ContentType&);
+    static RefPtr<SourceBufferParserWebM> create(const ContentType&);
 
     SourceBufferParserWebM();
     ~SourceBufferParserWebM();
@@ -71,10 +77,13 @@
     void resetParserState() final;
     void invalidate() final;
 
-#if !RELEASE_LOG_DISABLED
+    void flushPendingAudioBuffers();
+    void setMinimumAudioSampleDuration(float);
+
     void setLogger(const WTF::Logger&, const void* identifier) final;
-#endif
 
+    void provideMediaData(RetainPtr<CMSampleBufferRef>, uint64_t);
+
     enum class ErrorCode : int32_t {
         SourceBufferParserWebMErrorCodeStart = 2000,
         InvalidDocType,
@@ -95,21 +104,122 @@
         ReadingCluster,
     };
 
-private:
-    struct TrackData {
-        webm::TrackEntry track;
-        vp9_parser::Vp9HeaderParser headerParser;
-        RetainPtr<CMFormatDescriptionRef> formatDescription;
-        RetainPtr<CMBlockBufferRef> currentBlockBuffer;
-        uint64_t currentBlockBufferPosition { 0 };
+    enum class CodecType : uint8_t {
+        Unsupported,
+        VP9,
+        Vorbis,
+        Opus,
     };
-    TrackData* trackDataForTrackNumber(uint64_t);
 
-#if !RELEASE_LOG_DISABLED
+    class TrackData {
+        WTF_MAKE_FAST_ALLOCATED;
+    public:
+        static auto create(CodecType codecType, const webm::TrackEntry& trackEntry, SourceBufferParserWebM& parser) -> UniqueRef<TrackData>
+        {
+            return makeUniqueRef<TrackData>(codecType, trackEntry, Type::Unknown, parser);
+        }
+
+        enum class Type {
+            Unknown,
+            Audio,
+            Video,
+        };
+
+        TrackData(CodecType codecType, const webm::TrackEntry& trackEntry, Type trackType, SourceBufferParserWebM& parser)
+            : m_codec { codecType }
+            , m_track { webm::TrackEntry { trackEntry } }
+            , m_trackType { trackType }
+            , m_parser { parser }
+        {
+        }
+        virtual ~TrackData() = default;
+
+        CodecType codec() const { return m_codec; }
+        webm::TrackEntry& track() { return m_track; }
+        Type trackType() const { return m_trackType; }
+
+        RetainPtr<CMFormatDescriptionRef> formatDescription() { return m_formatDescription; }
+        void setFormatDescription(RetainPtr<CMFormatDescriptionRef>&& description) { m_formatDescription = WTFMove(description); }
+
+        SourceBufferParserWebM& parser() const { return m_parser; }
+        
+        virtual webm::Status consumeFrameData(webm::Reader&, const webm::FrameMetadata&, uint64_t*, const CMTime&, int)
+        {
+            ASSERT_NOT_REACHED();
+            return webm::Status(webm::Status::kInvalidElementId);
+        }
+
+    private:
+        CodecType m_codec;
+        webm::TrackEntry m_track;
+        Type m_trackType;
+        RetainPtr<CMFormatDescriptionRef> m_formatDescription;
+        SourceBufferParserWebM& m_parser;
+    };
+
+    class VideoTrackData : public TrackData {
+    public:
+        static auto create(CodecType codecType, const webm::TrackEntry& trackEntry, SourceBufferParserWebM& parser) -> UniqueRef<VideoTrackData>
+        {
+            return makeUniqueRef<VideoTrackData>(codecType, trackEntry, parser);
+        }
+
+        VideoTrackData(CodecType codecType, const webm::TrackEntry& trackEntry, SourceBufferParserWebM& parser)
+            : TrackData(codecType, trackEntry, Type::Video, parser)
+        {
+        }
+
+        webm::Status consumeFrameData(webm::Reader&, const webm::FrameMetadata&, uint64_t*, const CMTime&, int) final;
+        
+    private:
+        void createSampleBuffer(const CMTime&, int);
+        const char* logClassName() const { return "VideoTrackData"; }
+
+#if ENABLE(VP9)
+        vp9_parser::Vp9HeaderParser m_headerParser;
+        RetainPtr<CMBlockBufferRef> m_currentBlockBuffer;
+        uint64_t m_currentBlockBufferPosition { 0 };
+#endif
+    };
+
+    class AudioTrackData : public TrackData {
+    public:
+        static auto create(CodecType codecType, const webm::TrackEntry& trackEntry, SourceBufferParserWebM& parser, float minimumSampleDuration) -> UniqueRef<AudioTrackData>
+        {
+            return makeUniqueRef<AudioTrackData>(codecType, trackEntry, parser, minimumSampleDuration);
+        }
+
+        AudioTrackData(CodecType codecType, const webm::TrackEntry& trackEntry, SourceBufferParserWebM& parser, float minimumSampleDuration)
+            : TrackData { codecType, trackEntry, Type::Audio, parser }
+            , m_minimumSampleDuration { minimumSampleDuration }
+        {
+        }
+
+        webm::Status consumeFrameData(webm::Reader&, const webm::FrameMetadata&, uint64_t*, const CMTime&, int) final;
+        void createSampleBuffer();
+
+    private:
+        const char* logClassName() const { return "AudioTrackData"; }
+
+        CMTime m_samplePresentationTime;
+        CMTime m_packetDuration;
+        Vector<uint8_t> m_packetData;
+        size_t m_packetBytesRead { 0 };
+        size_t m_byteOffset { 0 };
+        Vector<AudioStreamPacketDescription> m_packetDescriptions;
+
+        // FIXME: 0.5 - 1.0 seconds is a better duration per sample buffer, but use 2 seconds so at least the first
+        // sample buffer will play until we fix SampleCursor::createSampleBuffer to deal with `endCursor`.
+        float m_minimumSampleDuration { 2 };
+    };
+
     const WTF::Logger* loggerPtr() const { return m_logger.get(); }
     const void* logIdentifier() const { return m_logIdentifier; }
-#endif
 
+private:
+
+    TrackData* trackDataForTrackNumber(uint64_t);
+
     // webm::Callback
     webm::Status OnElementBegin(const webm::ElementMetadata&, webm::Action*) final;
     webm::Status OnElementEnd(const webm::ElementMetadata&) final;
@@ -135,20 +245,18 @@
 
     State m_state { State::None };
 
-    class StreamingVectorReader;
     UniqueRef<StreamingVectorReader> m_reader;
 
-    Vector<TrackData> m_tracks;
+    Vector<UniqueRef<TrackData>> m_tracks;
     using BlockVariant = Variant<webm::Block, webm::SimpleBlock>;
     Optional<BlockVariant> m_currentBlock;
     Optional<uint64_t> m_rewindToPosition;
+    float m_minimumAudioSampleDuration { 2 };
 
     Box<BinarySemaphore> m_initializationSegmentIsHandledSemaphore;
 
-#if !RELEASE_LOG_DISABLED
     RefPtr<const WTF::Logger> m_logger;
     const void* m_logIdentifier { nullptr };
-#endif
 };
 
 }
@@ -157,4 +265,12 @@
     static bool isType(const WebCore::SourceBufferParser& parser) { return parser.type() == WebCore::SourceBufferParser::Type::WebM; }
 SPECIALIZE_TYPE_TRAITS_END()
 
+SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::SourceBufferParserWebM::VideoTrackData)
+    static bool isType(const WebCore::SourceBufferParserWebM::TrackData& trackData) { return trackData.trackType() == WebCore::SourceBufferParserWebM::TrackData::Type::Video; }
+SPECIALIZE_TYPE_TRAITS_END()
+
+SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::SourceBufferParserWebM::AudioTrackData)
+    static bool isType(const WebCore::SourceBufferParserWebM::TrackData& trackData) { return trackData.trackType() == WebCore::SourceBufferParserWebM::TrackData::Type::Audio; }
+SPECIALIZE_TYPE_TRAITS_END()
+
 #endif // ENABLE(MEDIA_SOURCE)

Modified: trunk/Source/WebCore/platform/graphics/cocoa/VP9UtilitiesCocoa.h (270661 => 270662)


--- trunk/Source/WebCore/platform/graphics/cocoa/VP9UtilitiesCocoa.h	2020-12-11 00:17:23 UTC (rev 270661)
+++ trunk/Source/WebCore/platform/graphics/cocoa/VP9UtilitiesCocoa.h	2020-12-11 00:45:46 UTC (rev 270662)
@@ -28,7 +28,14 @@
 #if ENABLE(VP9) && PLATFORM(COCOA)
 
 #include "VP9Utilities.h"
+#include <webm/dom_types.h>
 
+typedef const struct opaqueCMFormatDescription* CMFormatDescriptionRef;
+
+namespace vp9_parser {
+class Vp9HeaderParser;
+}
+
 namespace WebCore {
 
 struct MediaCapabilitiesInfo;
@@ -44,6 +51,8 @@
 extern bool isVPCodecConfigurationRecordSupported(VPCodecConfigurationRecord&);
 extern bool validateVPParameters(VPCodecConfigurationRecord&, MediaCapabilitiesInfo&, const VideoConfiguration&);
 
+RetainPtr<CMFormatDescriptionRef> createFormatDescriptionFromVP9HeaderParser(const vp9_parser::Vp9HeaderParser&, const webm::Element<webm::Colour>&);
+
 }
 
 #endif

Modified: trunk/Source/WebCore/platform/graphics/cocoa/VP9UtilitiesCocoa.mm (270661 => 270662)


--- trunk/Source/WebCore/platform/graphics/cocoa/VP9UtilitiesCocoa.mm	2020-12-11 00:17:23 UTC (rev 270661)
+++ trunk/Source/WebCore/platform/graphics/cocoa/VP9UtilitiesCocoa.mm	2020-12-11 00:45:46 UTC (rev 270662)
@@ -23,8 +23,8 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "VP9UtilitiesCocoa.h"
+#import "config.h"
+#import "VP9UtilitiesCocoa.h"
 
 #if ENABLE(VP9) && PLATFORM(COCOA)
 
@@ -36,13 +36,20 @@
 #import "SystemBattery.h"
 #import "VideoConfiguration.h"
 #import <CoreMedia/CMFormatDescription.h>
+#import <_javascript_Core/DataView.h>
+#import <common/vp9_header_parser.h>
 #import <wtf/text/StringToIntegerConversion.h>
 
 #import <pal/cocoa/AVFoundationSoftLink.h>
+#import <pal/cf/CoreMediaSoftLink.h>
+#import "CoreVideoSoftLink.h"
 #import "VideoToolboxSoftLink.h"
 
 namespace WebCore {
 
+using namespace PAL;
+using namespace webm;
+
 static bool hardwareVP9DecoderDisabledForTesting { false };
 
 struct OverrideScreenData {
@@ -257,6 +264,288 @@
     return true;
 }
 
+static uint8_t convertToColorPrimaries(const Primaries& coefficients)
+{
+    switch (coefficients) {
+    case Primaries::kBt709:
+        return VPConfigurationColorPrimaries::BT_709_6;
+    case Primaries::kUnspecified:
+        return VPConfigurationColorPrimaries::Unspecified;
+    case Primaries::kBt470M:
+        return VPConfigurationColorPrimaries::BT_470_6_M;
+    case Primaries::kBt470Bg:
+        return VPConfigurationColorPrimaries::BT_470_7_BG;
+    case Primaries::kSmpte170M:
+        return VPConfigurationColorPrimaries::BT_601_7;
+    case Primaries::kSmpte240M:
+        return VPConfigurationColorPrimaries::SMPTE_ST_240;
+    case Primaries::kFilm:
+        return VPConfigurationColorPrimaries::Film;
+    case Primaries::kBt2020:
+        return VPConfigurationColorPrimaries::BT_2020_Nonconstant_Luminance;
+    case Primaries::kSmpteSt4281:
+        return VPConfigurationColorPrimaries::SMPTE_ST_428_1;
+    case Primaries::kSmpteRp431:
+        return VPConfigurationColorPrimaries::SMPTE_RP_431_2;
+    case Primaries::kSmpteEg432:
+        return VPConfigurationColorPrimaries::SMPTE_EG_432_1;
+    case Primaries::kJedecP22Phosphors:
+        return VPConfigurationColorPrimaries::EBU_Tech_3213_E;
+    }
 }
 
+static CFStringRef convertToCMColorPrimaries(uint8_t primaries)
+{
+    switch (primaries) {
+    case VPConfigurationColorPrimaries::BT_709_6:
+        return kCVImageBufferColorPrimaries_ITU_R_709_2;
+    case VPConfigurationColorPrimaries::EBU_Tech_3213_E:
+        return kCVImageBufferColorPrimaries_EBU_3213;
+    case VPConfigurationColorPrimaries::BT_601_7:
+    case VPConfigurationColorPrimaries::SMPTE_ST_240:
+        return kCVImageBufferColorPrimaries_SMPTE_C;
+    case VPConfigurationColorPrimaries::SMPTE_RP_431_2:
+        return kCMFormatDescriptionColorPrimaries_DCI_P3;
+    case VPConfigurationColorPrimaries::SMPTE_EG_432_1:
+        return kCMFormatDescriptionColorPrimaries_P3_D65;
+    case VPConfigurationColorPrimaries::BT_2020_Nonconstant_Luminance:
+        return kCMFormatDescriptionColorPrimaries_ITU_R_2020;
+    }
+
+    return nullptr;
+}
+
+static uint8_t convertToTransferCharacteristics(const TransferCharacteristics& characteristics)
+{
+    switch (characteristics) {
+    case TransferCharacteristics::kBt709:
+        return VPConfigurationTransferCharacteristics::BT_709_6;
+    case TransferCharacteristics::kUnspecified:
+        return VPConfigurationTransferCharacteristics::Unspecified;
+    case TransferCharacteristics::kGamma22curve:
+        return VPConfigurationTransferCharacteristics::BT_470_6_M;
+    case TransferCharacteristics::kGamma28curve:
+        return VPConfigurationTransferCharacteristics::BT_470_7_BG;
+    case TransferCharacteristics::kSmpte170M:
+        return VPConfigurationTransferCharacteristics::BT_601_7;
+    case TransferCharacteristics::kSmpte240M:
+        return VPConfigurationTransferCharacteristics::SMPTE_ST_240;
+    case TransferCharacteristics::kLinear:
+        return VPConfigurationTransferCharacteristics::Linear;
+    case TransferCharacteristics::kLog:
+        return VPConfigurationTransferCharacteristics::Logrithmic;
+    case TransferCharacteristics::kLogSqrt:
+        return VPConfigurationTransferCharacteristics::Logrithmic_Sqrt;
+    case TransferCharacteristics::kIec6196624:
+        return VPConfigurationTransferCharacteristics::IEC_61966_2_4;
+    case TransferCharacteristics::kBt1361ExtendedColourGamut:
+        return VPConfigurationTransferCharacteristics::BT_1361_0;
+    case TransferCharacteristics::kIec6196621:
+        return VPConfigurationTransferCharacteristics::IEC_61966_2_1;
+    case TransferCharacteristics::k10BitBt2020:
+        return VPConfigurationTransferCharacteristics::BT_2020_10bit;
+    case TransferCharacteristics::k12BitBt2020:
+        return VPConfigurationTransferCharacteristics::BT_2020_12bit;
+    case TransferCharacteristics::kSmpteSt2084:
+        return VPConfigurationTransferCharacteristics::SMPTE_ST_2084;
+    case TransferCharacteristics::kSmpteSt4281:
+        return VPConfigurationTransferCharacteristics::SMPTE_ST_428_1;
+    case TransferCharacteristics::kAribStdB67Hlg:
+        return VPConfigurationTransferCharacteristics::BT_2100_HLG;
+    }
+}
+
+static CFStringRef convertToCMTransferFunction(uint8_t characteristics)
+{
+    switch (characteristics) {
+    case VPConfigurationTransferCharacteristics::BT_709_6:
+        return kCVImageBufferTransferFunction_ITU_R_709_2;
+    case VPConfigurationTransferCharacteristics::SMPTE_ST_240:
+        return kCVImageBufferTransferFunction_SMPTE_240M_1995;
+    case VPConfigurationTransferCharacteristics::SMPTE_ST_2084:
+        return kCMFormatDescriptionTransferFunction_SMPTE_ST_2084_PQ;
+    case VPConfigurationTransferCharacteristics::BT_2020_10bit:
+    case VPConfigurationTransferCharacteristics::BT_2020_12bit:
+        return kCMFormatDescriptionTransferFunction_ITU_R_2020;
+    case VPConfigurationTransferCharacteristics::SMPTE_ST_428_1:
+        return kCMFormatDescriptionTransferFunction_SMPTE_ST_428_1;
+    case VPConfigurationTransferCharacteristics::BT_2100_HLG:
+        return kCMFormatDescriptionTransferFunction_ITU_R_2100_HLG;
+    case VPConfigurationTransferCharacteristics::IEC_61966_2_1:
+        return canLoad_CoreMedia_kCMFormatDescriptionTransferFunction_sRGB() ? PAL::get_CoreMedia_kCMFormatDescriptionTransferFunction_sRGB() : nullptr;
+    case VPConfigurationTransferCharacteristics::Linear:
+        return kCMFormatDescriptionTransferFunction_Linear;
+    }
+
+    return nullptr;
+}
+
+static uint8_t convertToMatrixCoefficients(const MatrixCoefficients& coefficients)
+{
+    switch (coefficients) {
+    case MatrixCoefficients::kRgb:
+        return VPConfigurationMatrixCoefficients::Identity;
+    case MatrixCoefficients::kBt709:
+        return VPConfigurationMatrixCoefficients::BT_709_6;
+    case MatrixCoefficients::kUnspecified:
+        return VPConfigurationMatrixCoefficients::Unspecified;
+    case MatrixCoefficients::kFcc:
+        return VPConfigurationMatrixCoefficients::FCC;
+    case MatrixCoefficients::kBt470Bg:
+        return VPConfigurationMatrixCoefficients::BT_470_7_BG;
+    case MatrixCoefficients::kSmpte170M:
+        return VPConfigurationMatrixCoefficients::BT_601_7;
+    case MatrixCoefficients::kSmpte240M:
+        return VPConfigurationMatrixCoefficients::SMPTE_ST_240;
+    case MatrixCoefficients::kYCgCo:
+        return VPConfigurationMatrixCoefficients::YCgCo;
+    case MatrixCoefficients::kBt2020NonconstantLuminance:
+        return VPConfigurationMatrixCoefficients::BT_2020_Nonconstant_Luminance;
+    case MatrixCoefficients::kBt2020ConstantLuminance:
+        return VPConfigurationMatrixCoefficients::BT_2020_Constant_Luminance;
+    }
+}
+
+static CFStringRef convertToCMYCbCRMatrix(uint8_t coefficients)
+{
+    switch (coefficients) {
+    case VPConfigurationMatrixCoefficients::BT_2020_Nonconstant_Luminance:
+        return kCMFormatDescriptionYCbCrMatrix_ITU_R_2020;
+    case VPConfigurationMatrixCoefficients::BT_470_7_BG:
+    case VPConfigurationMatrixCoefficients::BT_601_7:
+        return kCVImageBufferYCbCrMatrix_ITU_R_601_4;
+    case VPConfigurationMatrixCoefficients::BT_709_6:
+        return kCVImageBufferYCbCrMatrix_ITU_R_709_2;
+    case VPConfigurationMatrixCoefficients::SMPTE_ST_240:
+        return kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
+    }
+
+    return nullptr;
+}
+
+static uint8_t convertSubsamplingXYToChromaSubsampling(uint64_t x, uint64_t y)
+{
+    if (x & y)
+        return VPConfigurationChromaSubsampling::Subsampling_420_Colocated;
+    if (x & !y)
+        return VPConfigurationChromaSubsampling::Subsampling_422;
+    if (!x & !y)
+        return VPConfigurationChromaSubsampling::Subsampling_444;
+    // This indicates 4:4:0 subsampling, which is not expressable in the 'vpcC' box. Default to 4:2:0.
+    return VPConfigurationChromaSubsampling::Subsampling_420_Colocated;
+}
+
+RetainPtr<CMFormatDescriptionRef> createFormatDescriptionFromVP9HeaderParser(const vp9_parser::Vp9HeaderParser& parser, const webm::Element<Colour>& color)
+{
+    // Ref: "VP Codec ISO Media File Format Binding, v1.0, 2017-03-31"
+    // <https://www.webmproject.org/vp9/mp4/>
+    //
+    // class VPCodecConfigurationBox extends FullBox('vpcC', version = 1, 0)
+    // {
+    //     VPCodecConfigurationRecord() vpcConfig;
+    // }
+    //
+    // aligned (8) class VPCodecConfigurationRecord {
+    //     unsigned int (8)     profile;
+    //     unsigned int (8)     level;
+    //     unsigned int (4)     bitDepth;
+    //     unsigned int (3)     chromaSubsampling;
+    //     unsigned int (1)     videoFullRangeFlag;
+    //     unsigned int (8)     colourPrimaries;
+    //     unsigned int (8)     transferCharacteristics;
+    //     unsigned int (8)     matrixCoefficients;
+    //     unsigned int (16)    codecIntializationDataSize;
+    //     unsigned int (8)[]   codecIntializationData;
+    // }
+    //
+    // codecIntializationDataSize​For VP8 and VP9 this field must be 0.
+    // codecIntializationData​binary codec initialization data. Not used for VP8 and VP9.
+    //
+    // FIXME: Convert existing struct to an ISOBox and replace the writing code below
+    // with a subclass of ISOFullBox.
+
+    VPCodecConfigurationRecord record;
+
+    record.profile = ""
+    // CoreMedia does nat care about the VP9 codec level; hard-code to Level 1.0 here:
+    record.level = 10;
+    record.bitDepth = parser.bit_depth();
+    record.videoFullRangeFlag = parser.color_range() ? VPConfigurationRange::FullRange : VPConfigurationRange::VideoRange;
+    record.chromaSubsampling = convertSubsamplingXYToChromaSubsampling(parser.subsampling_x(), parser.subsampling_y());
+    record.colorPrimaries = VPConfigurationColorPrimaries::Unspecified;
+    record.transferCharacteristics = VPConfigurationTransferCharacteristics::Unspecified;
+    record.matrixCoefficients = VPConfigurationMatrixCoefficients::Unspecified;
+
+    // Container color values can override per-sample ones:
+    if (color.is_present()) {
+        auto& colorValue = color.value();
+        if (colorValue.chroma_subsampling_x.is_present() && colorValue.chroma_subsampling_y.is_present())
+            record.chromaSubsampling = convertSubsamplingXYToChromaSubsampling(colorValue.chroma_subsampling_x.value(), colorValue.chroma_subsampling_y.value());
+        if (colorValue.range.is_present() && colorValue.range.value() != Range::kUnspecified)
+            record.videoFullRangeFlag = colorValue.range.value() == Range::kFull ? VPConfigurationRange::FullRange : VPConfigurationRange::VideoRange;
+        if (colorValue.bits_per_channel.is_present())
+            record.bitDepth = colorValue.bits_per_channel.value();
+        if (colorValue.transfer_characteristics.is_present())
+            record.transferCharacteristics = convertToTransferCharacteristics(colorValue.transfer_characteristics.value());
+        if (colorValue.matrix_coefficients.is_present())
+            record.matrixCoefficients = convertToMatrixCoefficients(colorValue.matrix_coefficients.value());
+        if (colorValue.primaries.is_present())
+            record.colorPrimaries = convertToColorPrimaries(colorValue.primaries.value());
+    }
+
+    constexpr size_t VPCodecConfigurationContentsSize = 12;
+
+    uint32_t versionAndFlags = 1 << 24;
+    uint8_t bitDepthChromaAndRange = (0xF & record.bitDepth) << 4 | (0x7 & record.chromaSubsampling) << 1 | (0x1 & record.videoFullRangeFlag);
+    uint16_t codecIntializationDataSize = 0;
+
+    auto view = JSC::DataView::create(ArrayBuffer::create(VPCodecConfigurationContentsSize, 1), 0, VPCodecConfigurationContentsSize);
+    view->set(0, versionAndFlags, false);
+    view->set(4, record.profile, false);
+    view->set(5, record.level, false);
+    view->set(6, bitDepthChromaAndRange, false);
+    view->set(7, record.colorPrimaries, false);
+    view->set(8, record.transferCharacteristics, false);
+    view->set(9, record.matrixCoefficients, false);
+    view->set(10, codecIntializationDataSize, false);
+
+    auto data = "" (const UInt8 *)view->data(), view->byteLength()));
+
+    CFTypeRef configurationKeys[] = { CFSTR("vpcC") };
+    CFTypeRef configurationValues[] = { data.get() };
+    auto configurationDict = adoptCF(CFDictionaryCreate(kCFAllocatorDefault, configurationKeys, configurationValues, WTF_ARRAY_LENGTH(configurationKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
+
+    Vector<CFTypeRef> extensionsKeys { kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms };
+    Vector<CFTypeRef> extensionsValues = { configurationDict.get() };
+
+    if (record.videoFullRangeFlag == VPConfigurationRange::FullRange) {
+        extensionsKeys.append(kCMFormatDescriptionExtension_FullRangeVideo);
+        extensionsValues.append(kCFBooleanTrue);
+    }
+
+    if (auto cmColorPrimaries = convertToCMColorPrimaries(record.colorPrimaries)) {
+        extensionsKeys.append(kCVImageBufferColorPrimariesKey);
+        extensionsValues.append(cmColorPrimaries);
+    }
+
+    if (auto cmTransferFunction = convertToCMTransferFunction(record.transferCharacteristics)) {
+        extensionsKeys.append(kCVImageBufferTransferFunctionKey);
+        extensionsValues.append(cmTransferFunction);
+    }
+
+    if (auto cmMatrix = convertToCMYCbCRMatrix(record.matrixCoefficients)) {
+        extensionsKeys.append(kCVImageBufferYCbCrMatrixKey);
+        extensionsValues.append(cmMatrix);
+    }
+
+    auto extensions = adoptCF(CFDictionaryCreate(kCFAllocatorDefault, extensionsKeys.data(), extensionsValues.data(), extensionsKeys.size(), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
+
+    CMVideoFormatDescriptionRef formatDescription = nullptr;
+    if (noErr != CMVideoFormatDescriptionCreate(kCFAllocatorDefault, kCMVideoCodecType_VP9, parser.width(), parser.height(), extensions.get(), &formatDescription))
+        return nullptr;
+    return adoptCF(formatDescription);
+}
+
+}
+
 #endif // PLATFORM(COCOA)

Copied: trunk/Source/WebCore/platform/graphics/cocoa/WebMAudioUtilitiesCocoa.h (from rev 270661, trunk/Source/WebCore/platform/cocoa/MediaUtilities.h) (0 => 270662)


--- trunk/Source/WebCore/platform/graphics/cocoa/WebMAudioUtilitiesCocoa.h	                        (rev 0)
+++ trunk/Source/WebCore/platform/graphics/cocoa/WebMAudioUtilitiesCocoa.h	2020-12-11 00:45:46 UTC (rev 270662)
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2020 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#if PLATFORM(COCOA)
+
+#include <wtf/RetainPtr.h>
+
+class AudioStreamDescription;
+typedef const struct opaqueCMFormatDescription* CMFormatDescriptionRef;
+
+namespace WebCore {
+
+bool isVorbisDecoderAvailable();
+RetainPtr<CMFormatDescriptionRef> createVorbisAudioFormatDescription(size_t, const void*);
+
+bool isOpusDecoderAvailable();
+RetainPtr<CMFormatDescriptionRef> createOpusAudioFormatDescription(size_t, const void*);
+
+}
+
+#endif // && PLATFORM(COCOA)

Added: trunk/Source/WebCore/platform/graphics/cocoa/WebMAudioUtilitiesCocoa.mm (0 => 270662)


--- trunk/Source/WebCore/platform/graphics/cocoa/WebMAudioUtilitiesCocoa.mm	                        (rev 0)
+++ trunk/Source/WebCore/platform/graphics/cocoa/WebMAudioUtilitiesCocoa.mm	2020-12-11 00:45:46 UTC (rev 270662)
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2020 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "config.h"
+#import "WebMAudioUtilitiesCocoa.h"
+
+#if PLATFORM(COCOA)
+
+#import "CAAudioStreamDescription.h"
+#import "Logging.h"
+#import "MediaUtilities.h"
+#import <AudioToolbox/AudioComponent.h>
+#import <AudioToolbox/AudioFormat.h>
+#import <CoreMedia/CMFormatDescription.h>
+#import <dlfcn.h>
+
+namespace WebCore {
+
+#if ENABLE(VORBIS) || ENABLE(OPUS)
+static bool registerDecoderFactory(const char* decoderName, OSType decoderType)
+{
+    constexpr char audioComponentsDylib[] = "/System/Library/Components/AudioCodecs.component/Contents/MacOS/AudioCodecs";
+    void *handle = dlopen(audioComponentsDylib, RTLD_LAZY | RTLD_LOCAL);
+    if (!handle)
+        return false;
+
+    AudioComponentFactoryFunction decoderFactory = reinterpret_cast<AudioComponentFactoryFunction>(dlsym(handle, decoderName));
+    if (!decoderFactory)
+        return false;
+
+    AudioComponentDescription desc { 'adec', decoderType, 'appl', kAudioComponentFlag_SandboxSafe, 0 };
+    if (!AudioComponentRegister(&desc, CFSTR(""), 0, decoderFactory)) {
+        dlclose(handle);
+        return false;
+    }
+
+    return true;
+}
+
+static RetainPtr<CMFormatDescriptionRef> createAudioFormatDescriptionForFormat(OSType formatID, Vector<uint8_t> magicCookie)
+{
+    AudioStreamBasicDescription asbd { };
+    asbd.mFormatID = formatID;
+    uint32_t size = sizeof(asbd);
+    auto error = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, magicCookie.size(), magicCookie.data(), &size, &asbd);
+    if (error) {
+        RELEASE_LOG_ERROR(Media, "createAudioFormatDescriptionForFormat failed with error %d (%.4s)", error, (char *)&error);
+        return nullptr;
+    }
+
+    return createAudioFormatDescription(CAAudioStreamDescription(asbd), magicCookie.size(), magicCookie.data());
+}
+#endif // ENABLE(VORBIS) || ENABLE(OPUS)
+
+#if ENABLE(OPUS)
+static Vector<uint8_t> cookieFromOpusCodecPrivate(size_t, const void*)
+{
+    return { };
+}
+#endif
+
+bool isOpusDecoderAvailable()
+{
+    static bool available;
+
+#if ENABLE(OPUS) && PLATFORM(MAC)
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        available = registerDecoderFactory("ACOpusDecoderFactory", 'opus');
+    });
+#endif
+
+    return available;
+}
+
+RetainPtr<CMFormatDescriptionRef> createOpusAudioFormatDescription(size_t privateDataSize, const void* privateData)
+{
+#if ENABLE(OPUS)
+    if (!isOpusDecoderAvailable())
+        return nullptr;
+
+    auto cookieData = cookieFromOpusCodecPrivate(privateDataSize, privateData);
+    if (!cookieData.size())
+        return nullptr;
+
+    return createAudioFormatDescriptionForFormat('opus', cookieData);
+#else
+    UNUSED_PARAM(privateDataSize);
+    UNUSED_PARAM(privateData);
+    return nullptr;
+#endif
+}
+
+#if ENABLE(VORBIS)
+static Vector<uint8_t> cookieFromVorbisCodecPrivate(size_t codecPrivateSize, const void* codecPrivateData)
+{
+    // https://tools.ietf.org/html/draft-ietf-cellar-codec-03
+    // 6.4.15. A_VORBIS
+    // Codec ID: A_VORBIS
+    // Codec Name: Vorbis
+    // Initialization: The "Private Data" contains the first three Vorbis packet in order. The lengths of the
+    // packets precedes them. The actual layout is:
+    // - Byte 1: number of distinct packets '"#p"' minus one inside the CodecPrivate block.This MUST be '2'
+    //   for current (as of 2016-07-08) Vorbis headers.
+    // - Bytes 2..n: lengths of the first '"#p"' packets, coded in Xiph-style lacing. The length of the last
+    //   packet is the length of the CodecPrivate block minus the lengths coded in these bytes minus one.
+    // - Bytes n+1..: The Vorbis identification header, followed by the Vorbis comment header followed by the
+    //   codec setup header.
+
+    const unsigned char* privateDataPtr = static_cast<const unsigned char*>(codecPrivateData);
+
+    const int vorbisMinimumCookieSize = 3;
+    if (codecPrivateSize < vorbisMinimumCookieSize) {
+        RELEASE_LOG_ERROR(Media, "cookieFromVorbisCodecPrivate: codec private data too small (%zu)", codecPrivateSize);
+        return { };
+    }
+
+    // Despite the "This MUST be '2'" comment in the IETF document, packet count is not always equal to
+    // 2 in real-word files, so ignore that field.
+    const uint16_t idHeaderSize = privateDataPtr[1];
+    const uint16_t commentHeaderSize = privateDataPtr[2];
+    const uint16_t calculatedHeaderSize = 1 + idHeaderSize + commentHeaderSize;
+    if (1 + idHeaderSize + commentHeaderSize > codecPrivateSize) {
+        RELEASE_LOG_ERROR(Media, "cookieFromVorbisCodecPrivate: codec private data too small (%zu) for header sizes (%d)", codecPrivateSize, calculatedHeaderSize);
+        return { };
+    }
+
+    const unsigned char* idHeader = &privateDataPtr[3];
+    const unsigned char* commentHeader = idHeader + idHeaderSize;
+    const unsigned char* codecSetupHeader = commentHeader + commentHeaderSize;
+    const uint16_t codecSetupHeaderSize = codecPrivateSize - idHeaderSize - commentHeaderSize - 2 - 1;
+
+    if ((idHeaderSize + commentHeaderSize + codecSetupHeaderSize + 3) > codecPrivateSize) {
+        RELEASE_LOG_ERROR(Media, "cookieFromVorbisCodecPrivate: codec private header size is invalid - id = %d, comment = %d, header = %d, chunk size = %zu", idHeaderSize, commentHeaderSize, codecSetupHeaderSize, codecPrivateSize);
+        return { };
+    }
+
+    Vector<uint8_t> cookieData;
+    cookieData.append(reinterpret_cast_ptr<const uint8_t*>(&idHeaderSize), sizeof(idHeaderSize));
+    cookieData.append(idHeader, idHeaderSize);
+
+    cookieData.append(reinterpret_cast_ptr<const uint8_t*>(&commentHeaderSize), sizeof(commentHeaderSize));
+    cookieData.append(commentHeader, commentHeaderSize);
+
+    cookieData.append(reinterpret_cast_ptr<const uint8_t*>(&codecSetupHeaderSize), sizeof(codecSetupHeaderSize));
+    cookieData.append(codecSetupHeader, codecSetupHeaderSize);
+
+    return cookieData;
+}
+#endif // ENABLE(VORBIS)
+
+bool isVorbisDecoderAvailable()
+{
+    static bool available;
+
+#if ENABLE(VORBIS) && PLATFORM(MAC)
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        available = registerDecoderFactory("ACVorbisDecoderFactory", 'vorb');
+    });
+#endif
+
+    return available;
+}
+
+RetainPtr<CMFormatDescriptionRef> createVorbisAudioFormatDescription(size_t privateDataSize, const void* privateData)
+{
+#if ENABLE(VORBIS)
+    if (!isVorbisDecoderAvailable())
+        return nullptr;
+
+    auto cookieData = cookieFromVorbisCodecPrivate(privateDataSize, privateData);
+    if (!cookieData.size())
+        return nullptr;
+
+    return createAudioFormatDescriptionForFormat('vorb', cookieData);
+#else
+    UNUSED_PARAM(privateDataSize);
+    UNUSED_PARAM(privateData);
+    return nullptr;
+#endif
+}
+
+}
+
+#endif // PLATFORM(COCOA)
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to