Mini Project
Name      : Maha Lakshmi K
Register Number : 953622243052
Subject code : CS3591
Subject Title : Computer Networks
Topic : Video Streaming Using RTSP and RTP
Video Streaming with RTSP and RTP
Introduction :
In this mini-project, we will build a video streaming application that streams video content from an
RTSP (Real-Time Streaming Protocol) source and serves it over HTTP using Flask. The client will
be able to view the live video stream in a web browser.
Technologies Used :
      Python: Flask for creating the web server.
      OpenCV: For capturing and processing video frames.
      HTML/CSS/JavaScript: For creating the client-side interface and displaying the video
       stream in a web browser.
Project Structure :
      app.py: Contains the Flask application code to serve the video stream.
      templates/index.html: HTML file for the client-side interface.
      static/style.css: CSS file for styling the HTML page.
      static/script.js: JavaScript file for fetching and displaying the video stream.
Installation and Setup :
     1. Clone the Repository: Clone this repository to your local machine.
git clone <repository_url>
cd video-streaming-mini-project
     2. Install Dependencies: Install the required Python packages.
pip install Flask opencv-python-headless
     3. Run the Application: Start the Flask server
python app.py
     4. Access the Application: Open a web browser and navigate to http://localhost:5000 to view
        the live video stream.
Project Implementation Details:
     The Flask application (app.py) sets up a route /video to serve the video stream.
     OpenCV is used to capture the video frames from the RTSP source.
     The captured frames are encoded into JPEG format and streamed to the client using Flask's
      Response object.
     The client-side interface (index.html) contains a video element to display the live video
      stream.
     JavaScript (script.js) fetches the video stream from the server and updates the video element
      with the received frames.
Backend:
Server-side (Python Flask):
from flask import Flask, Response
import cv2
app = Flask(__name__)
@app.route('/video')
def video_feed():
  cap = cv2.VideoCapture('https://www.youtube.com/watch?v=OxAvxsL08Cc') # Replace with
your RTSP URL
  if not cap.isOpened():
    return Response("Error: Could not open video stream.", status=500)
  def generate():
    while cap.isOpened():
       ret, frame = cap.read()
       if not ret:
         break
       ret, jpeg = cv2.imencode('.jpg', frame)
       frame_bytes = jpeg.tobytes()
       yield (b'--frame\r\n'
             b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
  return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
  app.run(host='0.0.0.0', port=5000, debug=True)
Program Explanation:
    This code sets up a Flask web server.
    The /video route is defined to serve as the endpoint for video streaming.
    Inside the video_feed function:
             It captures a video stream from the given RTSP URL using OpenCV
              (cv2.VideoCapture).
             It continuously reads frames from the video stream.
             Each frame is encoded into JPEG format.
             The encoded frame is then yielded as a response with a MIME type of multipart/x-
              mixed-replace which allows streaming of multiple images in a single HTTP
              response.
FrontEnd:
Client-side (HTML/JavaScript):
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Video Streaming with RTSP and RTP</title>
</head>
<body>
  <h1>Video Streaming with RTSP and RTP</h1>
  <video id="video-stream" controls autoplay></video>
  <script>
    const videoElement = document.getElementById('video-stream');
    // Function to fetch video stream from backend
    function fetchVideoStream() {
      fetch('/video')
          .then(response => {
               if (!response.ok) {
                   throw new Error('Network response was not ok');
               }
               return response.body;
          })
          .then(body => {
                                  const reader = body.getReader();
               let decoder = new TextDecoder();
               let partialData = '';
               let chunks = [];
               reader.read().then(function processText({ done, value }) {
                   if (done) {
                       return;
                   }
                 let chunk = partialData + decoder.decode(value, { stream: true });
                 partialData = '';
                 let lines = chunk.split('\r\n');
                 for (let i = 0; i < lines.length - 1; i++) {
                     if (lines[i] === '--frame') {
                         if (chunks.length > 0) {
                             let blob = new Blob(chunks, { type: 'image/jpeg' });
                             const url = URL.createObjectURL(blob);
                             videoElement.src = url;
                             chunks = [];
                         }
                     } else {
                         chunks.push(new Uint8Array(Buffer.from(lines[i] + '\r\n', 'utf-8')));
                     }
                 }
                 partialData = lines[lines.length - 1];
                 return reader.read().then(processText);
               });
          })
          .catch(error => console.error('Error fetching video stream:', error));
    }
    // Call fetchVideoStream function when page loads
    window.onload = fetchVideoStream;
  </script>
</body>
</html>
Program Explanation:
    This HTML file creates a basic webpage with a video element (<video>).
     The JavaScript code fetches the video stream from the server (/video endpoint) using the
      Fetch API.
     It processes the response stream as text, splitting it into individual JPEG frames.
     As each frame is received, it's displayed in the video element by creating a blob URL for the
      JPEG image and setting it as the source of the video element.
Output :
Conclusion :
This mini-project demonstrates how to build a simple video streaming application using RTSP and
Flask. It serves as a foundation for more advanced video streaming projects and applications.
Feel free to explore and extend this project further by adding features such as authentication,
multiple camera support, or real-time video processing.