Skip to content

media sdk play video

Andre Lafleur edited this page Oct 8, 2026 · 9 revisions

About MediaPlayer

MediaPlayer is a WPF control that displays live camera streams, archived video, or local G64 and G64x files. It owns rendering, playback commands, snapshots, stream statistics, metadata stream subscription, and synchronized playback across multiple instances.

For live and archive playback from a camera, call Initialize with a logged-on Platform SDK Engine. The Security Center license must include the Media SDK option; without it, the Initialize call fails and camera playback does not start. For local file playback, call OpenFile(filePath) and PlayFile(); that path does not require Initialize or an Engine.

On this page, MediaPlayer is Genetec.Sdk.Media.MediaPlayer, not the WPF System.Windows.Media.MediaPlayer. In a WPF application, qualify the type or alias it: using MediaPlayer = Genetec.Sdk.Media.MediaPlayer;.

How playback works

Add MediaPlayer to the WPF visual tree, set per-instance properties, subscribe to the events you need, then call Initialize followed by PlayLive, PlayArchive, or OpenFile and PlayFile. MediaPlayer opens its streaming session inside Initialize, so most setup properties are ignored or throw if you set them after initialization.

Three state machines run in parallel and answer different questions:

Property Type Reports
State PlayerState Playback state: playing, paused, stopped, buffering, error, no-video
StreamingConnectionStatus StreamingConnectionStatus Streaming session state, independent of playback
ErrorDetails ErrorDetails Error information when the player enters an error state

A player can be in state Playing with a degraded StreamingConnectionStatus, or Stopped with an ErrorDetails that explains why startup failed. Subscribe to all three when the application needs to surface meaningful messages to an operator.

MediaPlayer

Add the control to a WPF host, and then initialize and start playback:

MediaPlayer player = new MediaPlayer();
VideoHost.Children.Add(player);

player.PlayerStateChanged += OnPlayerStateChanged;
player.StreamingConnectionStatusChanged += OnConnectionChanged;

player.Initialize(engine, cameraGuid);
player.PlayLive();

Initialize has overloads for selecting the streaming type, the client subnet, and the network adapter binding. Pass Guid.Empty for the client subnet when the default media route is acceptable, which it is for most integrations.

MediaPlayer members

Set these on the instance before calling Initialize:

Member Type Description
HardwareAccelerationEnabled bool Use GPU decoding when the host machine supports it.
IsAudioEnabled bool Decode audio when the camera carries an audio stream.
FillRenderedVideoContainer bool Fill the host control with the rendered video while preserving the aspect ratio; parts of the image can be cropped. When false (the default), the whole image is displayed inside the host control.

Set IsLiveCachingEnabled after calling Initialize; a value set before Initialize is discarded. When enabled, the player keeps a local buffer of recent live video so the operator can rewind and replay it, then return to live (instant replay).

These global static properties affect every MediaPlayer created afterward in the process. Set them during application startup, before any player is created:

Member Type Description
MediaPlayer.CacheRootLocation string Folder used for the playback cache. By default, when the local user application-data path is writable, the SDK uses a VideoCache subfolder under that path.
MediaPlayer.MaximumCacheSize long Cache size in megabytes.
MediaPlayer.PlayOutBufferCache TimeSpan Play-out buffer length used to absorb packet delay variation.
MediaPlayer.AutomaticallyStartOverlayStream bool Have new players automatically subscribe to overlay metadata streams as they become available.

Live, archive, and file playback

Three entry points cover the supported sources:

player.Initialize(engine, cameraGuid, StreamingType.Live);
player.PlayLive();
player.Initialize(engine, cameraGuid);
player.PlayArchive(seekTimeUtc);
player.OpenFile(filePath);
player.PlayFile();

Use UTC values for PlayArchive, Seek, Rewind, and loop ranges. Convert to local time only at the UI boundary.

For file playback, watch PlayerStateChanged to know when the file is ready: success appears as State reaching Playing. If file playback fails, State settles at something other than Playing and ErrorDetails is non-null; inspect them together to determine whether the file, the playback state, or another condition caused the failure.

After archive playback starts, PlaybackSequencesList contains the recorded ranges available in the current playback context. Use it to drive timeline UI such as enabling or disabling regions where no recording exists.

