Skip to content

gwp api reference

Andre Lafleur edited this page Dec 12, 2025 · 1 revision

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.

GWP Version: 1.12.41 Security Center Compatibility: 5.10+ (dewarping requires 5.10.2+)

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 ensure version compatibility. 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
  • Best practices and usage patterns
  • Gotchas 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 (e.g., "1.12.41")

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
): 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

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
): Promise<void>

Parameters:

  • camera - Camera GUID
  • mediaGatewayService - Existing Media Gateway service instance
  • serverVersion (optional) - Security Center version

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

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  // '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


onTimelineContentUpdated

Fired when timeline content is updated.

Event Data: TimelineContentEvent - See ITimelineProvider


IPtzControl Interface

Interface for controlling PTZ cameras.

Methods

Method Parameters Description
startPanTilt() panSpeed: number, tiltSpeed: number Start pan/tilt movement (speeds 0-100%)
stopPanTilt() - Stop pan/tilt movement
startZoom() zoomSpeed: number Start zoom movement (speed 0-100%)
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

Example

const ptz = webPlayer.ptzControl;

// Pan and tilt
ptz.startPanTilt(0.5, 0.3);  // 50% pan, 30% tilt
setTimeout(() => ptz.stopPanTilt(), 3000);

// Zoom
ptz.startZoom(0.8);  // 80% zoom 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

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

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.setTimelineRange(
    new Date('2024-01-01T00:00:00Z'),
    new Date('2024-01-02T00:00:00Z')
);

webPlayer.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.


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
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

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
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  // '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

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

Security Center SDK


Macro SDK Developer Guide


Web SDK Developer Guide

  • Getting Started Setup, authentication, and basic configuration for the Web SDK.
  • Referencing Entities Entity discovery, search capabilities, and parameter formats.
  • Entity Operations CRUD operations, multi-value fields, and method execution.
  • Partitions Managing partitions, entity membership, and user access control.
  • Custom Fields Creating, reading, writing, and filtering custom entity fields.
  • Custom Card Formats Managing custom credential card format definitions.
  • Actions Control operations for doors, cameras, macros, and notifications.
  • Events and Alarms Real-time event monitoring, alarm monitoring, and custom events.
  • Incidents Incident management, creation, and attachment handling.
  • Reports Activity reports, entity queries, and historical data retrieval.
  • Performance Guide Optimization tips and best practices for efficient API usage.
  • Reference Entity GUIDs, EntityType enumeration, and EventType enumeration.
  • Under the Hood Technical architecture, query reflection, and SDK internals.
  • Troubleshooting Common error resolution and debugging techniques.

Media Gateway Developer Guide


Web Player Developer Guide

Clone this wiki locally