Skip to content

PoC: SGAI alterantive cmcd vast events#161

Draft
cotid-qualabs wants to merge 343 commits intodevelopmentfrom
sgai/alterantive-cmcd-vast
Draft

PoC: SGAI alterantive cmcd vast events#161
cotid-qualabs wants to merge 343 commits intodevelopmentfrom
sgai/alterantive-cmcd-vast

Conversation

@cotid-qualabs
Copy link

@cotid-qualabs cotid-qualabs commented Feb 4, 2026

Alternative MPD and List MPD implementation with:

  • CMCDv2 integration.
  • CMCD reporting for vast events (start, firstQuartile, etc) using custom events.
  • Callback Event to vast urls

cotid-qualabs and others added 30 commits February 26, 2025 11:52
Co-authored-by: Sebastian Piquerez <89274285+sebastianpiq@users.noreply.github.com>
[MPDList] Add sample page for List MPDs
[MPDList] Fix MPD Lists BaseURI issues
…ds-bug

[MPDList] Fix handling of periods with duration but without start time
…eOffset-default

[AlternativeMPD] Add default (60 seconds) to the erliestResolutionTimeOffset
cotid-qualabs and others added 28 commits January 14, 2026 15:30
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
* feat: implement CMCD v2 functionality

* remove unused function

* Update src/dash/vo/EventTarget.js

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* cmcdvs parameters unit test

* fix unit tests

* add batch config from mpd

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
* cmcd reporter initialization

* request mode migration

* event mode migration

* cmcd model migration

* fix cmcd model unit tests

* fixes for cmcd parameters and cleanup -
protection controller fixes WIP

* cleanup and update unit tests

* refactor unit tests and fixes

* fix unit tests and remove batchTimer
* ab, lab and tab inner list and request mode

* ab, tab and lab inner list for v2

* bl inner list and event mode

* br inner list and event mode

* toInnerList helper

* bsd inner list

* mtp inner list and event mode

* nor inner list

* pb inner list and event mode

* tp inner list and event mode

* tpb inner list and event mode

* fix unit tests
@gemini-code-assist
Copy link

Summary of Changes

Hello @cotid-qualabs, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces significant enhancements to the player's capabilities for dynamic content delivery and client-side media data reporting. It integrates CMCDv2 for advanced analytics, implements support for alternative media presentations (such as ad insertion) through MPD events, and adds functionality for handling List MPD manifests. These changes aim to provide more flexible and robust solutions for content monetization and quality of experience monitoring.

