-
Notifications
You must be signed in to change notification settings - Fork 6
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.
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
- TypeScript definitions
- gwp module
- IWebPlayer interface
- IPtzControl interface
- IDigitalZoomControl interface
- IDewarperControl interface
- ITimelineProvider interface
- IMediaGatewayService interface
- Enumerations
- Event types
- Type definitions
- Notes
The global GWP module provides factory methods for creating players and services.
Creates a new web player instance.
Signature:
buildPlayer(container: HTMLDivElement): IWebPlayerParameters:
-
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);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
Enables GWP console logging for debugging.
Signature:
enableLogs(intense?: boolean): stringParameters:
-
intense(optional) - Enable verbose/debug level logging. Default:false
Returns: Confirmation string
Example:
gwp.enableLogs(); // Standard logging
gwp.enableLogs(true); // Verbose loggingDisables GWP console logging (warnings and errors still shown).
Signature:
disableLogs(): stringReturns: Confirmation string
Returns the GWP library version number.
Signature:
version(): stringReturns: Version string (for example, "1.12.125")
Example:
console.log('GWP Version:', gwp.version());The main interface for controlling a video player instance.
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
);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
Stops the current stream and disconnects from the Media Gateway.
Signature:
stop(): voidNotes:
- Player can be restarted with a different camera using
start() - Player resources are retained for reuse
Stops and completely releases the player, removing it from the DOM.
Signature:
dispose(): voidNotes:
- Player instance becomes unusable after disposal
- Unregister all event handlers before disposing
- DOM container is cleared
Switches to live streaming mode.
Signature:
playLive(): voidNotes:
- No effect if already playing live
- Play speed is always 1x in live mode
- PTZ controls are available in live mode
Seeks to a specific time in playback mode.
Signature:
seek(seekTime: Date): voidParameters:
-
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
Pauses the player.
Signature:
pause(): voidNotes:
- In live mode: switches to playback at current time
- Use
playLive()to return to live, notresume()
Resumes playback from paused state.
Signature:
resume(): voidNotes:
- Resumes at the last played frame
- Uses the last set play speed
Sets the playback speed.
Signature:
setPlaySpeed(playSpeed: number): voidParameters:
-
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 speedEnables or disables audio playback.
Signature:
setAudioEnabled(isAudioEnabled: boolean): voidParameters:
-
isAudioEnabled-trueto enable,falseto disable
Notes:
- Only works if audio is available
- Should be called in response to user action (browser requirement)
Enables or disables PTZ low-latency mode.
Signature:
setPtzMode(ptzMode: boolean): voidParameters:
-
ptzMode-trueto enable,falseto disable
Notes:
- Reduces latency at the expense of stream quality
- May trigger transcoding
- Disable when PTZ control is not needed
Toggles privacy protection on/off.
Signature:
togglePrivacy(): voidNotes:
- Availability depends on camera configuration and user privileges
Shows or hides the diagnostic overlay.
Signature:
showDebugOverlay(show: boolean): voidParameters:
-
show-trueto show,falseto hide
Alternative: Use Ctrl+Shift+A keyboard shortcut
Captures a snapshot of the currently displayed frame.
Signature:
getSnapshot(): ImageData | nullReturns: ImageData object or null if no frame available
Notes:
- Includes video watermarking
- Does not include digital zoom or dewarping
Gets a snapshot of the current player diagnostic statistics.
Signature:
getPlayerStats(): Promise<IPlayerStats>Returns: Promise resolving to IPlayerStats
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 |
All events use the ILiteEvent<T> interface for registration:
interface ILiteEvent<T> {
register(handler: (data: T) => void): void;
unregister(handler: (data: T) => void): void;
}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
}
});Fired periodically when frames are rendered (throttled to ~250ms).
Event data: Date - Frame timestamp
Fired when the streaming connection status changes.
Event data: StreamingConnectionStatusChangeEvent
{
state: StreamingConnectionStatus, // Status code
value: string // Status description
}Fired when the player state changes.
Event data: PlayerStateChangeEvent
{
playerState: PlayerState, // State code
value: string // State description
}Fired when play speed changes.
Event data: PlaySpeedChangeEvent
{
playSpeed: number // New play speed
}Fired when audio playback state changes.
Event data: AudioStateChangeEvent
{
isAudioEnabled: boolean // Whether audio is enabled
}Fired when audio availability changes.
Event data: AudioAvailabilityChangeEvent
{
isAudioAvailable: boolean // Whether audio is available
}Fired when switching between live and playback modes.
Event data: PlayerModeChangeEvent
{
playerMode: PlayerMode // 'unknown', 'live', or 'playback'
}Fired during playback buffering.
Event data: number - Buffering progress (0-100%)
Fired when privacy protection state changes.
Event data: void
Interface for controlling PTZ cameras.
| 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 |
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 movementInterface for digital zoom functionality.
| 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 |
| Event | Data Type | Description |
|---|---|---|
onPositionChanged |
void |
Fired when zoom position changes |
| 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 |
Interface for fisheye dewarping.
| 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 |
| 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 |
Interface for accessing timeline events (bookmarks, sequences).
Sets the range of interest for timeline events.
Signature:
setTimelineRange(startTime: Date, endTime: Date): voidParameters:
-
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
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`);
}
});
});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.
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 |
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 |
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 |
Player mode enumeration.
| Mode | Value | Description |
|---|---|---|
unknown |
"unknown" | Unknown mode |
live |
"live" | Live streaming mode |
playback |
"playback" | Playback mode |
Timeline event type enumeration.
| Kind | Value | Description |
|---|---|---|
RecordingSequence |
0 | Available archive sequence |
Bookmark |
1 | User bookmark |
Focus distance enumeration for PTZ focus control.
| Distance | Value | Description |
|---|---|---|
Near |
0 | Focus near |
Far |
1 | Focus far |
Iris operation enumeration for PTZ iris control.
| Operation | Value | Description |
|---|---|---|
Open |
0 | Open iris |
Close |
1 | Close iris |
{
errorCode: ErrorCode,
value: string,
isFatal: boolean
}{
state: StreamingConnectionStatus,
value: string
}{
playerState: PlayerState,
value: string
}{
playSpeed: number
}{
isAudioEnabled: boolean
}{
isAudioAvailable: boolean
}{
playerMode: PlayerMode // 'unknown', 'live', or 'playback'
}{
coverageStart: Date,
coverageEnd: Date,
events: TimelineEvent[]
}{
time: Date,
duration?: number, // Duration in seconds (optional)
details?: string, // Event details (optional)
kind: TimelineEventKind // 0 = RecordingSequence, 1 = Bookmark
}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 |
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();
};- 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
- Overview
- Connecting to Security Center
- SDK certificates
- Referencing SDK assemblies
- SDK compatibility
- Entities
- Entity cache
- Transactions
- Events
- Actions
- Security Desk
- Custom events
- ReportManager
- ReportManager query reference
- DownloadAllRelatedData and StrictResults
- Privileges
- Partitions
- Logging
- Overview
- Certificates
- Lifecycle
- Threading
- State management
- Configuration
- Restricted configuration
- Events
- Queries
- Request manager
- Database
- Entity ownership
- Entity mappings
- Server management
- Custom privileges
- Custom entity types
- Resolving non-SDK assemblies
- Deploying plugins
- .NET 8 support
- Overview
- Certificates
- Creating modules
- Tasks
- Pages
- Components
- Tile extensions
- Services
- Contextual actions
- Options extensions
- Configuration pages
- Monitors
- Shared components
- Commands
- Extending events
- Map extensions
- Timeline providers
- Image extractors
- Credential encoders
- Credential readers
- Cardholder fields extractors
- Badge printers
- Content builders
- Dashboard widgets
- Incidents
- Logon providers
- Pinnable content builders
- Custom report pages
- Overview
- Getting started
- MediaPlayer
- VideoSourceFilter
- MediaExporter
- MediaFile
- G64 converters
- FileCryptingManager
- PlaybackSequenceQuerier
- PlaybackStreamReader
- OverlayFactory
- PtzCoordinatesManager
- AudioTransmitter
- AudioRecorder
- AnalogMonitorController
- Camera blocking
- Overview
- Getting started
- Referencing entities
- Entity operations
- About access control in the Web SDK
- About video in the Web SDK
- Users and user groups
- Partitions
- Custom fields
- Custom card formats
- Actions
- Events and alarms
- Incidents
- Reports
- Tasks
- Macros
- Custom entity types
- System endpoints
- Performance guide
- Reference
- Under the hood
- Troubleshooting