Sometimes you need to calculate the bitrate (in kbps) of a live stream to restrict the usage or manage to the bill of the user. As of today, there is no direct way to get the bitrate of a live stream in Red5 open source or Red5 Pro. Instead, you can use this old-school sampling technique to estimate the bitrate of a live stream which can be coded in any language for any platform.
The steps involved in evaluating the bitrate cab roughly be written as in the following manner :
- On application startup, start a timer which will be running continuously (every 2 seconds), aiding in evaluation of bitrates of all candidate streams taken fro a list.
- Detect publish start for a new stream
- On publish start add the stream to a list as a candidate for evaluation
- For each evaluation cycle inside the timer calculate the current estimated bitrate using bytes-transferred-inwards data
- Store the evaluated bitrate sample in a tmp data structure. In the similar way capture about 4 or 6 data samples.
- Take the average of all the data samples collected to get a average bitrate
- Finally use this average bitrate data to calculate bitrate per second.
- On unpublish remove the stream from list of candidates so that we dont get a NullPointerException
The code snippet below demonstrates how to calculate and log the average bitrate of a live stream in Red5.