Skip to content

Instantly share code, notes, and snippets.

@GiriAakula
Created November 19, 2025 05:03
Show Gist options
  • Select an option

  • Save GiriAakula/36be403fdb6c30af7248ccb77aa77eb2 to your computer and use it in GitHub Desktop.

Select an option

Save GiriAakula/36be403fdb6c30af7248ccb77aa77eb2 to your computer and use it in GitHub Desktop.

SGAI (Server-Guided Ad Insertion) Technical Documentation

This document provides a technical overview of the Server-Guided Ad Insertion (SGAI) feature as implemented in the proof-of-concept index.html file. It is intended for developers and engineers who need to understand, maintain, or extend this functionality.

1. Introduction

The SGAI feature enables the insertion of advertisements into a Video on Demand (VOD) stream in a manner guided by the server. This implementation leverages AWS MediaTailor to dynamically insert ads into an HLS stream, with the client-side player handling the ad playback, tracking, and content resumption.

The primary goal is to provide a seamless ad experience for the user, where ads are played at specific points in the content timeline as dictated by the HLS manifest.

Technology Stack

  • Video Player: Video.js is used as the base HTML5 video player.
  • Ad Insertion Service: AWS Elemental MediaTailor provides the server-side ad insertion capabilities.
  • HLS Manifest Parsing: A custom m3u8-parser.js library is used to parse the HLS manifest and extract ad-related metadata.

2. Architecture

The architecture involves three main components:

  1. Client-Side Player (Browser): The user's web browser, which runs the Video.js player and the custom SGAI logic.
  2. AWS MediaTailor: A server-side service that stitches ad content into the main video stream. It provides a master HLS manifest (.m3u8) that contains markers for ad breaks.
  3. Ad Server (VAST): A standard VAST server that provides the ad creatives and tracking information.

Interaction Diagram

+-------------------+      +-------------------+      +----------------+
| Client-Side       |      | AWS MediaTailor   |      | Ad Server      |
| (Video.js, SGAI)  |      |                   |      | (VAST)         |
+-------------------+      +-------------------+      +----------------+
        |                          |                         |
        | 1. Fetch Master Manifest |                         |
        |------------------------->|                         |
        |                          |                         |
        | 2. Return Manifest with  |                         |
        |    Ad Markers (EXT-X-DATERANGE) |                    |
        |<-------------------------|                         |
        |                          |                         |
        | 3. Parse Manifest,       |                         |
        |    Identify Ad Breaks    |                         |
        |                          |                         |
        | 4. At Ad Break Time,     |                         |
        |    Fetch Ad Asset URL    |                         |
        |------------------------->|                         |
        |                          |                         |
        |                          | 5. Request Ad from      |
        |                          |    Ad Server            |
        |                          |------------------------>|
        |                          |                         |
        |                          | 6. Return Ad Creative   |
        |                          |<------------------------|
        |                          |                         |
        | 7. Return Ad Asset      |                         |
        |    (Media + Tracking)    |                         |
        |<-------------------------|                         |
        |                          |                         |
        | 8. Play Ad & Send        |                         |
        |    Tracking Beacons      |------------------------>|
        |                          |                         |
        | 9. After Ad, Resume      |                         |
        |    Main Content          |                         |
        |                          |                         |

3. Workflow

