Skip to main content

Triggers/Hooks

The trigger/hook system allows you to customize MistServer at nearly every event, allowing you to effectively completely rewrite how Stream data goes in or out of MistServer. Any language can be used together with trigger/hook for a full list of triggers and how they specifically work please look at the triggers/hooks documentation

All Triggers/hooks have a set of options:

  • Handler : This determines what script/page gets the trigger payload information.
  • Blocking : When blocking the trigger/hook will await a response and act on it. Otherwise the handler will be reached, but responses are ignored and normal server flow continues.
  • Default Response : When Blocking and the handler fails to answer, use what is filled in here as the answer instead.
  • Applies to: Choose the streams to which this trigger/hook applies.

Handler

Should a local script be used, MistServer will provide the payload over standard in and expects an answer back of the standard out. If handled as an URL, a POST request is sent to the URL with an extra X-Trigger header containing the trigger name and the payload as the POST body.

Blocking

Blocking is an important mode for triggers/hooks as it determines whether you're going to change the server flow or not. When set to Blocking MistServer will await an response to the trigger and use the response to change the default behaviour. When non-blocking is used, the handler will still get the payload and fire, however MistServer will not await a response and immediately go to the default behaviour.

Note that even if a trigger is set to non-blocking you could still have it activate a script that affects the server directly through the script itself.

1 · Trigger setup2 · Blocking vs Non-Blocking3 · ContinueTrigger conditionMistServer prepares the event payloadConfigured handlerlocal script or HTTP endpointBlocking handlerMistServer waits for a resultNon-blocking handlerMistServer continues immediatelyApply the resultallow, reject, or rewriteor use the timeout defaultIgnore the responseobserve or log the eventside effects may still call the APIContinue MistServer flow
  1. 01
    Trigger condition
    payload

    MistServer calls the configured handler.

  2. 02
    Handler
    blocking or non-blocking

    The mode determines whether MistServer waits for a result.

  3. 03
    Blocking path
    responsedefault response on timeout

    Use the response to allow, reject, or rewrite the action.

  4. 04
    Non-blocking path
    observe only

    MistServer continues with its default behaviour while the result can be logged.

  5. 05
    Trigger ends

    Both paths finish without changing the trigger lifecycle.

Blocking handlers may change the action. Non-blocking handlers observe it without delaying MistServer.

Type of triggers/hooks and when do they activate

The trigger/hook system is quite massive and there's many points that can be used. For the ease of understand we've divided the triggers in 4 categories and created flowcharts that should hopefully help in finding which trigger might be best for each use-case.

Access Control Hook/Triggers

These exist to do any form of Access control where you allow viewers/contributors access to MistServer

  • USER_NEW - (Whenever a new viewer session starts or an existing session is revalidated, true allows access and false rejects it)
  • PLAY_REWRITE - ( Whenever playback is attempted, Response overrides the stream playback to the given stream name instead)
  • PUSH_REWRITE - (Whenever an incoming push is detected, override the MistServer Stream target or empty for reject)
  • *RTMP_PUSH_REWRITE - (Whenever an incoming RTMP push comes in, obsoleted by PUSH_REWRITE, override MistServer Stream target or empty for reject)

Lifecycle Hook/Triggers

These exist to start/continue/stop new or existing connections.

  • CONN_OPEN - (Whenever a connection is accepted, false blocks)
  • CONN_PLAY - (Right before playback after acception, false rejects)
  • LIVE_BANDWIDTH - (Everytime keyframe is received, check bandwidth, if false shut down input)
  • STREAM_PUSH - (Right before an incoming push is accepted, false to reject the push)
  • STREAM_READY - (When a stream finished loading and is ready for playback, if false shut down the input)
  • STREAM_UNLOAD - (Before a stream input is unloaded, if false keep the stream active)
  • PUSH_OUT_START - (Whenever any push to file/target is started, override the target with response or empty for abort)
  • SYSTEM_START - (When MistServer boots, if false shut down the server)
  • SYSTEM_STOP - (When MistServer shuts down, if false abort shutdown)
  • *STREAM_LOAD - (Right before a stream input is loaded, false to abort loading of input. Obsoleted by STREAM_SOURCE which allows for more control at the same event point.)

Configuration Hook/Triggers

