# ffmpeg monitor and restart stream when it hung or stall

You are using ffmpeg to stream to youtube but after a while, it hung or stuck. You want to restart the streaming command when this happens.

First run the `ffmpeg` command on a terminal in a while loop (this example is for fish terminal)

```
while true
  ffmpeg -re -i https://roundrobin3.videostreamingwowza.com/visdeurbel2/visdeurbel2.stream/playlist.m3u8 -c:v copy -c:a aac -ar 44100 -ab 128k -ac 2 -strict -2 -flags +global_header -bsf:a aac_adtstoasc -bufsize 3000k -f flv "rtmp://a.rtmp.youtube.com/live2/abcd-efgh-ijkl" > youtube.log
  sleep 5
end
```

This will run the stream and output it to a `log.txt`

run this script on separate terminal to monitor and restart ffmpeg process

```
#!/bin/sh

#sleep 10
while true
do
    frameA=$(grep "videostreamingwowza" youtube.log | tail -n1 | sed -n 's/.*\(roundrobin3.videostreamingwowza.com.*\.ts.*\)/\1/p')
    echo "A: $frameA"
    sleep 30
    frameB=$(grep "videostreamingwowza" youtube.log | tail -n1 | sed -n 's/.*\(roundrobin3.videostreamingwowza.com.*\.ts.*\)/\1/p')
    echo "B: $frameB"

    if [ "$frameA" = "$frameB" ]
    then
        echo "Stream has hung"
        printf "%s - Stream has hung\n" "$(date)" >> stream.log
        pkill ffmpeg
        echo "killed ffmpeg..."
    fi

    sleep 2
done
```

Basically it take some line from the log, and do it again after 30 seconds.

If the line stays the same, it assume that the stream stuck and kill the `ffmpeg` process


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://til.yulrizka.com/unix/ffmpeg-monitor-and-restart-stream-when-it-hung-or-stall.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