The entire process, from loading the player to resuming content after an ad, follows these steps:

  1. Initialization:

    • The main HLS manifest from AWS MediaTailor is fetched.
    • The manifest is parsed to extract the awsSessionData, which is required for subsequent ad-related requests.
  2. Ad Break Detection:

    • The client continuously monitors the loaded HLS playlist for EXT-X-DATERANGE tags. These tags, provided by MediaTailor, mark the ad breaks in the timeline.
    • The startTime and endTime of each ad break are recorded.
  3. Ad Triggering:

    • The player's current time is monitored.
    • When the player's time matches the startTime of a scheduled ad break, the main content playback is paused, and the ad playback process is initiated.
  4. Ad Playback:

    • An ad asset URL is constructed using data from the EXT-X-DATERANGE tag and the awsSessionData.
    • A request is made to this URL, which returns a JSON object containing the ad's media stream URL and its VAST tracking events.
    • The Video.js player's source is switched to the ad's media stream, and playback begins.
  5. Ad Tracking:

    • During ad playback, VAST tracking events (e.g., impression, start, firstQuartile, midpoint, thirdQuartile, complete, pause, mute) are fired by making GET requests to the beacon URLs provided in the ad asset response.
  6. Content Resumption:

    • An event listener is attached to the player's ended event.
    • When the ad video finishes playing, the player's source is switched back to the original content HLS stream.
    • The player's current time is set to the endTime of the ad break, ensuring that the main content resumes from where it left off.

4. Code Implementation Details

The core logic is contained within the <script> tag in vod-player/html/sgai/index.html.

Key Variables

  • player: The Video.js player instance.
  • awsSessionData: Stores the session data from the master manifest, used to fetch ad assets.
  • isAdPlaying: A boolean flag to indicate if an ad is currently active.
  • resumeTime: Stores the timestamp at which the main content should resume after an ad break.

Core Functions

  • giri():

    • The entry point of the SGAI logic.
    • Fetches and parses the initial HLS manifest to get awsSessionData.
    • Sets up an interval to start the ad detection process.
  • parse(manifestText):

    • Uses m3u8-parser.js to parse the manifest text.
    • Extracts and stores the awsSessionData from the parsed manifest.
  • getsegments():

    • Waits for the Video.js player and its HLS tech (vhs) to be ready.
    • Retrieves the dateRanges array, which contains the ad break information, from the HLS playlist.
    • Calls handleSegments() to process the ad breaks.
  • handleSegments(media):

    • Takes the array of ad breaks (media).
    • Sets up an interval that checks every second if the player's currentTime matches the startTime of an ad break.
    • When a match is found, it calls playAd() and stores the ad break's endTime.
    • Sets up the ended event listener on the player to handle content resumption.
  • playAd(element):

    • Sets isAdPlaying to true.
    • Constructs the ad asset URL from the ad break data.
    • Fetches the ad asset JSON.
    • Calls handleRespose() to process the ad data.
  • handleRespose(res):

    • Extracts the ad media URL and tracking events from the response.
    • Calls handleTrackingEvents() to set up VAST tracking.
    • Changes the player source to the ad media URL and starts playback.
  • handleTrackingEvents(events, mainDuration):

    • Sets up functions (start, impression, pause, resume, etc.) that fire tracking beacons for each VAST event.
    • The monitorDuration function is created to track ad playback progress and fire quartile events (firstQuartile, midpoint, thirdQuartile, complete) at the appropriate time.
  • getPlayerObject():

    • Initializes the player variable with the Video.js instance.
    • Attaches player event listeners (timeupdate, play, pause, volumechange, etc.) that call the corresponding tracking functions set up by handleTrackingEvents when an ad is playing.

5. Dependencies

  • video.min.js: The Video.js library.
  • video-js.css: The default stylesheet for the Video.js player.
  • m3u8-parser.js: A JavaScript library for parsing HLS .m3u8 manifests. This is crucial for reading the EXT-X-DATERANGE tags that define the ad breaks.

6. Configuration

To use this SGAI implementation, the primary configuration is setting the src attribute of the <source> element inside the <video> tag to a valid AWS MediaTailor HLS manifest URL.

Example:

<video id="my-video" class="video-js" ...>
    <source
        src="https://.../master.m3u8?aws.insertionMode=GUIDED"
        type="application/x-mpegURL" />
    ...
</video>

The aws.insertionMode=GUIDED query parameter is essential, as it instructs MediaTailor to provide the ad break information in the manifest for the client to handle.

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