These exist to adjust/change default server behaviour

  • DEFAULT_STREAM - (whenver an unavailable stream is attempted to be watched, can change stream to be used, false for error)
  • STREAM_ADD - (Before a new stream is created, false to reject)
  • STREAM_CONFIG - (Whenever a stream configuration changes, false to reject the changes)
  • STREAM_REMOVE - (Before an existing stream is removed, if false reject the change)
  • STREAM_SOURCE - (When a stream's source is loaded, response overrides the stream source, empty will continue with the current source)

Notification Hook/triggers

These exist purely to pass on information to another application/endpoint meant to measure, list or log so decisions can be made or logged. These cannot activate a response to the trigger itself and are only there for logging purposes.

  • CONN_CLOSE - ( Whenever a connection closes)
  • INPUT_ABORT - ( Whenever an input process exists with error)
  • LIVEPEER_SEGMENT_REJECTED - ( Whenever a segmented is rejected by MistProcLivepeer with a 422 status twice in a row for different broadcasters)
  • LIVE_TRACK_LIST - ( Whenever valid tracks update/change)
  • OUTPUT_END - ( Whenever an output (push or pull out) stops)
  • OUTPUT_START - ( Whenever an output to another server starts)
  • OUTPUT_STOP - ( When a protocol connector stops listening for connections)
  • PUSH_END - ( Whenever a push (file or target) stops for any reason)
  • RECORDING_END ( Whenever a push to file finishes)
  • STREAM_BUFFER ( Whenever a live stream buffer changes)
  • STREAM_END ( Whenever a stream ends due to viewer inactivity)
  • USER_END ( Whenever a session ends, give statistics of session)

General flowchart

1 · Server boot2 · Configuration & connectors3 · Focused runtime flows4 · Shutdownconfigured media pathsidentity + analyticsMistServer bootsSYSTEM_STARTConnectorsOUTPUT_START · OUTPUT_STOPStream configurationSTREAM_CONFIGController + sessionssettings · keys · JWTLive ingestsource and buffer lifecyclePlayback + pushviewer and output lifecycleVoD + processingmedia and track lifecycleSession flowidentity and analyticsSYSTEM_STOP
  1. 01
    Server lifecycle
    SYSTEM_STARTSYSTEM_STOP

    Run hooks when MistServer starts and shuts down.

  2. 02
    Connectors
    OUTPUT_STARTOUTPUT_STOP

    Listening sockets become available to ingest and playback.

  3. 03
    Stream configuration
    STREAM_CONFIG

    Settings, stream keys, and JWT policy select the next media path.

  4. 04
    Runtime paths
    live ingestVoD ingestplaybackpush output

    Each focused path has its own diagram below.

  5. 05
    Sessions and analytics

    Session state exchanges viewer and operational data with the controller.

The overview is a map, not a required linear sequence. Open the focused diagrams below for each runtime path.

Live streaming ingest

1 · Source connect2 · Ingest accept3 · Live monitoring4 · Source ends → offlineallowedstream activeemitsadds tracks Issues -> Dryunrecoverable or stoppedLive sourceincoming pushCONN_OPENPUSH_REWRITEAuthenticatepush requestRejectedpush deniedSTREAM_PUSHor STREAM_SOURCEBegin ingestingcreate or attach tracksINPUT_ABORTInput errorSTREAM_READYIncoming mediapackets and keyframesLive streamactive bufferStream processoptional track outputSTREAM_BUFFERBuffer health changesLIVE_TRACK_LISTEvery track add/removeLIVE_BANDWIDTHEvery KeyframeFULLDRY / RECOVERIssues gone = RECOVEREMPTYSource disconnectsor all tracks endSTREAM_UNLOADSTREAM_ENDOffline
  1. 01
    Source active
    CONN_OPENPUSH_REWRITE

    Authenticate the incoming push. A failed check rejects it; an ingest error emits INPUT_ABORT.

  2. 02
    Accept Ingest
    STREAM_PUSHSTREAM_SOURCE

    Create or attach to the stream and begin ingesting tracks.

  3. 03
    Playback ready
    STREAM_READY

    The stream becomes active once media data fills a track.

  4. 04
    Live monitor
    STREAM_BUFFERLIVE_TRACK_LISTLIVE_BANDWIDTH

    Report buffer health, track changes, and measured bandwidth while stream processes can add tracks.

  5. 05
    Live health
    FULLDRYRECOVEREMPTY

    Healthy streams may stall and recover; unrecoverable or ended streams become empty.

  6. 06
    Stream end
    STREAM_UNLOADSTREAM_END

    All tracks ending or the source disconnecting takes the stream offline.

The live path is grouped into admission, activation, the active stream loop, and shutdown. Viewers can connect once a stream is live and will follow the playback loop.

Deprecated, DO NOT USE:

  • RTMP_PUSH_REWRITE - Replaced by PUSH_REWRITE which has the same functionality, however works for all incoming push protocols
  • STREAM_LOAD - replaced by STREAM_SOURCE which has the same trigger point, but allows changes instead of just sending a notification.

VoD ingest

Tracked viewer connections keep a VoD input's activity timer refreshed. After the last tracked viewer disconnects, the input stays loaded until inputtimeout expires (30 seconds by default). MistServer calls STREAM_UNLOAD before releasing the input; a blocking handler may cancel that unload. STREAM_END is emitted when the stream becomes inactive.

1 · Prepare and serve2 · Idle cleanuplast tracked viewer session disconnectsPlayback requestVoD sourceSTREAM_SOURCELoad metadatacreate DTSH if neededSTREAM_READYload media into shared memory on demandInput activity timeoutinputtimeout · 20s defaultSTREAM_UNLOADmay cancel unloadInput unloadsshared media is releasedSTREAM_ENDnotification
  1. 01
    Playback request
    STREAM_SOURCE

    Prepare the source when it is not active.

  2. 02
    Prepare metadata
    DTSH

    Create DTSH when needed, then load VoD metadata.

  3. 03
    Ready
    STREAM_READY

    Load requested media into shared memory.

  4. 04
    Serve viewers

    Tracked output connections keep the input activity timer refreshed.

  5. 05
    Idle cleanup
    STREAM_UNLOADSTREAM_END

    After the last tracked viewer disconnects, unload when inputtimeout expires (20 seconds by default).

The input activity timer is refreshed while tracked viewers are connected. Once the stream is ready Viewers can connect for the playback loop and receive stream data from shared memory. After the last one disconnects, the 20-second default input timeout begins; STREAM_UNLOAD may cancel the unload.

Playback/viewers

Viewer sessions and input lifetimes use different timers. A normal viewer session ends and emits USER_END after 15 seconds without an active connection. The separate 10-minute timeout applies to invalidated sessions; it does not control when a VoD input unloads.

1 · Playback request2 · Serve playbackoffline / missingactive / rewrittenfallback readyinvalid requestnew viewerexisting sessionallowedViewerplayback requestCONN_OPENPLAY_REWRITEDEFAULT_STREAMtry a fallbackSelected streamactive, rewritten, or fallbackRejectinvalid requestSession lookupreuse when possibleUSER_NEWauthorize new viewerCONN_PLAYsession authorizedRejectpermission deniedCONN_CLOSEplayback endUSER_END15s of no other activitySession removed
  1. 01
    Open connection
    CONN_OPENPLAY_REWRITE

    Rewrite the requested stream before playback begins.

  2. 02
    Resolve the stream
    DEFAULT_STREAM

    Use a fallback when the requested stream is missing or offline; reject invalid requests.

  3. 03
    Authorize the viewer
    USER_NEW

    Create a session for a new viewer or reuse an existing session.

  4. 04
    Start playback
    CONN_PLAY

    Begin playback after session permissions pass.

  5. 05
    Close and expire
    CONN_CLOSEUSER_END

    Close the connection, then end a normal viewer session after 15 seconds without an active connection.

Playback separates connection admission, stream selection, and session authorization. A normal viewer session ends after 15 seconds without an active connection; invalidated sessions use a separate 10-minute hold.

Push output & recording

Manual requestAutomatic ruleconditions metPUSH_OUT_STARTPush activelocal and remote targetsCONN_OPENremote targetClose outputCONN_CLOSEPUSH_ENDRECORDING_ENDor OUTPUT_END
  1. 01
    Request a push

    Start manually or when an automatic push rule matches.

  2. 02
    Authorize start
    PUSH_OUT_START

    Choose a local recording or a remote target.

  3. 03
    Run the push
    CONN_OPEN for remote targets

    The push remains active until its source or rule stops.

  4. 04
    Close output
    CONN_CLOSERECORDING_END or OUTPUT_END

    Recordings emit RECORDING_END; other targets emit OUTPUT_END.

  5. 05
    Finish
    PUSH_END

    Both paths converge on the final push event.

OUTPUT_END always fires, RECORDING_END only for local pushes.

Stream processes

Stream sourcetracks addedLIVE_TRACK_LISTNew tracks addedStream bufferProcess startsINPUT_ABORTProcess start failLIVEPEER_SEGMENTREJECTEDFail at any pointLive ingest pipeline add track to current or another stream
  1. 01
    Source track changes
    LIVE_TRACK_LIST

    Added tracks update the stream buffer.

  2. 02
    Start a process

    Start when the configured conditions match.

  3. 03
    Handle failures
    INPUT_ABORTLIVEPEER_SEGMENT_REJECTED

    Report startup failures or rejected Livepeer segments.

  4. 04
    Return output
    LIVE_TRACK_LIST

    Add new tracks to the current stream, or send them to another live ingest pipeline.

A process may add a track to the current stream or feed another live ingest pipeline.

Special mention: Sessions

While no triggers/hooks directly affect Sessions they are very important as they decide whether certain behaviour is registered as an output, viewer, or not at all and when it is recognised as a previously existing connection. A good example would be USER_NEW which can be used to force new viewers to authenticate with your account system. However should this be done when they switch protocol? When they switch playback token? When they switch IP address?

We recommend reading up on the session system for this reason.