Playback commands

Command Member
Start live playback PlayLive()
Start archive playback PlayArchive(DateTime seekTime)
Open a local file OpenFile(string fileName) and PlayFile()
Pause Pause()
Resume ResumePlaying()
Stop Stop()
Seek to a time Seek(DateTime seekStartTime)
Rewind Rewind() or Rewind(DateTime seekTime)
Step by frame PlayNextFrame() or PlayPreviousFrame()
Loop a range SetLoopRange(DateTime startTime, DateTime endTime)
Remove the loop range RemoveLoop()
Change playback speed PlaySpeed property

Drive button enabled state from PlayerStateChanged. A command can succeed asynchronously, so do not assume the next state immediately after invoking it: media startup, buffering, archive availability, and security checks can all change the resulting state.

Player state lifecycle

State is a PlayerState value on MediaPlayer and on each source filter (through their shared PublicMediaPlayerProxy base). PlayerStateChanged is raised after the value changes. The event argument carries the new state only; an application that needs to detect a specific transition must remember the previous value itself.

States

State Meaning
Stopped Not rendering any stream. The initial state and the state after Stop() completes from a non-error state.
Starting Initializing the stream rendering pipeline. Raised on initialization and on each restart.
Buffering Waiting for stream data.
Playing Receiving and rendering a stream forward.
Rewinding Receiving and rendering a stream backward (during Rewind).
Paused A stream is loaded but rendering is paused.
WaitingForArchiverData Near-live playback is waiting for the archiver to write more data before resuming.
EndReached Forward playback reached the end of the available sequence.
BeginReached Reverse playback reached the start of the available sequence.
NoVideoSequenceAvailable The selected time has no video sequence and no later one. Also raised by Seek or Rewind when the requested UTC time is after DateTime.UtcNow, by maximum-unit-connection-reached and bandwidth-limit-exceeded conditions, and by other no-video conditions.
AwaitingSynchronizedTime The selected time has no sequence yet but a sequence exists later; the player is waiting for the synchronization time to reach it.
InsufficientSecurityInformation The stream cannot be decrypted (no decryption key). Playback stops as for NoVideoSequenceAvailable.
Error The player is in error mode. Read ErrorDetails for the cause.
Stopping Transient state raised during Stop() from a non-error state, immediately before Stopped.

Reacting to state changes

Playback commands take effect asynchronously, so State does not necessarily change the moment you call a command, and the player can pass through intermediate states such as Starting and Buffering before Playing. Drive your UI from PlayerStateChanged and react to the state the player reports rather than predicting the next value. When the player reports Error, read ErrorDetails.Code and ErrorDetails.Details for the cause.

Useful state groupings

When writing UI logic, group states by intent rather than checking each value:

Group States in the group
Video is currently displayed Playing, Paused, Rewinding
Waiting for data Buffering, WaitingForArchiverData
Playback cannot continue forward EndReached, BeginReached, NoVideoSequenceAvailable, InsufficientSecurityInformation, Error
Reached an edge of the available sequence EndReached, BeginReached
Player is not running at all Stopped, Stopping, Starting

Player capabilities

Not every camera supports every command. MediaPlayer exposes three capability flags after initialization:

Property Type Use it to check
FeatureCapabilities FeatureCapabilities enum Optional commands such as snapshots, frame stepping, speed changes, looping, synchronization, caching, digital zoom, and access to decoded frames.
EventCapabilities EventCapabilities enum Optional events such as rendered frames, buffering progress, start, stop, and live-caching-disabled events.
StatisticsCapabilities StatisticsCapabilities enum Optional stream statistics such as source IP, packet loss, dimensions, frame rate, and view size.
snapshotButton.IsEnabled = player.FeatureCapabilities
    .HasFlag(FeatureCapabilities.SnapshotCommand);

speedSelector.IsEnabled = player.FeatureCapabilities
    .HasFlag(FeatureCapabilities.SetPlaySpeedPlaybackCommand);

Snapshots

SnapShot() returns a System.Drawing.Bitmap of the rendered frame. The caller owns the bitmap and must dispose it.

