Skip to content

gwp api reference

Andre Lafleur edited this page Apr 30, 2026 · 7 revisions

GWP API reference

This document provides practical examples and explanations for the Genetec Web Player (GWP) API. For conceptual information and getting started guides, see the Genetec Web Player developer guide.

To check the GWP version bundled with your Media Gateway, call gwp.version() at runtime.

Use the gwp.js and gwp.d.ts files from the same Media Gateway that your application connects to.

TypeScript definitions

For full type definitions, IDE autocomplete, and IntelliSense support, download the TypeScript definitions file directly from your Media Gateway:

https://<MediaGatewayAddress>/media/v2/files/gwp.d.ts

For TypeScript/JavaScript projects:

// Reference the type definitions from your Media Gateway
/// <reference path="https://<MediaGatewayAddress>/media/v2/files/gwp.d.ts" />

// Or download and include locally
import type { IWebPlayer, IPtzControl } from './gwp.d.ts';

Important

Always use the gwp.d.ts file from your Media Gateway to keep type definitions aligned with the gwp.js file served by that Media Gateway.

The TypeScript file contains:

  • Complete interface definitions
  • All method signatures with parameter types
  • Inline documentation comments
  • Enum definitions

This API reference complements the TypeScript definitions by providing:

  • Practical code examples for common scenarios
  • Explanations of when and why to use specific methods
  • Usage notes for methods and events
  • Compatibility notes and warnings

Table of contents

gwp module

The global GWP module provides factory methods for creating players and services.

gwp.buildPlayer()

Creates a new web player instance.

Signature:

buildPlayer(container: HTMLDivElement): IWebPlayer

Parameters:

  • container - Empty HTML div element where the player will be embedded

Returns: IWebPlayer instance

Example:

const divContainer = document.getElementById('playerContainer');
const webPlayer = gwp.buildPlayer(divContainer);

gwp.buildMediaGatewayService()

Creates a Media Gateway service for multiplexing multiple players over a single WebSocket connection.

Signature:

buildMediaGatewayService(
    url: string,
    tokenRetriever: TokenRetrieverFct
): Promise<IMediaGatewayService>

