Newest 'ffmpeg' Questions - Stack Overflow

http://stackoverflow.com/questions/tagged/ffmpeg

Les articles publiés sur le site

  • FFmpeg : high quality animated GIF ? [closed]

    26 juin, par David Hope

    I'm generating animated a GIF from a video on my server.

    The generated GIF is not really high quality and it looks like the pixels are huge.

    Example:

    example GIF

    This is how I generate the GIF:

    /usr/bin/ffmpeg -i video.mkv -vf scale=500:-1 -t 10 -r 10 image.gif
    

    I did a search on Google and came across this:

    /usr/bin/ffmpeg -i video.mkv -r 20 -f image2pipe -vcodec ppm - | convert -delay 5 - output.gif
    

    But the command above doesn't do anything and no output.gif is being generated at all.

    There are some tutorials that I came across but none of them worked for me and some of them involve using ImageMagick which I dont have access to.

    Could someone please let me know if there is a clear way to generate a high-quality GIF using FFmpeg?

  • Use an IP-camera with webRTC

    26 juin, par Minz

    I want to use an IP camera with webrtc. However webrtc seems to support only webcams. So I try to convert the IP camera's stream to a virtual webcam.

    I found software like IP Camera Adapter, but they don't work well (2-3 frames per second and delay of 2 seconds) and they work only on Windows, I prefer use Linux (if possible).

    I try ffmpeg/avconv:

    • firstly, I created a virtual device with v4l2loopback (the command was: sudo modprobe v4l2loopback). The virtual device is detected and can be feed with a video (.avi) with a command like: ffmpeg -re -i testsrc.avi -f v4l2 /dev/video1

    • the stream from the IP camera is available with: rtsp://IP/play2.sdp for a Dlink DCS-5222L camera. This stream can be captured by ffmpeg.

    My problem is to make the link between these two steps (receive the rstp stream and write it to the virtual webcam). I tried ffmpeg -re -i rtsp://192.168.1.16/play2.sdp -f video4linux2 -input_format mjpeg -i /dev/video0 but there is an error with v4l2 (v4l2 not found).

    Does anyones has an idea how to use an IP camera with webRTC?

  • cv2/ffmpeg "grabFrame packet read max attempts exceeded" error after exactly reading certain number of frames

    26 juin, par banjaxing

    I am using OpenCV to extract frames from videos, run a segmentation AI model, and save the frames and masks to a folder. When I run my code to extract the frame from I encounter the error "grabFrame packet read max attempts exceeded" after processing a certain number of frames. This issue occurs consistently for the same videos across multiple environments.

    Error message:

    [ WARN:0@379.898] global cap_ffmpeg_impl.hpp:1541 grabFrame packet read max attempts exceeded, if your video have multiple streams (video, audio) try to increase attempt limit by setting environment variable OPENCV_FFMPEG_READ_ATTEMPTS (current value is 10000)
    

    Minimum Reproducible Example

    import os
    import cv2
    
    videofilename = "test.mp4"
    capture = cv2.VideoCapture(videofilename)
    frameNum = 0
    
    createfolder = os.getcwd() + '/' + videofilename.split(".")[0] + '/'
    if not os.path.exists(createfolder):
        os.makedirs(createfolder)
        os.makedirs(createfolder + "/frames/")
    
    while True:
        success, frame = capture.read()
        if success is False:
            break
        frameNum += 1
        framedownloadname = videofilename.split(".")[0] + '-fr' + str(frameNum) + '.jpg'
        framedownloadloc = createfolder + '/frames/' + framedownloadname
        print(framedownloadloc)
        cv2.imwrite(framedownloadloc, frame)
        img = cv2.imread(framedownloadloc)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
    capture.release()
    

    As suggested in error, I increased the OPENCV_FFMPEG_READ_ATTEMPTS env variable up to 10000. However, this seems to have little to no effect on the number of frames before the error appears.

  • PHP convert any video to MP4 using ffmpeg

    26 juin, par Dilak

    I have a website in which I allow users to upload videos. But with the HTML5 tag video, only MP4 videos are allowed

    So, I want to convert any type of videos that the users upload to MP4 and then add the path in my database.

    I tried something, changing the file extension to MP4 but it didn't work. I've read something about ffmepg but I can't figure out how to use it.

    Here is my PHP script where I change the file extension and then add the path in my data base, please how can I convert the video correctly, what should I add/change?

    <?php 
        if(file_exists($_FILES['media-vid']['tmp_name']) && is_uploaded_file($_FILES['media-vid']['tmp_name']))
        {
            $targetvid = md5(time());
            $target_dirvid = "videos/";
            $target_filevid =  $targetvid.basename($_FILES["media-vid"]["name"]);
            $uploadOk = 0;
            $videotype = pathinfo($target_filevid,PATHINFO_EXTENSION);
            
            $video_formats = array(
                "mpeg",
                "mp4",
                "mov",
                "wav",
                "avi",
                "dat",
                "flv",
                "3gp"
            );
            foreach ($video_formats as $valid_video_format)
            {
                if (preg_match("/$videotype/i", $valid_video_format)) 
                {
                    $target_filevid = $targetvid . basename($_FILES["media-vid"] . ".mp4");
                    $uploadOk = 1;
                    break;
                } 
                else 
                {
                    //if it is an image or another file format it is not accepted
                    $format_error = "Invalid Video Format!";
                }
            }
    
            if ($_FILES["media-vid"]["size"] > 5000000000000)
            {
                $uploadOk = 0;
                echo "Sorry, your file is too large.";
            }
    
            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0 && isset($format_error))
            {
                echo "Sorry, your video was not uploaded.";
                // if everything is ok, try to upload file
            }
            else if ($uploadOk == 0) 
            {
                echo "Sorry, your video was not uploaded.";
            }
            else
            {
                $target_filevid = strtr($target_filevid,
                'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
                'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
                $target_filevid = preg_replace('/([^.a-z0-9]+)/i', '_', $target_filevid);
                if (!move_uploaded_file($_FILES["media-vid"]["tmp_name"], $target_dirvid. $target_filevid))
                {
                    echo "Sorry, there was an error uploading your file. Please retry.";
                }
                else
                {
                    $vid= $target_dirvid.$target_filevid;
                    $nbvid = 1;
                }
            }
        }
    ?>
    

    Thank you.

  • Create playable video with audio for vscode using ffmpeg [closed]

    25 juin, par Camilo Martínez M.

    I am trying to create a function which adds an audio stream to a silent video using ffmpeg. According to this, in order to be able to play videos in vscode, we need to...

    make sure that both the video and audio track's media formats are supported. Many .mp4 files for example use H.264 for video and AAC audio. VS Code will be able to play the video part of the mp4, but since AAC audio is not supported there won't be any sound. Instead you need to use mp3 for the audio track.

    The following function already produces a playable video in vscode, but the audio is not played, even though I am using the libmp3lame encoder, which is the MP3 encoder (according to this).

    def add_audio_to_video(
        silent_video_path: Path,
        audio_source_path: Path,
        output_path: Path,
        audio_codec: Literal["libmp3lame", "aac"] = "libmp3lame",
        fps: int | None = None,
    ) -> None:
        """Combine a video file with an audio stream from another file using ffmpeg.
    
        Args:
            silent_video_path (Path): Path to the video file without audio.
            audio_source_path (Path): Path to the file containing the audio stream.
            output_path (Path): Path for the final video file with audio.
            audio_codec (Literal["libmp3lame", "aac"]): Codec to use for the audio stream.
                Defaults to "libmp3lame" (MP3). Use "aac" for AAC codec. **Note**: MP3 is compatible
                with vscode's video preview.
            fps (int): Frames per second for the output video. Defaults to 30.
    
        Todo:
            * [ ] TODO: Not working to be able to play audio in vscode
        """
        # TODO: Not working to be able to play audio in vscode
        if not check_ffmpeg_installed():
            raise RuntimeError("ffmpeg is required to add audio to the video.")
    
        # If fps is not provided, try to get it from the silent video
        if not fps:
            video_info = get_video_info(silent_video_path)
            if video_info and video_info.fps:
                fps = int(video_info.fps)
            else:
                logger.warning(
                    "fps not provided and could not be determined from the video. Using default 30.",
                )
                fps = 30
    
        logger.info(f"Adding audio from '{audio_source_path}' to '{silent_video_path}'...")
    
        cmd = [
            "ffmpeg",
            "-y",  # Overwrite output file if it exists
            "-i",
            str(silent_video_path),  # Input 0: Silent video
            "-i",
            str(audio_source_path),  # Input 1: Audio source
            "-c:v",
            "libx264",
            "-profile:v",
            "baseline",
            "-level",
            "3.0",
            "-pix_fmt",
            "yuv420p",
            "-r",
            str(fps),
            "-c:a",
            audio_codec,
            "-b:a",
            "192k",  # Set a reasonable audio bitrate for quality
            "-map",
            "0:v:0",  # Map video stream from input 0
            "-map",
            "1:a:0?",  # Map audio stream from input 1 (optional)
            "-shortest",  # Finish encoding when the shortest input stream ends
            str(output_path),
        ]
    
        try:
            subprocess.run(cmd, check=True, capture_output=True, text=True)  # noqa: S603
            logger.success(f"Final video with audio saved to {output_path}")
        except subprocess.CalledProcessError as e:
            logger.error("ffmpeg command failed to add audio.")
            logger.error(f"ffmpeg stderr:\n{e.stderr}")
            raise
    

    Has anyone faced something similar before?