functions/public/Invoke-RTSPSegment.ps1

function Invoke-RTSPSegment {
  <#
  .SYNOPSIS
  Saves an RTSP stream to a series of file segments on the local filesystem.

  .PARAMETER Hostname
  The DNS name or IP address of the RTSP endpoint that you want to stream data from.

  .PARAMETER Username
  The username to authenticate to the RTSP endpoint.

  .PARAMETER Pass
  The password to authenticate to the RTSP endpoint.

  .PARAMETER Port
  The port that the RTSP endpoint is listening on. This value is different for every service or security camera out there.

  .PARAMETER UrlPath
  The value that comes AFTER the forward slash character in the URL.
  For example, some Foscam cameras use videoMain.
  Some cameras might use live/ch0 or live/ch1.

  .PARAMETER SegmentTime
  The duration of each segment from the RTSP stream.
  By default, we use 600 seconds (10 minutes).

  .PARAMETER Destination
  The output file path. You MUST use strftime() format for this.
  If you don't know what strftime() is, just leave it at the default value.

  .EXAMPLE
  Stream video data from a security camera.

  Invoke-RTSPSegment -Hostname 192.168.5.50 -Username username -Pass password -Port 88
  
  .EXAMPLE
  Change the per-segment time to 5 minutes.
  Invoke-RTSPSegment -Hostname 192.168.5.50 -Username username -Pass password -Port 88 -SegmentTime 300

  #>

  [CmdletBinding()]
  param (
    [Parameter(Mandatory = $true)]
    [string] $Hostname,
    [string] $Username,
    [string] $Pass,
    [int] $Port = 554,
    [string] $UrlPath = '',
    [Parameter(Mandatory = $false)]
    [int] $SegmentTime = 600,
    [string] $Destination = 'output-%Y-%m-%d-%H-%M-%S.mkv'
  )
  $CredString = $null -eq $Username ? '' : '{0}:{1}@' -f $Username, $Pass
  $InputString = 'rtsp://{0}{1}:{2}/{3}' -f $CredString, $Hostname, $Port, $UrlPath
  $Command = 'ffmpeg -i {0} -c copy -f segment -segment_time {1} -strftime 1 -reset_timestamps 1 {2} 2> $null' -f $InputString, $SegmentTime, $Destination
  Invoke-Expression -Command $Command
}