Video Playback and Analytics with Shaka
Use Shaka Player to load the platform's HLS manifest, and application listeners on its underlying <video> element to send GxP analytics. Shaka configuration controls playback; it does not automatically send window.gxp.track() events or define a “watched” business rule. This recipe supplies that measurement layer for finite, on-demand social-stream videos.
Start with GxP Analytics Plugin. The local toolkit logs/broadcasts tracking events; the installed portal owns production ingestion and reporting. This is an example to integrate into your frontend, not a new built-in platform player or a claim that frontend video analytics are already deployed.
Get the right media fields
Read the post through the installed app's authorized social-stream dependency and deployed API catalog. The reviewed SocialStreamPostResource exposes these fields through its field-scope filter:
| Field | Use |
|---|---|
id, social_stream_id | Stable post/stream identifiers for your app and reporting |
file_path_manifest_url | HLS manifest URL to pass to player.load() |
file_thumbnail_url | Optional poster image |
file_duration | Optional stored media metadata; the tracker uses the loaded media element's actual finite duration |
file_path_transcription_url | Optional transcript artifact URL |
file_url, file_medium_url, file_large_url | Other media variants; not interchangeable with an HLS manifest |
These fields can be absent due to the principal's field ceiling, or null while processing is incomplete/unavailable. Missing output does not prove a particular transcoding job failed. Re-read through the authorized post API when appropriate; do not guess a storage URL, bypass audience policy, or place a project integration key in the browser. Keep API authorization and media/CDN access separate.
The transcription job reads a JSON artifact and stores transcription metadata. Do not assume file_path_transcription_url is a WebVTT caption file or that metadata.transcription contains readable words in every serialized response. The example fetches the artifact and adapts the Google-style annotation_results → speech_transcriptions → alternatives shape to a readable transcript and, when timed words are present, a WebVTT subtitle track. The downloadable converter handles the snake_case, { seconds, nanos } format shown below; other API serializers may use camelCase or duration strings and need their own adapter. JSON cannot be attached directly to <track> or loaded as WebVTT.
The processing pipeline is asynchronous and configuration-dependent. Test one authorized uploaded video through upload, manifest readiness, transcript readiness and playback as separate stages. An upload acknowledgment or a non-null field is not proof that all variants and segments are accessible.
Define the metric before wiring events
| Question | Measurement in this recipe |
|---|---|
| Was Play clicked? | Raw gxp-track="video.play_clicked" interaction; intent only |
| Did playback begin? | video.started after a playing observation with finite duration; once per view |
| How much of the video was played? | Union of the browser's played media ranges divided by duration |
| Did the viewer watch at least 25/50/75/90%? | video.threshold once per threshold per view, using unique coverage |
| Did playback reach its end? | video.ended; seeking near the end can produce this with very little coverage |
| Did it meet the completion policy? | video.completed requires ended and at least 99% unique coverage by default |
| What was the latest observed state? | Rate-limited progress plus pause/hidden/pagehide/unmount summaries |
A view is one keyed component mount. Pause/resume, buffering recovery and native replay within that mount do not create another start or re-award thresholds. Remounting starts a new view ID. That ID identifies an observation session, not a person. If your product counts every replay as another play, explicitly start a new session on replay and change your reporting definition consistently.
Do not use currentTime / duration as watched percentage: seeking from 0 to 95% would incorrectly credit skipped content. The browser's played ranges describe media intervals that actually played. The helper merges/clamps intervals and does not count replayed segments twice. This measures media coverage, including background/muted playback; it does not prove human attention, foreground viewing, audibility or training compliance. At 2× speed, coverage advances twice as fast as wall-clock time.
The default completion policy permits a 1% total coverage gap; it is not literal 100% viewing. Set completionPercent: 100 for a strict policy, accepting that small media/range gaps may prevent completion. Thresholds compare unrounded values. Unknown, zero or infinite duration cannot produce a valid percentage; live streams, ads, changing-duration timelines and cross-device continuation require a different policy.
Copy the complete example
Download these files into the same directory in your toolkit app:
- GxpSocialVideo.vue — Shaka lifecycle, transcript display, generated captions with an on/off button, and tracked Play button.
- videoAnalytics.mjs — measurement, event delivery adapter and cleanup.
- transcriptionCaptions.mjs — timestamp parsing, phrase grouping and escaped WebVTT output.
- track-events.json — declarations to merge into your manifest, preserving unrelated/richer definitions.
For a small conversion exercise, also download example-transcription.json and its expected example-captions.vtt. The three sentences and timestamps are synthetic; they do not include a real upload path or require a media download.
These downloads are formatted source files, not minified bundles. In the documentation repository, cd website && npm run check:video-examples checks formatting and lints the JavaScript/Vue source. npm run format:video-examples applies the checked-in formatting rules. The JSON is parsed/formatted, and tests compare the VTT file with the converter’s output.
Install the Shaka package with your app's package manager and commit its lockfile. The API/import shape was checked against the platform checkout's installed Shaka 4.16.45; this is not a claim that this is the newest release or a registry compatibility guarantee. For that example version:
npm install shaka-player@4.16.45
Use HTTPS or localhost with secure-context browser APIs. Start from the toolkit scaffold; it supplies analytics in development. Mount the component only after the authorized post has been retrieved:
<script setup>
import GxpSocialVideo from './GxpSocialVideo.vue'
defineProps({ post: { type: Object, required: true } })
</script>
<template>
<GxpSocialVideo
:key="post.id + ':' + post.file_path_manifest_url + ':' + (post.file_path_transcription_url || '')"
:post="post"
/>
</template>
Changing the post, manifest, transcript URL or requested caption language requires a remount; the child intentionally does not race multiple loads in a watcher. A refreshed signed URL or a newly available transcript URL also remounts this example and creates another view. If you supply a reactive captionLanguage prop, include it in the key as well. Do not treat view count as unique people. If media can be replaced under one post ID, add a stable media revision from your application contract to event identity/report grouping; do not use the signed URL as that revision or send it to analytics.
Shaka lifecycle
The component follows Shaka's basic initialization: lazy import after mount, polyfills/support check, player attachment, error handling and manifest loading. It uses native video controls; it does not require the Shaka UI overlay or its styles. It handles unmount during asynchronous import/attach/load, destroys its player, aborts transcript fetch, removes its own listeners and revokes the generated caption Blob URL after player destruction settles.
Use player.configure() for settings such as audio language before load() when required by that setting. Prefer measured defaults over copying a large configuration block. Shaka buffering/error events and getStats() are useful for playback-quality diagnosis; they are separate from a watched-coverage or unique-person definition. Newer player quartile events based on playhead position are not a substitute for this recipe's unique-range policy.
The downloaded component calls:
const analytics = createVideoAnalytics(videoElement, {
postId: post.id,
viewId: crypto.randomUUID(),
thresholds: [25, 50, 75, 90],
completionPercent: 99,
send(name, properties) {
if (typeof window.gxp?.track !== 'function') return false
window.gxp.track(name, properties)
return true // local call only, not a durable storage receipt
},
})
Here createVideoAnalytics, videoElement and post come from your app/example. Call analytics.dispose() before detaching/replacing the media source; it emits a final best-effort summary and removes only its own listeners. The tracker retries locally unsent milestones when a later media event observes an available tracker, but it has no persistent queue or server receipt. If the plugin never becomes available, the page is killed or the network drops, events can be lost.
Click intent versus playback
Use a raw attribute on a custom play control to measure its click intent:
<button type="button" gxp-track="video.play_clicked"
:gxp-track-props="JSON.stringify({ post_id: post.id, view_id: viewId })"
@click="play">Play video</button>
post, viewId and play are provided by the downloaded Vue component. Do not place gxp-track="video.started" on the whole <video>: a click can pause, seek or open controls. Keyboard/native controls and autoplay also bypass your custom button. The helper sends custom playback events through window.gxp.track() in response to media behavior, so both tracking styles have distinct meanings.
The play promise can reject because autoplay/user-gesture/browser policy blocks it. The example shows a recoverable message; it does not award a start merely because play() was requested. Repeated Shaka/media errors with the same code are coalesced per view. Only a short error code goes into telemetry, never the full error object or signed URL.
Event schema and manifest
The downloadable track-events.json includes video.play_clicked, video.started, video.progress, video.threshold, video.ended, video.completed, video.summary and video.error. Merge its track-events object into app-manifest.json. These are application-chosen names, not reserved or automatically provisioned platform metrics. Extraction does not discover names hidden inside a helper's dynamic send() callback reliably; inspect/add the declarations explicitly.
Playback events carry:
| Property | Meaning |
|---|---|
schema_version, measurement_policy | Version the event/coverage interpretation |
post_id, view_id | Resource and observation session; not attendee identity |
event_id, sequence | Best-effort client ordering/deduplication keys within a view |
position_seconds, duration_seconds | Observed timeline position and finite duration |
unique_watched_seconds, watched_percent | Unique covered content, rounded for output |
playback_rate, ended, completion_percent | Context and configured completion policy |
threshold_percent | Present on a threshold event |
reason | Summary reason: pause, hidden, pagehide, ended or unmount |
error_code | Short code on an error event |
The declarations use the manifest's free-form "string" property descriptor, matching extraction defaults; this is metadata, not coercion or numeric validation. Payload numbers remain numbers. Interaction clicks instead include element metadata and the two supplied IDs. Never attach transcript contents, attendee email, names, signed URLs, API keys or full error/request objects. The host determines the authorized principal/project context; do not forge identity by supplying an attendee_id property.
Progress is sampled on timeupdate at most once per ten seconds, not on every frame. Thresholds still sample independently. Pause, hidden, pagehide, ended and unmount can all emit summaries; these are successive snapshots, not separate view completions. Browser timers and lifecycle events are best effort, particularly on mobile. No unload-only strategy guarantees final delivery.
Turn events into reports
Filter by project, event name, post/media revision, policy version and time window before aggregating. Use authorized Activity, Journeys and Report Queries to verify recorded events and the available report capabilities. This recipe does not add a prebuilt video dashboard or promise that every formula below is exposed by an existing UI; an authorized reporting query/export or backend aggregation may be needed.
| Report | Calculation after deduplication |
|---|---|
| Started views / play count | Distinct view_id with video.started |
| Unique viewers | Distinct stable server-attributed actors with a start; anonymous/session IDs are not verified people |
| Watched at least 90% | Distinct views with video.threshold and threshold_percent = 90; use distinct authorized actors for a people count |
| Completed views | Distinct views with video.completed, grouped by the recorded completion policy |
| Completion rate | Completed started views / all started views, using the same filters and denominator |
| Average coverage | Maximum observed coverage per started view, then average those values; do not sum progress snapshots |
Deduplicate event_id if the chosen storage/report path supports it; the GxP tracking API is not claimed to enforce it automatically. Late/out-of-order snapshots should not reduce a view's maximum coverage. Do not combine different durations/media revisions under a post ID or mix 99% and 100% completion policies. Grouping unique viewers depends on real authenticated/authorized actor attribution; one browser-generated view_id per mount cannot answer “how many people” by itself.
This example does not send the complete interval set, so summaries from separate views cannot reconstruct the union of watched ranges across devices or sessions. A learner who watches the first half in one session and the second half later needs a separate authenticated progress service if you want cross-session completion. Client analytics remain forgeable and lossy; do not award compliance certificates or access rights solely from these events.
Convert a transcription into captions
The example artifact contains three sentences: “Welcome to the developer hub.”, “This video explains how captions work.” and “You can turn them off at any time.” Each sentence is a speech_transcriptions entry with a first alternatives item containing transcript and timed words. The helper uses the words for captions and the transcript string for the readable paragraph; it does not attempt to redistribute corrected paragraph text over old word timestamps.
Convert seconds and nanos
A word has start_time and end_time objects. Calculate each offset as:
const seconds = (time.seconds ?? 0) + (time.nanos ?? 0) / 1_000_000_000
For numeric fields, { "seconds": 1, "nanos": 400000000 } means 1.4 seconds, { "seconds": 2 } means 2 seconds, and {} means zero. The downloaded durationSeconds() also accepts integer-string fields and validates them; a missing timestamp object, invalid number, negative offset or out-of-range nanos is rejected. It does not treat an entirely missing timestamp as zero.
Google’s WordInfo contract places word offsets relative to the source audio. Do not add segment.start_time_offset again. For an edited/trimmed/re-timed rendition, verify alignment and apply an explicit timeline mapping outside this helper.
Run the conversion
From the directory containing the downloaded helper and JSON, run:
node --input-type=module <<'JS'
import { readFile, writeFile } from 'node:fs/promises'
import { transcriptionToCaptions } from './transcriptionCaptions.mjs'
const artifact = JSON.parse(await readFile('./example-transcription.json', 'utf8'))
const captions = transcriptionToCaptions(artifact)
await writeFile('./generated-captions.vtt', captions.webvtt)
console.log(`${captions.cues.length} cues; ${captions.skippedWords} invalid words skipped`)
JS
The result matches the downloadable VTT:
WEBVTT
1
00:00:00.000 --> 00:00:02.300
Welcome to the developer hub.
2
00:00:03.400 --> 00:00:06.000
This video explains how captions work.
3
00:00:07.000 --> 00:00:09.100
You can turn them off at any time.
transcriptionToCaptions() returns { language, text, cues, webvtt, skippedWords }. Its policy is intentionally small and explicit:
- Select one annotation (
annotationIndex: 0by default), rather than accidentally combining different input videos. Select the first speech block’s language by default, or pass an exact language tag such as{ language: 'en-us' }. Missing language codes are treated asund; unmatched languages produce no cues. Only the first recognition alternative is used, not every hypothesis. - Sort valid words by start time. Break phrases at sentence punctuation, pauses longer than 0.8 seconds, or before adding a word that would exceed 72 characters or five seconds. Override
maxChars,maxCueSecondsandmaxGapSecondsfor your content. These are grouping limits, not strict limits on an indivisible long word or word duration, nor an editorial line-wrapping/accessibility standard. - Keep zero-duration words inside their phrase. If an entire cue has zero duration after millisecond rounding, display it for up to 250 milliseconds, stopping at the next later cue when necessary. This is an example display policy, not an invented speech measurement. Overlapping source speech can still overlap; review timing before publishing captions.
- Skip malformed/reversed word timings and report their count. Preserve the separately supplied readable transcript. Without timed words, show the transcript without inventing synchronized cues.
- Collapse whitespace and escape
&,<and>for WebVTT cue text. Do not treat transcript text as HTML or copy raw transcript content into analytics events.
Add the generated track to Shaka
After both the transcript conversion and await player.load(manifestUrl) complete, the component uses Shaka’s external text-track API:
const captionUrl = URL.createObjectURL(
new Blob([captions.webvtt], { type: 'text/vtt' }),
)
const track = await player.addTextTrackAsync(
captionUrl, captions.language, 'subtitles', 'text/vtt', '', 'Auto-generated transcript',
)
player.selectTextTrack(track)
player.setTextTrackVisibility(true)
Here captions is the converter result and player is the already-loaded Shaka instance. This fragment shows attachment; use the complete Vue example for error handling and cleanup. Shaka does not automatically select an added track. The component initially shows this generated track and provides a Captions toggle with aria-pressed, synchronized with Shaka’s text-visibility event. Set caption-language="en-us" when you want that exact source language; the helper does not translate.
The example supports finite on-demand video. It waits for both inputs in either completion order, prevents attachment after unmount, and keeps caption/transcript errors separate from playback errors. The generated Blob URL remains valid until player.destroy() settles, including an unmount during text-track loading; revoking it immediately after attachment can break later text loading. Your application’s CSP must permit the generated Blob URL where its media/text loader uses it; verify this in the target browser rather than weakening unrelated policies.
Automatic speech recognition can contain errors. This conversion preserves its wording and does not generate speaker labels or non-speech sound descriptions; it is a subtitle example, not a complete accessibility captioning workflow. Review the text, reading speed and synchronization against the actual media before publication.
Manifest, segment and transcript access
A playable HLS experience needs access to the master playlist, variant playlists, segments and any keys/text tracks. CORS, HTTPS/mixed content, signed-URL expiry and browser codec support must work for every requested asset, not only the initial .m3u8.
The dashboard's current player copies a manifest query onto child requests lacking one. That code is not a universal frontend authorization contract. Query parameters are not automatically inherited by relative segment URLs. Obtain the approved signing/CDN contract; prefer correctly signed child URLs or a properly configured cookie/proxy policy. If a Shaka request filter is required, restrict propagation to approved origins, paths and parameter names, and never forward a privileged API bearer to arbitrary playlist/key/license destinations. This example intentionally does not copy query secrets broadly. Expired assets should trigger an authorized URL refresh/reload path, not a guessed storage URL.
The transcript fetch uses the returned artifact URL, checks HTTP status, parses JSON and renders text through Vue escaping. It is independent of video loading and is aborted on unmount. A readable transcript without valid timed words cannot produce synchronized captions, and a transcript failure does not prove video playback failed. Configure credentials/CORS only according to the artifact-serving contract. DRM, ad insertion and authenticated custom networking require additional integration; this sample is not a DRM/license example.
Verify before release
- Run the toolkit preview with a synthetic post and authorized media. Observe
gxp:trackand inspect names/IDs/properties without sending production analytics. - Test native controls, custom Play, pause/resume, buffering, playback-rate changes, replay, mid-video seeks and seeking directly to the end. Confirm threshold/completion counts follow the declared policy.
- Test unknown duration, missing manifest, denied/expired segment, invalid transcript JSON, missing/invalid word timings, missing analytics plugin, and unmount during media or caption loading. Confirm no stale update/listener or unhandled promise rejection.
- On supported target browsers/devices, verify real HLS decoding, CORS/signing, caption synchronization, on/off controls, transcript access, Blob/CSP behavior and cleanup. A mocked player cannot certify codecs, media delivery or attention.
- After an authorized deployment, verify ingestion, actor attribution, reporting permissions, deduplication and formulas against a controlled set of views. Local console output is not a saved event receipt.
The included helper has automated cases for interval merging, replay/seek exclusion, finite duration, exact thresholds, once-per-view start/completion, strict completion policy, throttling, missing tracker, lifecycle cleanup and error privacy. The Vue component also needs target-media/browser acceptance. See Project Acceptance for the boundary between a working example and an accepted deployed experience.
Reviewed implementation
Platform checkpoint e62b2015c5ce5fdbde07382a2a5a156324c915de: SocialStreamPostResource, its portal field-filter trait, VideoTranscriptionResponseJob and the dashboard Components/Mod/FormFields/VideoPlayer.vue. These support the field/transcript/dashboard observations, not a claim that every upload is transcoded/transcribed successfully. Shaka’s linked public documentation supports initialization/configuration; the recipe’s coverage and reporting policy is application-owned.