Highlights

  • CMCDv2 Integration: The player now supports CMCDv2, enabling enhanced client-side media data reporting. This includes new methods in the CmcdModel interface for tracking playback states, triggering events, and retrieving generic CMCD data. The @svta/cml-cmcd package has been updated to version 2.0.0 to support these changes. New sample pages demonstrate CMCDv2 reporting and network interceptor usage.
  • Alternative MPD Implementation: New functionality has been added to support alternative media presentations, often used for server-side ad insertion (SGAI). This includes new AlternativeMpd data structures and constants (DashConstants.ALTERNATIVE_MPD) for handling InsertPresentation and ReplacePresentation events within the manifest. Several new sample pages showcase various alternative MPD scenarios, including VOD-to-VOD, VOD-to-Live, Live-to-Live, and specific features like clip, executeOnce, and returnOffset.
  • List MPD Support: The player now supports the List MPD profile, allowing for dynamic manifest manipulation by importing external MPDs into periods. A new ListMpdController manages the loading and merging of these imported manifests. A dedicated sample page demonstrates various List MPD use cases, including single/multiple linked periods and handling of earliestResolutionTimeOffset.
  • VAST Event Reporting via CMCD: CMCD reporting has been extended to cover VAST-related events (e.g., start, firstQuartile) using custom events. This is facilitated by the CMCDv2 integration, allowing for more granular tracking and reporting of ad playback events and callbacks to VAST URLs.
  • Refactored CMCD Configuration Management: The internal handling of CMCD configuration has been refactored using CmcdConfigAccessor and CmcdPropertyMap. This provides a unified, version-aware, and priority-based mechanism for accessing CMCD settings from both player configuration and manifest parameters, simplifying future extensions and maintenance.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • build/webpack/modern/webpack.modern.dev.cjs
    • Changed the webpack dev server port from 3000 to 3001.
  • index.d.ts
    • Added numerous new methods to the CmcdModel interface, including playback state handlers (onStateChange, onPlaybackStarted, onRebufferingStarted, etc.), event triggering (triggerCmcdEventMode), and generic data retrieval (getGenericCmcdData).
    • Removed a trailing newline character from the end of the file.
  • package-lock.json
    • Updated @svta/cml-cmcd from 1.0.1 to 2.0.0.
    • Updated @svta/cml-cmsd from 1.0.1 to 1.0.3.
    • Updated @svta/cml-dash from 1.0.1 to 1.0.3.
    • Updated @svta/cml-id3 from 1.0.1 to 1.0.3.
    • Updated @svta/cml-request from 1.0.1 to 1.0.4.
    • Updated @svta/cml-xml from 1.0.1 to 1.1.1.
    • Added license: Apache-2.0 to all @svta packages.
  • package.json
    • Updated @svta/cml-cmcd from 1.0.1 to 2.0.0.
    • Updated @svta/cml-cmsd from 1.0.1 to 1.0.3.
    • Updated @svta/cml-dash from 1.0.1 to 1.0.3.
    • Updated @svta/cml-id3 from 1.0.1 to 1.0.3.
    • Updated @svta/cml-request from 1.0.1 to 1.0.4.
    • Updated @svta/cml-xml from 1.0.1 to 1.1.1.
  • samples/advanced/cmcd-v2-network-interceptors.html
    • Added a new sample page demonstrating CMCDv2 integration with network interceptors for pre-request and post-response callbacks.
  • samples/advanced/cmcd-v2.html
    • Added a new sample page showcasing CMCDv2 reporting capabilities, including configuration of various transmission modes and event targets.
  • samples/advanced/list-mpds.html
    • Added a new sample page illustrating the implementation of List MPDs, covering various use cases like single/multiple linked periods and duration handling.
  • samples/alternative/alternative-media-presentations.html
    • Added a new sample page demonstrating alternative media presentations with dedicated video elements for content switching using InsertPresentation and ReplacePresentation events.
  • samples/alternative/listen-mode.html
    • Added a new sample page for alternative MPD listen mode, showing how alternative content can be inserted without a fixed duration and later updated via status events.
  • samples/alternative/live-to-live.html
    • Added a new sample page for live-to-live alternative media presentations, demonstrating dynamic event injection for content replacement in live streams.
  • samples/alternative/sgai-insert-test.html
    • Added a new sample page for testing Server-Side Ad Insertion (SGAI) with alternative MPD and List MPDs using insert mode.
  • samples/highlighter.js
    • Modified the HTML structure for the 'Source code' header to use flexbox for alignment and applied Bootstrap styling to the 'Copy to clipboard' button.
  • samples/samples.json
    • Added new entries for 'CMCD v2 Reporting', 'CMCD v2 Callbacks with Network Interceptors', 'List MPD', and a new section 'Alternative Media Presentations' with four related samples.
  • src/core/Settings.js
    • Added listMpds configuration object to streaming settings, including minEarliestResolutionTimeOffset.
    • Added CmcdTarget typedef to describe CMCD reporting targets, including properties like mode, enabled, url, events, timeInterval, enabledKeys, includeOnRequests, and batchRetryDelays.
    • Added targets property to CMCD settings for configuring multiple CMCD reporting endpoints.
    • Added listMpdSettings typedef to describe settings related to List MPD configuration.
  • src/core/events/CoreEvents.js
    • Added new event constants: ALTERNATIVE_EVENT_RECEIVED, EVENT_READY_TO_RESOLVE, ORIGINAL_ALTERNATIVE_MANIFEST_LOADED, ORIGINAL_MANIFEST_LOADED, LIST_MPD_FOUND, LOADING_COMPLETED, LOADING_PROGRESS, LOADING_DATA_PROGRESS.
  • src/dash/DashAdapter.js
    • Added mergeManifests function to handle merging of imported MPDs into the main manifest, including property merging and duration adjustments.
    • Added _mergeEquivalentProperties and removeEmptyProperties helper functions for manifest merging.
    • Added getLinkedPeriods function to retrieve all linked periods from an MPD.
    • Exported getLinkedPeriods and mergeManifests in the instance.
  • src/dash/constants/DashConstants.js
    • Added ALTERNATIVE_MPD constants for InsertPresentation and ReplacePresentation elements, and ALTERNATIVE_MPD_SCHEME_ID.
    • Added EVENT_TARGET constant.
    • Added LIST_PROFILE_SCHEME constant for List MPD profiles.
    • Added MPD_LIST constant for MPD type.
    • Added REPORTING_TARGETS constant.
    • Added STATUS constant.
  • src/dash/models/DashManifestModel.js
    • Imported AlternativeMpd VO.
    • Modified getAdaptationsForType to handle cases where realAdaptations might be null or undefined.
    • Refined getPeriodId to check isNaN(realPeriod.start) for period start time validation.
    • Added getLinkedPeriods function to extract linked periods from the manifest.
    • Updated getEvents to parse alternativeMpd and status attributes from events, and to handle __cdata and #cdata for message data.
    • Added getAlternativeMpd and getAlternativeMpdCommonData functions to parse alternative MPD event data.
    • Updated _createClientDataReportingInstance to support both CTA_5004_2023_SCHEME and CTA_5004_2025_SCHEME for CMCD.
  • src/dash/parser/DashParser.js
    • Added DashConstants.EVENT_TARGET to the list of arrayNodes for XML parsing.
  • src/dash/vo/AlternativeMpd.js
    • Added a new Value Object (AlternativeMpd) to represent alternative MPD event data, including properties for URL, offsets, mode, duration, and clipping behavior.
  • src/dash/vo/CMCDParameters.js
    • Updated init method to parse version as an integer and handle default includeInRequests value.
    • Added parsing logic for ReportingTargets and EventTarget objects for CMCDv2.
  • src/dash/vo/Event.js
    • Added alternativeMpd property to the Event object to store parsed alternative MPD data.
    • Added idInt property to store integer representation of event ID.
    • Added status property to store event status.
    • Added triggeredReadyToResolve and triggeredNoJumpEvent flags for internal event tracking.
  • src/dash/vo/EventTarget.js
    • Added a new Value Object (EventTarget) to represent CMCD reporting target configurations for CMCDv2.
  • src/streaming/ManifestLoader.js
    • Modified the load function to accept linkedPeriod and alternative parameters, enabling specific handling for linked periods and alternative manifests.
    • Updated success and error callbacks to resolve promises for linked periods and trigger ORIGINAL_ALTERNATIVE_MANIFEST_LOADED for alternative manifests.
  • src/streaming/ManifestUpdater.js
    • Modified _onManifestLoaded to check for DashConstants.LIST_PROFILE_SCHEME in manifest profiles and trigger Events.LIST_MPD_FOUND accordingly.
  • src/streaming/MediaManager.js
    • Added a new MediaManager module to handle the lifecycle and switching between main and alternative video content, including prebuffering capabilities.
  • src/streaming/MediaPlayer.js
    • Imported new controllers: AlternativeMediaController, CmcdController, ListMpdController.
    • Updated reset method to include alternativeMediaController.reset() and cmcdController.reset().
    • Modified preload function to accept an optional time parameter for seeking.
    • Added getCmcdReporter method to expose the CMCD reporter instance.
    • Added setAlternativeVideoElement method to set the video element for alternative content.
    • Configured and initialized alternativeMediaController and listMpdController.
  • src/streaming/MediaPlayerEvents.js
    • Added ALTERNATIVE_MANIFEST_LOADED event constant.
  • src/streaming/SourceBufferSink.js
    • Modified _updateEndHandler to safely check if buffer is null before accessing its updating property, preventing potential errors.
  • src/streaming/cmcd/config/CmcdConfigAccessor.js
    • Added a new module CmcdConfigAccessor to provide a unified and version-aware interface for accessing CMCD configuration properties from both player settings and manifest parameters.
  • src/streaming/cmcd/config/CmcdPropertyMap.js
    • Added a new module CmcdPropertyMap to declaratively define mappings for CMCD properties, including paths in settings/manifest, priorities, and transformations.
  • src/streaming/constants/Constants.js
    • Updated CMCD constants to import directly from @svta/cml-cmcd for CMCD_QUERY_KEY, CMCD_MODE_QUERY, CMCD_DEFAULT_TIME_INTERVAL, CMCD_REPORTING_MODE, CMCD_KEYS, CMCD_REPORTING_EVENTS, CMCD_PLAYER_STATES.
    • Added CMCD_MODE_BODY, CMCD_DEFAULT_VERSION, CMCD_DEFAULT_INCLUDE_IN_REQUESTS, CMCD_CONTENT_TYPE_HEADER, CMCD_DEFAULT_BATCH_RETRY_DELAYS.
    • Added CTA_5004_2025_SCHEME.
    • Added ALTERNATIVE_MPD constants, including MODES (replace, insert), STATUS (update, repeat), URIS (replace, insert), ATTRIBUTES (noJump defaults/priority), and events (CONTENT_READY, CONTENT_START, CONTENT_END, EVENT_UPDATED).
  • src/streaming/controllers/AlternativeMediaController.js
    • Added a new module AlternativeMediaController to manage the logic for handling alternative media presentations, including parsing events, prebuffering, and switching content.
  • src/streaming/controllers/CmcdController.js
    • Added a new module CmcdController to manage CMCD reporting, including initialization, event mode reporting, request mode decoration, and integration with CmcdReporter.
    • Refactored CMCD logic from CmcdModel into this controller, leveraging CmcdConfigAccessor.
  • src/streaming/controllers/EventController.js
    • Added NO_JUMP_TRIGGER_ALL, NO_JUMP_TRIGGER_LAST, RETRIGGERABLES_SCHEMES, and MAX_PRESENTATION_TIME_THRESHOLD constants.
    • Implemented _onPlaybackSeeking and _onPlaybackSeeked handlers to reset event timer for accurate event triggering after seeks.
    • Modified _triggerEvents to handle retriggerable events, noJump events, executeOnce events, and earliestResolutionTimeOffset for prebuffering.
    • Modified _addOrUpdateEvent to process status="update" for alternative MPD events, allowing dynamic updates to active events.
    • Added logic to dispatch callback events for external listeners (e.g., CMCD reporting).
  • src/streaming/controllers/ExtUrlQueryInfoController.js
    • Modified _generateQueryParams to skip processing AdaptationSet elements for periods that are ImportedMPD types, preventing incorrect query parameter generation for linked manifests.
  • src/streaming/controllers/ListMpdController.js
    • Added a new module ListMpdController to manage the loading and merging of List MPD manifests, including handling linked periods and their resolution times.
  • src/streaming/controllers/PlaybackController.js
    • Added seekToStartDvrWindow function to seek to the beginning of the DVR window.
    • Added getDvrWindowStart function to retrieve the start time of the DVR window.
    • Modified _onPlaybackProgress to safely check for streamInfo before triggering the event.
  • src/streaming/controllers/StreamController.js
    • Imported ListMpdController.
    • Updated _switchStream logic to incorporate ListMpdController for handling linked periods during stream switching.
    • Modified _onStreamCanLoadNext to prevent preloading for linked periods.
    • Modified _onEnded to check if the next stream is a linked period before attempting to switch.
  • src/streaming/models/CmcdModel.js
    • Refactored CmcdModel to primarily serve as a data calculation and state management layer for CMCD, delegating configuration access to CmcdConfigAccessor.
    • Removed direct event listeners and simplified isCmcdEnabled, getQueryParameter, getHeaderParameters methods.
    • Introduced calculateCmcdDataForRequest, updateMsdData, onPlaybackRateChanged, onManifestLoaded, triggerCmcdEventMode, isIncludedInRequestFilter, getLastMediaTypeRequest.
    • Updated CMCD data calculation logic to support CMCDv2 keys and formats, including br (bitrate list), mtp (measured throughput list), bl (buffer length list), tb (top bitrate list), tpb (top playable bitrate list), pb (playhead bitrate list), bsd (buffer starvation duration), nor (next object request list), df (dropped frames), ltc (live latency), and bg (background state).
    • Added _getAggregatedBitrateData to calculate aggregated, top aggregated, and lowest aggregated bitrates for CMCDv2.
  • src/streaming/models/CustomParametersModel.js
    • Modified _resetInitialSettings to initialize requestInterceptors and responseInterceptors with default CMCD interceptors from CmcdController.
  • src/streaming/net/HTTPLoader.js
    • Removed direct dependency on CmcdModel.
    • Modified load function to pass commonMediaRequest.body to the underlying loader.
    • Removed _updateRequestUrlAndHeadersWithCmcd and _getAdditionalQueryParameter as CMCD handling is now managed by interceptors.
  • src/streaming/net/XHRLoader.js
    • Modified the send method to pass the body from commonMediaRequest to the XHR object, enabling POST requests with CMCD data.
  • src/streaming/protection/Protection.js
    • Updated the configuration passed to ProtectionController to use cmcdController instead of cmcdModel.
  • src/streaming/protection/controllers/ProtectionController.js
    • Updated the configuration to use cmcdController instead of cmcdModel.
    • Modified _doLicenseRequest to integrate with cmcdController.applyCmcdToRequest for CMCD data inclusion in license requests.
  • src/streaming/utils/CapabilitiesFilter.js
    • Modified _getConfigurations and _filterEssentialProperties to skip processing AdaptationSet elements for ImportedMPD periods, ensuring correct manifest filtering for List MPDs.
  • src/streaming/vo/CmcdReportRequest.js
    • Added a new Value Object (CmcdReportRequest) extending FragmentRequest to represent CMCD reporting requests.
  • src/streaming/vo/CommonMediaRequest.js
    • Added a body property to CommonMediaRequest to support sending data in the request body (e.g., for CMCD event mode).
  • src/streaming/vo/metrics/HTTPRequest.js
    • Added POST as a new HTTP method.
    • Added CMCD_EVENT as a new request type for CMCD reporting.
  • test/functional/adapter/DashJsAdapter.js
    • Added alternativeVideoElement property to the adapter.
    • Added initForAlternativeMedia method to initialize the player for alternative media scenarios.
  • test/functional/config/test-configurations/streams/alternative-mpd.json
    • Added a new test configuration file for alternative MPD functional tests, including various replace and insert scenarios for VOD and Live content.
  • test/functional/content/alternative-mpd/alternative-mpd-clip.mpd
    • Added a new MPD file for testing alternative MPD clip functionality.
  • test/functional/content/alternative-mpd/alternative-mpd-executeOnce.mpd
    • Added a new MPD file for testing alternative MPD executeOnce functionality.
  • test/functional/content/alternative-mpd/alternative-mpd-insert-vod-to-live.mpd
    • Added a new MPD file for testing VOD-to-Live alternative MPD insert scenarios.
  • test/functional/content/alternative-mpd/alternative-mpd-insert-vod-to-vod.mpd
    • Added a new MPD file for testing VOD-to-VOD alternative MPD insert scenarios.
  • test/functional/content/alternative-mpd/alternative-mpd-replace-vod-to-live.mpd
    • Added a new MPD file for testing VOD-to-Live alternative MPD replace scenarios.
  • test/functional/content/alternative-mpd/alternative-mpd-replace-vod-to-vod.mpd
    • Added a new MPD file for testing VOD-to-VOD alternative MPD replace scenarios.
  • test/functional/test/common/common.js
    • Added initializeDashJsAdapterForAlternativMedia function to facilitate functional testing of alternative media features.
  • test/functional/test/feature-support/alternative/alternative-mpd-clip-live.js
    • Added new functional tests for alternative MPD replace events with clip functionality in live-to-live scenarios.
  • test/functional/test/feature-support/alternative/alternative-mpd-clip-vod.js
    • Added new functional tests for alternative MPD replace events with clip functionality in VOD-to-VOD scenarios.
  • test/functional/test/feature-support/alternative/alternative-mpd-executeOnce.js
    • Added new functional tests for alternative MPD insert events with executeOnce functionality.
  • test/functional/test/feature-support/alternative/alternative-mpd-insert-vod.js
    • Added new functional tests for alternative MPD insert events in VOD-to-VOD and VOD-to-Live scenarios.
  • test/functional/test/feature-support/alternative/alternative-mpd-replace-live.js
    • Added new functional tests for alternative MPD replace events in live-to-live and live-to-VOD scenarios.
  • test/functional/test/feature-support/alternative/alternative-mpd-replace-vod.js
    • Added new functional tests for alternative MPD replace events in VOD-to-VOD and VOD-to-Live scenarios.
  • test/functional/test/feature-support/alternative/alternative-mpd-returnOffset.js
    • Added new functional tests for alternative MPD replace events with returnOffset functionality.
  • test/functional/test/feature-support/alternative/alternative-mpd-status-update-live.js
    • Added new functional tests for alternative MPD status update functionality in live streams.
  • test/functional/view/index.html
    • Added an alternative-video-element to the HTML for displaying alternative content.
  • test/unit/data/dash/manifest_list_mpd.xml
    • Added a new XML manifest file for unit testing List MPD functionality.
  • test/unit/helpers/MPDHelper.js
    • Added getListMpd method to create a mock List MPD manifest.
    • Added composeLinkedPeriod method to create mock linked periods.
  • test/unit/mocks/CmcdConfigAccessorMock.js
    • Added a new mock for CmcdConfigAccessor to facilitate unit testing of CMCD-related modules.
  • test/unit/mocks/DashMetricsMock.js
    • Added getCurrentDroppedFrames method to the mock.
  • test/unit/mocks/ManifestLoaderMock.js
    • Updated ManifestLoaderMock to handle promises and simulate success/failure for linked period loading.
  • test/unit/mocks/MediaManagerMock.js
    • Added a new mock for MediaManager to simulate alternative media playback management.
  • test/unit/mocks/StreamMock.js
    • Added getRepresentationsByType method to the mock.
  • test/unit/mocks/VideoModelMock.js
    • Added isPlaying method to the mock.
  • test/unit/test/streaming/streaming.ListMpdController.js
    • Added new unit tests for ListMpdController, covering manifest updates, linked period loading, and error handling.
  • test/unit/test/streaming/streaming.MediaManager.js
    • Added new unit tests for MediaManager, covering alternative video element setup, prebuffering, and content switching.
  • test/unit/test/streaming/streaming.controllers.AlternativeMediaController.js
    • Added new unit tests for AlternativeMediaController, covering configuration, event triggering (REPLACE/INSERT), anchor parsing, event ready to resolve, and switch-back logic.
  • test/unit/test/streaming/streaming.controllers.CmcdController.js
    • Added new unit tests for CmcdController, covering event mode and response mode reporting, CMCDv2 features, error handling, and manifest-based target configurations.
  • test/unit/test/streaming/streaming.controllers.EventController.js
    • Added new unit tests for EventController, specifically for noJump event handling, earliestResolutionTimeOffset triggering, and seek event handling to prevent false positives.
  • test/unit/test/streaming/streaming.models.CmcdModel.js
    • Refactored unit tests for CmcdModel to align with the new CmcdController and CmcdConfigAccessor architecture, focusing on data calculation and state management.
  • test/unit/test/streaming/streaming.net.HTTPLoader.js
    • Updated tests to reflect the change from cmcdModel to cmcdController for CMCD integration.
  • test/unit/test/streaming/streaming.protection.controllers.ProtectionController.js
    • Updated tests to reflect the change from cmcdModel to cmcdController for CMCD integration in license requests.