using Bitmap image = player.SnapShot(
    applyZoomToSnapShot: true,
    writeDateTime: true,
    additionnalData: "Entrance camera");

Overloads accept a target size for fitting the snapshot to a fixed output size, and PrintSnapShot sends the rendered frame to a printer.

Synchronizing several players

Add players to the process-wide synchronized group:

MediaPlayer playerA = new MediaPlayer();
MediaPlayer playerB = new MediaPlayer();

playerA.AddToSynchronizedPlayback();
playerB.AddToSynchronizedPlayback();

playerA.PlayArchive(startTimeUtc);

playerB.RemoveFromSynchronizedPlayback();

Use IsInSynchronizedPlayback() to check membership. Remove players from the group before disposing them.

Tracking viewed archive ranges

Call Stop() to end the playback session, and then call GetPlaybackAuditReport() to retrieve the archive ranges the operator viewed. Each PlaybackRange entry exposes the archive start and end times and the wall-clock range during which the operator was watching that segment.

This is the supported way to produce investigation audit information from the playback session itself. To query where recordings exist independently of playback, use PlaybackSequenceQuerier.

Metadata streams

Metadata streams can become available after the player starts. Subscribe from the availability event rather than assuming the list is complete during initialization:

player.AvailableMetadataStreamChange += (_, _) =>
{
    foreach (Guid streamId in player.AvailableMetadataStreams)
    {
        if (!player.MetadataStreamsSubscriptions.Contains(streamId))
        {
            player.SubscribeMetadataStream(streamId);
        }
    }
};
Member Description
AvailableMetadataStreams Metadata stream IDs the player can subscribe to.
MetadataStreamsSubscriptions Metadata stream IDs the player is currently subscribed to.
AvailableMetadataStreamChange Raised when metadata streams are discovered, added, or removed.
SubscribeMetadataStream(Guid) Display the selected metadata stream.
UnsubscribeMetadataStream(Guid) Stop displaying the selected metadata stream.

MediaPlayer.AutomaticallyStartOverlayStream is process-wide. When set to true, every player created afterward subscribes to overlay metadata streams automatically as they become available. Leave it false when the operator chooses which streams to display.

ShowSpecialOverlay(OverlayType) displays built-in player overlays such as status overlays. For application-drawn overlays, see OverlayFactory.

Buffering and live caching

Event Description
BufferingProgressChanged Reports archive or playback buffering progress through BufferingProgressChangedEventArgs.BufferingProgressPercentage (0-100).
LiveCachingDisabled Raised when live caching is disabled because the player cannot buffer data, such as when disk space is unavailable.

BufferingWriteCapacityChanged is kept for compatibility. PlayOutBufferCacheNotBigEnough and PlayOutBufferCacheOverflow are kept in the API for backward compatibility but are never raised. Use BufferingProgressChanged and LiveCachingDisabled together with State, StreamingConnectionStatus, and ErrorDetails for current playback feedback.

Stream quality and rendering events

Subscribe to these events to surface quality information or react to stream changes:

Event Description
FrameRendered Raised after each frame renders. Carries the rendered frame time.
BitRateRefreshed, FrameRateRefreshed Updated stream quality values.
RtpPacketsLostRefreshed Updated packet loss count.
VideoDimensionRefreshed, VideoRotationChange Stream dimensions or rotation changed. Re-layout when this is raised.
EncryptionStateChanged Encrypted stream state changed.

Disposing the player

Stop playback and dispose the player when the containing view closes:

player.Stop();
player.Dispose();

Call MediaPlayer.CleanUpStaticResources() once, when the application is finished with all MediaPlayer instances and all source-filter components (VideoSourceFilter, AudioVideoSourceFilter). The cleanup releases process-wide resources held by PublicMediaPlayerProxy, which the source filters inherit from. MediaPlayer exposes the static method even though it is not derived from PublicMediaPlayerProxy, because the cleanup affects the same underlying resources. Do not call it while any MediaPlayer or source-filter is still active. MediaExporter and PlaybackStreamReader do not share these static resources, so they are not affected.

See also

Platform SDK

Plugin SDK

Workspace SDK

Media SDK

Macro SDK

Web SDK

Synergis RIO

Media Gateway

Genetec Web Player

Clone this wiki locally