Parameters:

  • url - Media Gateway endpoint URL (e.g., https://gateway.example.com/media)
  • tokenRetriever - Function that retrieves tokens for cameras

Returns: Promise resolving to IMediaGatewayService

gwp.enableLogs()

Enables GWP console logging for debugging.

Signature:

enableLogs(intense?: boolean): string

Parameters:

  • intense (optional) - Enable verbose/debug level logging. Default: false

Returns: Confirmation string

Example:

gwp.enableLogs();        // Standard logging
gwp.enableLogs(true);    // Verbose logging

gwp.disableLogs()

Disables GWP console logging (warnings and errors still shown).

Signature:

disableLogs(): string

Returns: Confirmation string

gwp.version()

Returns the GWP library version number.

Signature:

version(): string

Returns: Version string (for example, "1.12.125")

Example:

console.log('GWP Version:', gwp.version());

IWebPlayer interface

The main interface for controlling a video player instance.

IWebPlayer methods

start()

Initializes connection to a Media Gateway for a specific camera.

Signature:

start(
    camera: string,
    mediaGatewayEndpoint: string,
    tokenRetriever: TokenRetrieverFct,
    serverVersion?: string,
    throttlePtzCommands?: boolean
): Promise<void>

Parameters:

  • camera - Camera GUID in 8-4-4-4-12 format
  • mediaGatewayEndpoint - Media Gateway URL
  • tokenRetriever - Function returning authentication token
  • serverVersion (optional) - Security Center version
  • throttlePtzCommands (optional) - Whether to throttle PTZ commands. Ignored for cameras that do not support PTZ commands.

Returns: Promise that resolves when connection is established

Throws: Error if connection fails

Example:

await webPlayer.start(
    '00000001-0000-babe-0000-080023e940c6',
    'https://gateway.example.com/media',
    getTokenFct
);

startWithService()

Starts the player using an existing Media Gateway service (for multiplexing).

Signature:

startWithService(
    camera: string,
    mediaGatewayService: IMediaGatewayService,
    serverVersion?: string,
    throttlePtzCommands?: boolean
): Promise<void>

Parameters:

  • camera - Camera GUID
  • mediaGatewayService - Existing Media Gateway service instance
  • serverVersion (optional) - Security Center version
  • throttlePtzCommands (optional) - Whether to throttle PTZ commands. Ignored for cameras that do not support PTZ commands.

Returns: Promise that resolves when connection is established

stop()

Stops the current stream and disconnects from the Media Gateway.

Signature:

stop(): void

Notes:

  • Player can be restarted with a different camera using start()
  • Player resources are retained for reuse

dispose()

Stops and completely releases the player, removing it from the DOM.

Signature:

dispose(): void

Notes:

  • Player instance becomes unusable after disposal
  • Unregister all event handlers before disposing
  • DOM container is cleared

playLive()

Switches to live streaming mode.

Signature:

playLive(): void

Notes:

  • No effect if already playing live
  • Play speed is always 1x in live mode
  • PTZ controls are available in live mode

seek()

Seeks to a specific time in playback mode.

Signature:

seek(seekTime: Date): void

Parameters:

  • seekTime - Target playback time

Notes:

  • Switches to playback mode if in live
  • If no recording exists at seek time, plays nearest available recording
  • Play speed and pause state are preserved

pause()

Pauses the player.

Signature:

pause(): void

Notes:

  • In live mode: switches to playback at current time
  • Use playLive() to return to live, not resume()

resume()

Resumes playback from paused state.

Signature:

resume(): void

Notes:

  • Resumes at the last played frame
  • Uses the last set play speed

setPlaySpeed()

Sets the playback speed.

Signature:

setPlaySpeed(playSpeed: number): void

Parameters:

  • playSpeed - Speed value. Valid ranges:
    • Forward: 0.01 to 100
    • Reverse: -100 to -0.01

Notes:

  • Only works in playback mode
  • Reverse playback uses keyframes only (recommend -6x minimum)
  • High speeds (>6x) use keyframes only

Example:

webPlayer.setPlaySpeed(2);    // 2x forward
webPlayer.setPlaySpeed(-6);   // 6x reverse
webPlayer.setPlaySpeed(0.5);  // Half speed

setAudioEnabled()

Enables or disables audio playback.

Signature:

setAudioEnabled(isAudioEnabled: boolean): void

Parameters:

  • isAudioEnabled - true to enable, false to disable

Notes:

  • Only works if audio is available
  • Should be called in response to user action (browser requirement)

setPtzMode()

Enables or disables PTZ low-latency mode.

Signature:

setPtzMode(ptzMode: boolean): void

Parameters:

  • ptzMode - true to enable, false to disable

Notes:

  • Reduces latency at the expense of stream quality
  • May trigger transcoding
  • Disable when PTZ control is not needed

togglePrivacy()

Toggles privacy protection on/off.

Signature:

togglePrivacy(): void

Notes:

  • Availability depends on camera configuration and user privileges

showDebugOverlay()

Shows or hides the diagnostic overlay.

Signature:

showDebugOverlay(show: boolean): void

Parameters:

  • show - true to show, false to hide

Alternative: Use Ctrl+Shift+A keyboard shortcut

getSnapshot()

Captures a snapshot of the currently displayed frame.

Signature:

getSnapshot(): ImageData | null

Returns: ImageData object or null if no frame available

Notes:

  • Includes video watermarking
  • Does not include digital zoom or dewarping

getPlayerStats()

Gets a snapshot of the current player diagnostic statistics.

Signature:

getPlayerStats(): Promise<IPlayerStats>

Returns: Promise resolving to IPlayerStats

IWebPlayer properties

All properties are read-only.

Property Type Description
isStarted boolean Whether the player is started and ready
ptzControl IPtzControl PTZ control interface
digitalZoomControl IDigitalZoomControl | null Digital zoom interface (null if not supported)
dewarperControl IDewarperControl | null Dewarping interface (null if not available)
timelineProvider ITimelineProvider Timeline API interface
isLive boolean Whether playing in live mode
isPaused boolean Whether the player is paused
playSpeed number Current play speed
lastFrameTime Date Timestamp of the last rendered frame
isAudioAvailable boolean Whether audio is available
isAudioEnabled boolean Whether audio is currently enabled
isPrivacyProtected boolean Whether privacy protection is active

IWebPlayer events

All events use the ILiteEvent<T> interface for registration:

interface ILiteEvent<T> {
    register(handler: (data: T) => void): void;
    unregister(handler: (data: T) => void): void;
}

onErrorStateRaised

Fired when a fatal error occurs.

Event data: ErrorStatusEvent

{
    errorCode: ErrorCode,    // Error code number
    value: string,           // Error description
    isFatal: boolean         // Whether error stops the player
}

Example:

webPlayer.onErrorStateRaised.register((error) => {
    console.error(`Error ${error.errorCode}: ${error.value}`);
    if (error.isFatal) {
        // Handle fatal error
    }
});

onFrameRendered

Fired periodically when frames are rendered (throttled to ~250ms).

Event data: Date - Frame timestamp

onStreamStatusChanged

Fired when the streaming connection status changes.

Event data: StreamingConnectionStatusChangeEvent

{
    state: StreamingConnectionStatus,  // Status code
    value: string                       // Status description
}

onPlayerStateChanged

Fired when the player state changes.

Event data: PlayerStateChangeEvent

{
    playerState: PlayerState,  // State code
    value: string              // State description
}

onPlaySpeedChanged

Fired when play speed changes.

Event data: PlaySpeedChangeEvent

{
    playSpeed: number  // New play speed
}

onAudioStateChanged

Fired when audio playback state changes.

Event data: AudioStateChangeEvent

{
    isAudioEnabled: boolean  // Whether audio is enabled
}

onAudioAvailabilityChanged

Fired when audio availability changes.

Event data: AudioAvailabilityChangeEvent

{
    isAudioAvailable: boolean  // Whether audio is available
}

onPlayerModeChanged

Fired when switching between live and playback modes.

Event data: PlayerModeChangeEvent

{
    playerMode: PlayerMode  // 'unknown', 'live', or 'playback'
}

onBufferingProgress

Fired during playback buffering.

Event data: number - Buffering progress (0-100%)

onPrivacyProtectionChanged

Fired when privacy protection state changes.

Event data: void

IPtzControl interface

Interface for controlling PTZ cameras.

Methods

Method Parameters Description
startPanTilt() panSpeed: number, tiltSpeed: number Start pan/tilt movement (signed integer speeds in the -100 to 100 range)
stopPanTilt() - Stop pan/tilt movement
startZoom() zoomSpeed: number Start zoom movement (signed integer speed in the -100 to 100 range)
stopZoom() - Stop zoom movement
goToPreset() preset: number Move to preset position
goHome() - Move to home position
runPattern() pattern: number Run pattern by ID
stop() - Stop all PTZ movement
lock() - Lock PTZ controls
unlock() - Unlock PTZ controls
startFocus() distance: PtzFocusDistance, speed: number Adjust focus
stopFocus() - Stop focus adjustment
startIris() operation: PtzIrisOperation, speed: number Adjust iris
stopIris() - Stop iris adjustment
goToImagePosition() x: number, y: number, zoom: number Move to an image position using relative coordinates

Example

const ptz = webPlayer.ptzControl;

// Pan and tilt
ptz.startPanTilt(50, 30);  // Pan right and tilt up
setTimeout(() => ptz.stopPanTilt(), 3000);

// Zoom
ptz.startZoom(80);  // Zoom in at 80% speed
setTimeout(() => ptz.stopZoom(), 2000);

// Presets
ptz.goToPreset(1);  // Go to preset #1
ptz.goHome();       // Return to home position

// Patterns
ptz.runPattern(1);  // Run pattern #1
ptz.stop();         // Stop all movement

IDigitalZoomControl interface

Interface for digital zoom functionality.

Properties

Property Type Description
Zoom number Current zoom factor (1-20)
X number X-coordinate of view center (normalized 0-1)
Y number Y-coordinate of view center (normalized 0-1)
Preview IDigitalZoomPreview Preview canvas interface

IDigitalZoomPreview exposes:

Property Type Description
Enabled boolean Whether the digital zoom preview is displayed when zoomed
Canvas HTMLCanvasElement Canvas used for the preview

Events

Event Data Type Description
onPositionChanged void Fired when zoom position changes

Methods

Method Parameters Description
goTo() x: number, y: number, zoomFactor: number Go to specific position and zoom
zoom() zoomFactor: number Zoom to factor (1-20)
move() x: number, y: number Move view (relative -1 to 1)
zoomWithFocus() x: number, y: number, zoomFactor: number Zoom while keeping point fixed
stop() - Reset to full image (1x zoom)
snapshot() - Returns ImageData | null of zoomed view

IDewarperControl interface

Interface for fisheye dewarping.

Properties

Property Type Description
isDewarping boolean Whether currently dewarping
PanDegrees number Pan angle in degrees
TiltDegrees number Tilt angle in degrees
X number X-coordinate (normalized -1 to 1)
Y number Y-coordinate (normalized -1 to 1)
ZoomFactor number Current zoom factor (1-20)
Preview IDewarperPreview Preview canvas interface

IDewarperPreview exposes:

Property Type Description
Enabled boolean Whether the dewarping preview control is displayed
Canvas HTMLCanvasElement Canvas used for the preview

Methods

Method Parameters Description
gotoPanTilt() panDegrees: number, tiltDegrees: number Navigate by pan/tilt degrees
gotoXY() x: number, y: number Navigate by X/Y coordinates
gotoZoom() zoomFactor: number Set zoom factor (1-20)
stopDewarping() - Return to original warped image

ITimelineProvider interface

Interface for accessing timeline events (bookmarks, sequences).

Methods

setTimelineRange()

Sets the range of interest for timeline events.

Signature:

setTimelineRange(startTime: Date, endTime: Date): void

Parameters:

  • startTime - Start of range
  • endTime - End of range (can be in the future)

Notes:

  • Range cannot exceed 72 hours
  • Recommended maximum: 24 hours
  • If end time is in future, periodic live updates will be received

Events

onTimelineContentUpdated

Fired when timeline content changes.

Event data: TimelineContentEvent

{
    coverageStart: Date,           // Start of updated coverage
    coverageEnd: Date,             // End of updated coverage
    events: TimelineEvent[]        // Array of timeline events
}

TimelineEvent Structure:

{
    time: Date,                    // Event time
    duration?: number,             // Duration in seconds (if applicable)
    details?: string,              // Event details (optional)
    kind: TimelineEventKind        // 0 = RecordingSequence, 1 = Bookmark
}

Example:

webPlayer.timelineProvider.setTimelineRange(
    new Date('2024-01-01T00:00:00Z'),
    new Date('2024-01-02T00:00:00Z')
);

webPlayer.timelineProvider.onTimelineContentUpdated.register((event) => {
    console.log(`Coverage: ${event.coverageStart} to ${event.coverageEnd}`);
    event.events.forEach(e => {
        if (e.kind === 1) {
            console.log(`Bookmark at ${e.time}: ${e.details}`);
        } else {
            console.log(`Recording: ${e.time}, duration: ${e.duration}s`);
        }
    });
});

IMediaGatewayService interface

Represents a connection to a Media Gateway server for multiplexing multiple players.

Note

This is an advanced feature. Most applications should use webPlayer.start() directly.

IMediaGatewayService does not expose public methods. Pass the service instance to webPlayer.startWithService() to start players on the shared Media Gateway connection.

Enumerations

ErrorCode

Error codes for fatal errors.

Code Value Description
Unknown 0 Unknown error
ConnectionLost 2 Connection lost
InsufficientDiskSpace 3 Server disk space issues
ConnectionFailed 4 Connection failed
StreamNotFound 6 Stream not found
RequestTimedOut 9 Request timed out
UnitPlaybackUnavailable 11 Video unit can't do playback
LiveCapacityExceeded 12 Live stream limit reached
PlaybackCapacityExceeded 13 Playback stream limit reached
UnsupportedEncoding 14 Unsupported codec
DatabaseUpgradeRequired 15 Media Router needs upgrade
InsufficientPrivilege 16 User lacks privileges
InsufficientCapability 17 Video unit can't process command
MissingCertificate 18 Can't decrypt encrypted stream
NotSupported 20 Command not supported
CantUsePrivateKey 21 Certificate missing private key
Mp4CodecNotSupported 22 Reserved value not used by GWP
DeniedByServer 23 Server rejected request
NoTranscodingAllowed 24 Transcoding prevented
ForbiddenTransformation 32 Transformation requires transcoding
CloudPlaybackFailure 33 Can't play from cloud
UnsupportedOmnicastFederationRole 34 Federation role not supported
UpdateSessionError 1000 Invalid stream state
DeviceOffline 10000 Device is offline
ConnectionError 10001 Signaling error
HlsPlaybackError 10002 HLS playback error
NoVideoRecording 10003 No video recording is available for HLS playback at the requested time
OperationCanceled 10004 Live or playback request was interrupted before it could start
TooManyClients 10005 Device reached the maximum number of concurrent live streams
WebRtcStreamingDenied 10006 WebRTC streaming is not allowed for this tenant

PlayerState

Player operational states.

State Value Description
Stopped 0 Not ready to accept commands
Buffering 1 Buffering data
Playing 2 Actively playing
Starting 3 Starting up
Paused 4 Paused and ready to resume
Stopping 5 Stopping
Rewinding 6 Playing in reverse
BeginReached 7 No more content (reverse)
EndReached 8 No more content (forward)
WaitingForArchiverData 9 Waiting for archiver
NoVideoSequenceAvailable 10 No video recorded
AwaitingSynchronizedTime 11 Reserved
Error 12 Error occurred
InsufficientSecurityInformation 13 Stream encrypted, can't decrypt

StreamingConnectionStatus

Connection status values (see complete list in TypeScript definitions).

Common values:

Status Value Description
ConnectingToMediaGateway -1 Connecting to Media Gateway
Streaming 5 Successfully streaming
UnauthorizedToken 31 Token denied

PlayerMode

Player mode enumeration.

Mode Value Description
unknown "unknown" Unknown mode
live "live" Live streaming mode
playback "playback" Playback mode

TimelineEventKind

Timeline event type enumeration.

Kind Value Description
RecordingSequence 0 Available archive sequence
Bookmark 1 User bookmark

PtzFocusDistance

Focus distance enumeration for PTZ focus control.

Distance Value Description
Near 0 Focus near
Far 1 Focus far

PtzIrisOperation

Iris operation enumeration for PTZ iris control.

Operation Value Description
Open 0 Open iris
Close 1 Close iris

Event types

ErrorStatusEvent

{
    errorCode: ErrorCode,
    value: string,
    isFatal: boolean
}

StreamingConnectionStatusChangeEvent

{
    state: StreamingConnectionStatus,
    value: string
}

PlayerStateChangeEvent

{
    playerState: PlayerState,
    value: string
}

PlaySpeedChangeEvent

{
    playSpeed: number
}

AudioStateChangeEvent

{
    isAudioEnabled: boolean
}

AudioAvailabilityChangeEvent

{
    isAudioAvailable: boolean
}

PlayerModeChangeEvent

{
    playerMode: PlayerMode  // 'unknown', 'live', or 'playback'
}

TimelineContentEvent

{
    coverageStart: Date,
    coverageEnd: Date,
    events: TimelineEvent[]
}

TimelineEvent

{
    time: Date,
    duration?: number,       // Duration in seconds (optional)
    details?: string,        // Event details (optional)
    kind: TimelineEventKind  // 0 = RecordingSequence, 1 = Bookmark
}

Type definitions

IPlayerStats

Snapshot of diagnostic statistics returned by webPlayer.getPlayerStats().

Property Type Description
id number Player identifier
version string Player version
mode PlayerMode Current player mode
state PlayerState Current player state
speed number Current play speed
streamStatus string | null Current streaming status
lastErrorCode number | null Last error code
lastErrorMessage string | null Last error message
videoCodec string | null Video codec
resolution IResolution | null Video resolution
clockRate number | null Video clock rate
fps number | null Video frame rate
kfInterval TimeSpan | null Average time between keyframes
videoBitrateKbps number | null Video bitrate in kbps
audioBitrateKbps number | null Audio bitrate in kbps
isPrivacyProtected boolean Whether the stream is privacy protected
playerStartTimestamp string | null Time when the player received the start command
packetsReceived number | null Total packets received
packetsLost number | null Total packets lost
framesDecoded number | null Total frames decoded
framesDropped number | null Total frames dropped
networkLatency TimeSpan | null Live video network transmission time
playerLatency TimeSpan | null Live video decode and render time
firstDataReceivedDelay TimeSpan | null Time to receive first data after a user command
firstDataReceivedTimestamp string | null Time when the player received first data after a user command
firstFrameRenderDelay TimeSpan | null Time to render the first frame after a user command
firstFrameRenderTimestamp string | null Time when the player rendered the first frame after a user command
lastFrameReceived string | null Timestamp of the last frame received
lastFrameRendered string | null Timestamp of the last frame rendered
mediaTime number Media time from MP4 frames
zoomLevel number Current zoom level

TokenRetrieverFct

Function type for retrieving authentication tokens.

type TokenRetrieverFct = (camera: string) => Promise<string>

Parameters:

  • camera - Camera GUID

Returns: Promise resolving to token string

Example:

const getTokenFct = async (cameraId) => {
    const response = await fetch(`${mediaGateway}/v2/token/${cameraId}`, {
        credentials: 'include',
        headers: {
            'Authorization': `Basic ${btoa(credentials)}`
        }
    });
    return await response.text();
};

Notes

  • All interface definitions are available in gwp.d.ts
  • For detailed usage examples, see the Genetec Web Player developer guide
  • Date/time values are in UTC
  • All coordinates are normalized (0-1 or -1-1 ranges as specified)
  • Event handlers should be lightweight to avoid impacting video smoothness

Platform SDK

Plugin SDK

Workspace SDK

Media SDK

Macro SDK

Web SDK

Media Gateway

Genetec Web Player

Clone this wiki locally