Activity
  • This pull request is a Proof of Concept (PoC) for the described features. No specific reviewer comments or approvals have been recorded yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces significant new functionality, including CMCDv2 integration, List MPD support, and Alternative Media Presentations. The architecture, especially the refactoring of CMCD logic into a dedicated controller and the addition of controllers for List MPDs and Alternative Media, is a major step forward. However, the implementation introduces a critical security vulnerability: the player makes network requests to URLs provided directly in the MPD manifest without validation. This can be exploited by a malicious manifest to perform forced requests from the user's browser (a form of client-side SSRF), potentially leading to data leakage (e.g., session IDs) or interaction with internal network services. It is strongly recommended to implement URL validation or allow-listing for all URLs extracted from the manifest that trigger network requests. Additionally, I've identified a few minor bugs and areas for potential refactoring to improve clarity and type safety.

Comment on lines 65 to 67
this.LOADING_ABANDONED = 'loadingAborted';
this.LOADING_COMPLETED = 'loadingCompleted';
this.LOADING_DATA_PROGRESS = 'loadingDataProgress';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The properties LOADING_ABANDONED, LOADING_COMPLETED, and LOADING_DATA_PROGRESS are defined twice in the constructor. These duplicated lines should be removed to avoid potential confusion and bugs.


// Replace
this.returnOffset = NaN;
this.returnOffset = NaN;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The property returnOffset is initialized twice. This duplicate initialization is redundant and should be removed.

