.mp4 file is not playing in Django template and FireFox or Chrome

0

I can save live RTSP video stream in .mp4 but when I run saved .mp4 video in Django template or Firefox or Chrome browser or VLC, video is not playing in ubuntu. I think I have a compatible issue problem in .mp4. Furthermore, I want to show and play .mp4 saved file in Django.

I have a two IP camera which provides a live RTSP video stream.

self.input_stream---> rtsp://admin:Admin123@192.168.1.208/user=admin_password=Admin123_channel=0channel_number_stream=0.sdp

self.input_stream---> rtsp://Admin:@192.168.1.209/user=Admin_password=_channel=0channel_number_stream=0.sdp

Python 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] on linux,

Django==3.1.2

I am implementing this code in difference Ubuntu PCs

Ubuntu = 18.04 and 20.04

opencv-contrib-python==4.4.0.46

opencv-python==4.4.0.46

ffmpeg version 4.2.4-1ubuntu0.1 Copyright (c) 2000-2020 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-10ubuntu2)

I had tried different fourcc to save .mp4 but below fourcc work perfectly in Ubuntu.

fourcc = cv2.VideoWriter_fourcc(*'mp4v')

class ffmpegStratStreaming(threading.Thread):
    def __init__(self, input_stream=None, output_stream=None, camera=None, *args, **kwargs):
        self.input_stream = input_stream
        self.output_stream = output_stream
        self.camera = camera
        super().__init__(*args, **kwargs)

    def run(self):
        try:vs = cv2.VideoCapture(self.input_stream)
            fps_rate = int(vs.get(cv2.CAP_PROP_FPS))
            ##############################
            ##############################  
            # ~ print('fps rate-->', fps_rate,'camera id-->' ,str(self.camera.id))
            # ~ vs.set(cv2.CAP_PROP_POS_FRAMES,50)  #Set the frame number to be obtained
            # ~ print('fps rate-->', fps_rate,'camera id-->' ,str(self.camera.id),' ####### ')
            
            # initialize the video writer (we'll instantiate later if need be)
            writer = None

            # initialize the frame dimensions (we'll set them as soon as we read
            # the first frame from the video)
            W = None
            H = None    
            # start the frames per second throughput estimator
            fps = FPS().start()

            #  saving frame in avi video format
            video_file_count = 0
            start_time = time.time()

            while True:
                try:
                    # grab the next frame and handle if we are reading from either
                    # VideoCapture or VideoStream
                    
                    frame_init = vs.read()
                    frame = frame_init[1] if self.input_stream else frame_init
                    
                    # if frame is can't read correctly ret is False
                    while frame_init[0] == False:
                        print("Can't receive frame. Retrying ...")
                        vs.release()
                        vs = cv2.VideoCapture(self.input_stream)                                                                              
                        frame_init = vs.read()
                        frame = frame_init[1] if self.input_stream else frame_init

                    # if we are viewing a video and we did not grab a frame then we
                    # have reached the end of the video
                    if self.input_stream is not None and frame is None:
                        break

                    # resize the frame to have a maximum width of 500 pixels (the
                    # less data we have, the faster we can process it), then convert
                    # the frame from BGR to RGB for dlib
                    frame = imutils.resize(frame, width=500)        
                    
                    
                    #<---------------------- Start of  writing a video to disk ------------------------->                   
                    minute = 1
                    second  = 60
                    minite_to_save_video = int(minute) * int(second)

                
                    # if we are supposed to be writing a video to disk, initialize
                    if time.time() - start_time >= minite_to_save_video or  video_file_count == 0 :
                        ## where H = heigth, W = width, C = channel 
                        H, W, C = frame.shape
                        video_file_count += 1
                        start_time = time.time()
                        output_save_directory = self.output_stream+str(video_file_count)+'.mp4'
                        # fourcc = cv2.VideoWriter_fourcc(*"MJPG")
                        # fourcc = cv2.VideoWriter_fourcc(*'XVID')
                        # fourcc = cv2.VideoWriter_fourcc(*'X264')
                        # fourcc = cv2.VideoWriter_fourcc(*'MP4V')

                        
                        # fourcc = cv2.VideoWriter_fourcc(*'FMP4')

                        # fourcc = cv2.VideoWriter_fourcc(*'avc1')


                        # fourcc = cv2.VideoWriter_fourcc('M','J','P','G')

                        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
                        # fourcc = cv2.VideoWriter_fourcc(*'mp3v')
                        # fourcc = 0x00000021
                        print(fourcc, type(fourcc),'ffffffff')
                        # a = int(vs.get(cv2.CAP_PROP_FOURCC))
                        # print(a,type(a),'  aaaaaaaa' )

                        # writer = skvideo.io.FFmpegWriter(output_save_directory, outputdict={
                        #   '-vcodec': 'libx264', '-b': '300000000'
                        # })
                        
                        # writer = skvideo.io.FFmpegWriter(self.output_stream, outputdict={'-r': '120', '-c:v': 'libx264', '-crf': '0', '-preset': 'ultrafast', '-pix_fmt': 'yuv444p'})
                        
                        writer = cv2.VideoWriter(output_save_directory, fourcc ,20.0,( int(W), int(H) ), True)
                        
                        
                        # ~ The cv2.VideoWriter requires five parameters:    

                    # check to see if we should write the frame to disk
                    if writer is not None:                          
                        try:
                            writer.write(frame)
                        except Exception as e:
                            print('Error in writing video output---> ', e)
                            
                    #<---------------------- end of  writing a video to disk ------------------------->

                    # show the output frame
                    # cv2.imshow("Frame", frame)
                    # key = cv2.waitKey(1) & 0xFF

                    # if the `q` key was pressed, break from the loop
                    # if key == ord("q"):
                    #   break

                    # increment the total number of frames processed thus far and
                    # then update the FPS counter
                    totalFrames += 1
                    fps.update()
                except Exception as e:
                    print('Error in main while loop--> ', e)

            # stop the timer and display FPS information
            fps.stop()

            # check to see if we need to release the video writer pointer
            # if writer is not None:
            #   writer.release()

            # if we are not using a video file, stop the camera video stream
            # if not self.input_stream:
            #   vs.stop()

            # otherwise, release the video file pointer
            # else:
            #   vs.release()

            # close any open windows
            # cv2.destroyAllWindows()
        except Exception as e:
            print(e, '333333333333333333333333333')

My Django template code

{% block main %}
<div class="row">
  {% if folders|length == 0 %}
    <div class="col-md-12 text-center">
      <h6 class="card-title">There are no files in this directory.</h6>
    </div>
  {% else %}
    {% for folder in folders %}
      <div class="col-md-3 text-center">
          <div class="card-block">
            <video id="my_video_{{forloop.counter}}" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"  muted data-setup='{ "controls": true, "autoplay": false, "preload": "auto", "seek": true  }' />
                <source src="{% get_media_prefix %}camera-feed/video-saved/{{pk}}/{{parent}}/{{folder}}" type="video/mp4">
            </video>
            <h6 class="card-title">{{folder}}</h6>
          </div>
      </div>
    {% endfor %}
  {% endif %}
</div>
{% endblock %}

Function in view.py to see saved .mp4 video in Django template. Video is saved at local folder.

def CameraVideos(request, pk, folder):
    dirpath = settings.MEDIA_ROOT + '/camera-feed/video-saved/' + str(pk) + '/' + folder
    folders = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)
    data = []
    for file in folders:
        if not file.name.startswith('.'):
            data.append(file.name)
    return render(request, "home/camera_video.html", {'folders': data, 'pk': pk, 'parent': folder})
python
django
opencv
ubuntu
ffmpeg

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0