...cmcdModel.updateMsdData(Constants.CMCD_REPORTING_MODE.REQUEST),
};

request.cmcd = cmcdData; //TODO: wrong because cmcdData only has data from model, not complete data with reporter

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The request.cmcd property is being assigned an incomplete set of CMCD data, as noted in the TODO comment. It's missing stateful data managed by the CmcdReporter (like sn). The CMCD_DATA_GENERATED event triggered later will therefore contain this incomplete data. To fix this, request.cmcd should be assigned the complete data object from the reporter after applyRequestReport is called, or retrieved directly from the reporter's internal state.

Comment on lines +232 to +239
const httpRequest = new CmcdReportRequest();
httpRequest.url = request.url;
httpRequest.method = request.method;
httpRequest.headers = request.headers;
httpRequest.body = request.body;
httpRequest.type = HTTPRequest.CMCD_EVENT;

urlLoader.load({

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The CMCD v2 implementation allows the MPD manifest to specify reporting targets via the ReportingTargets element. The CmcdController uses these URLs to send playback reports without any validation or allow-listing. A malicious manifest can instruct the player to send requests to arbitrary URLs, potentially leaking session information or being used to interact with internal network services from the user's browser. It is recommended to implement a URL validation mechanism or an allow-list for reporting targets.

Comment on lines 898 to 899
const url = event.messageData instanceof Uint8Array ? Utils.uint8ArrayToString(event.messageData) : event.messageData;
_sendCallbackRequest(url);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The EventController processes callback events from the manifest and makes network requests to the URLs provided in the event's message data. There is no validation of these URLs, allowing a malicious manifest to trigger requests to arbitrary destinations. It is recommended to validate callback URLs against an allow-list of trusted domains.

Comment on lines +117 to +122
const relativePath = period.ImportedMPD.uri;
const baseUrl = period.BaseURL ?? manifest.BaseURL;
const resolvedUri = baseUrl ? baseUrl[0].__text + relativePath : relativePath;

const updatedManifest = new Promise(resolve => {
manifestLoader.load(resolvedUri, null, null, true)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The ListMpdController loads imported manifests from URLs specified in the ImportedMPD element of the main manifest. These URLs are resolved and fetched without validation, which can be exploited by a malicious manifest to force the player to fetch content from arbitrary URLs. It is recommended to restrict imported MPD URLs to a set of trusted base URLs.

schemeIdUri: event.eventStream.schemeIdUri,
maxDuration: alternativeMpdNode.maxDuration / timescale,
alternativeMPD: {
url: alternativeMpdNode.url,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The AlternativeMediaController extracts alternative MPD URLs from the manifest. These URLs are later used to load content without validation. A malicious manifest could point to an arbitrary URL, causing the player to perform a forced request. It is recommended to validate these URLs before use.

Comment on lines 3757 to 3807
export interface CmcdModel {
setup(): void;

reset(): void;

setConfig(config: object): void;

getCmcdData(request: HTTPRequest): object;

getCmcdParametersFromManifest(): CMCDParameters;
onStateChange(state: any): void;

getHeaderParameters(request: HTTPRequest): object | null;
onPeriodSwitchComplete(): void;

getQueryParameter(request: HTTPRequest): { key: string, finalPayloadString: string } | null;
onPlaybackStarted(): void;

initialize(): void;
onPlaybackPlaying(): void;

isCmcdEnabled(): boolean;
onRebufferingStarted(mediaType: string): void;

reset(): void;
onRebufferingCompleted(mediaType: string): void;

setConfig(config: object): void;
onPlayerError(errorData: any): void;

onPlaybackSeeking(): void;

onPlaybackSeeked(): void;

onPlaybackRateChanged(data: any): void;

wasPlaying(): boolean;

onManifestLoaded(data: any): void;

onBufferLevelStateChanged(data: any): void;

updateMsdData(mode: string): object;

resetInitialSettings(): void;

getCmcdParametersFromManifest(): CMCDParameters;

triggerCmcdEventMode(event: string): object;

getGenericCmcdData(mediaType?: string): object;

isIncludedInRequestFilter(type: string, includeInRequests?: any): boolean;

getLastMediaTypeRequest(): string;

onEventChange(state: any): void;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The CmcdModel interface uses any for several method parameters (onStateChange, onPlayerError, onPlaybackRateChanged, onManifestLoaded, onBufferLevelStateChanged, onEventChange). Using any reduces type safety and the benefits of TypeScript. Consider defining specific types or interfaces for these parameters to improve code clarity and prevent potential runtime errors. For example, for onPlayerError, you could use a more specific error type like DashJSError.

Comment on lines +727 to +769
function _isFirstEventInSequence(event, eventsInSamePeriod, currentVideoTime) {
try {
if (!eventsInSamePeriod || !event.eventStream) {
return false;
}

const schemeIdUri = event.eventStream.schemeIdUri;
const eventsWithSameScheme = eventsInSamePeriod[schemeIdUri] || [];

// Get all events with noJump=1 from the same scheme that are not in the future
const noJump1Events = eventsWithSameScheme.filter(e =>
e.alternativeMpd &&
e.alternativeMpd.noJump === NO_JUMP_TRIGGER_ALL &&
e.calculatedPresentationTime <= currentVideoTime
);

if (noJump1Events.length === 0) {
return false;
}

// Find the event with the lowest presentation time (the first one)
// While doing so, flag all subsequent events as triggered
const firstEvent = noJump1Events.reduce((earliest, current) => {
if (current.calculatedPresentationTime < earliest.calculatedPresentationTime) {
// Current event is earlier, so flag the previous (earliest) as triggered
if (!earliest.triggeredNoJumpEvent) {
earliest.triggeredNoJumpEvent = true;
}
return current;
} else {
// Earliest event is still the first one, so flag current as triggered
if (!current.triggeredNoJumpEvent) {
current.triggeredNoJumpEvent = true;
}
return earliest;
}
});
return event.id === firstEvent.id;
} catch (e) {
logger.error(e);
return false;
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The use of reduce in _isFirstEventInSequence (and similarly in _isLastEventInSequence) to both find an item and apply side effects to other items in the array can be confusing. A more readable approach would be to separate these concerns: first, find the target event (earliest/latest), and then iterate through the array to apply side effects. This would make the function's intent clearer and improve maintainability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants