Newest 'ffmpeg' Questions - Stack Overflow

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

Les articles publiés sur le site

  • define the input FPS of a stream using ffmpeg-python

    28 mars, par tamirg

    Im creating an HLS playlist using ffmpeg, reading my input from an RTSP stream.

    When probing the RTSP stream, i get an FPS which is not the true FPS, and i want to "tell" ffmpeg the actual real FPS.

    In the command line, im using the -r flag, which works fine:

    ffmpeg -rtsp_transport tcp -r 18 -i rtsp://localhost:554/test -b:v 100KB -vf format=yuvj420p  -c:a copy -hls_time 2 -hls_list_size 10 -hls_flags delete_segments -start_number 1 output.m3u8
    

    I noticed that flag must come before the input param. If i use the -r after, it simply doesnt work.

    In ffmpeg-python, i dont see any option to do so. And using it as a flag to the .input() function, does not work.

    How can i use the -r flag with ffmpeg-python?

  • AWS Lambda failed to resolve hostname in child_process spawn

    28 mars, par warly

    i'm trying to get ffmpeg working in AWS Lambda reading from and writing to S3. I crawled through dozens of aws documentations, stackoverflow questions and blog posts. All do it slightly different, but in the end none of them worked for me. So I hope to find help here :) I sticked to the tutorial from InPlainEnglish: https://plainenglish.io/community/automated-video-processing-with-aws-lambda-and-ffmpeg-2834b7

    The ffprobe command does work, so ffmpeg is callable. But when calling ffmpeg within a child_process.spawn command i get the error Failed to resolve hostname my-bucket.s3.eu-central-1.amazonaws.com: System error

    export const handler = async (event) => {
        const s3 = new S3Client({});
        const bucket = event.Records[0].s3.bucket.name;
        const sourceKey = event.Records[0].s3.object.key;
        const sourceURL = await getSignedUrl(s3, new GetObjectCommand({
            Bucket: bucket,
            Key: sourceKey,
        }), {
            expiresIn: 900,
        });
    
        const tmpFilePath = 'tmp/video.mp4';
        const { convertOut } = await commander(`/opt/ffmpeg -i "${sourceURL}" -vf scale=1080:-2,format=yuv420p ${tmpFilePath}`);
    
        return {
            statusCode: 200,
            body: {
                result: JSON.stringify(convertOut),
            },
        };
    };
    

    the signed url is fine. I've tested it with vanilla js await fetch(sourceURL) and it returned the file. The problem is that for some reason the child_process has no internet access.

    if anyone is able to point me in the right direction i would appreciate it :D

    Full error message:

    {
      "errorType": "Error",
      "errorMessage": "Command failed: /opt/ffmpeg -i \"https://my-bucket.s3.eu-central-1.amazonaws.com/original/Testvideo.MOV?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential={redacted}&X-Amz-Date=20240209T212255Z&X-Amz-Expires=900&X-Amz-Security-Token={redacted}&X-Amz-Signature={redacted}&X-Amz-SignedHeaders=host&x-id=GetObject\" -vf scale=1080:-2,crop=1080:1350,format=yuv420p tmp/video.mp4\nffmpeg version 6.1-static https://johnvansickle.com/ffmpeg/  Copyright (c) 2000-2023 the FFmpeg developers\n  built with gcc 8 (Debian 8.3.0-6)\n  configuration: --enable-gpl --enable-version3 --enable-static --disable-debug --disable-ffplay --disable-indev=sndio --disable-outdev=sndio --cc=gcc --enable-fontconfig --enable-frei0r --enable-gnutls --enable-gmp --enable-libgme --enable-gray --enable-libaom --enable-libfribidi --enable-libass --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libvorbis --enable-libopus --enable-libtheora --enable-libvidstab --enable-libvo-amrwbenc --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libdav1d --enable-libxvid --enable-libzimg\n  libavutil      58. 29.100 / 58. 29.100\n  libavcodec     60. 31.102 / 60. 31.102\n  libavformat    60. 16.100 / 60. 16.100\n  libavdevice    60.  3.100 / 60.  3.100\n  libavfilter     9. 12.100 /  9. 12.100\n  libswscale      7.  5.100 /  7.  5.100\n  libswresample   4. 12.100 /  4. 12.100\n  libpostproc    57.  3.100 / 57.  3.100\n[tcp @ 0x141950d0] Failed to resolve hostname my-bucket.s3.eu-central-1.amazonaws.com: System error\n[in#0 @ 0x14190900] Error opening input: Input/output error\nError opening input file https://my-bucket.s3.eu-central-1.amazonaws.com/original/Testvideo.MOV?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential={redacted}&X-Amz-Date=20240209T212255Z&X-Amz-Expires=900&X-Amz-Security-Token={redacted}&X-Amz-Signature={redacted}&X-Amz-SignedHeaders=host&x-id=GetObject.\nError opening input files: Input/output error\n",
      "trace": [
        "Error: Command failed: /opt/ffmpeg -i \"https://my-bucket.s3.eu-central-1.amazonaws.com/original/Testvideo.MOV?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential={redacted}&X-Amz-Date=20240209T212255Z&X-Amz-Expires=900&X-Amz-Security-Token={redacted}&X-Amz-Signature={redacted}&X-Amz-SignedHeaders=host&x-id=GetObject\" -vf scale=1080:-2,crop=1080:1350,format=yuv420p tmp/video.mp4",
        "ffmpeg version 6.1-static https://johnvansickle.com/ffmpeg/  Copyright (c) 2000-2023 the FFmpeg developers",
        "  built with gcc 8 (Debian 8.3.0-6)",
        "  configuration: --enable-gpl --enable-version3 --enable-static --disable-debug --disable-ffplay --disable-indev=sndio --disable-outdev=sndio --cc=gcc --enable-fontconfig --enable-frei0r --enable-gnutls --enable-gmp --enable-libgme --enable-gray --enable-libaom --enable-libfribidi --enable-libass --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libvorbis --enable-libopus --enable-libtheora --enable-libvidstab --enable-libvo-amrwbenc --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libdav1d --enable-libxvid --enable-libzimg",
        "  libavutil      58. 29.100 / 58. 29.100",
        "  libavcodec     60. 31.102 / 60. 31.102",
        "  libavformat    60. 16.100 / 60. 16.100",
        "  libavdevice    60.  3.100 / 60.  3.100",
        "  libavfilter     9. 12.100 /  9. 12.100",
        "  libswscale      7.  5.100 /  7.  5.100",
        "  libswresample   4. 12.100 /  4. 12.100",
        "  libpostproc    57.  3.100 / 57.  3.100",
        "[tcp @ 0x141950d0] Failed to resolve hostname my-bucket.s3.eu-central-1.amazonaws.com: System error",
        "[in#0 @ 0x14190900] Error opening input: Input/output error",
        "Error opening input file https://my-bucket.s3.eu-central-1.amazonaws.com/original/Testvideo.MOV?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential={redacted}&X-Amz-Date=20240209T212255Z&X-Amz-Expires=900&X-Amz-Security-Token={redacted}&X-Amz-Signature={redacted}&X-Amz-SignedHeaders=host&x-id=GetObject.",
        "Error opening input files: Input/output error",
        "",
        "    at ChildProcess.exithandler (node:child_process:422:12)",
        "    at ChildProcess.emit (node:events:518:28)",
        "    at maybeClose (node:internal/child_process:1105:16)",
        "    at ChildProcess._handle.onexit (node:internal/child_process:305:5)"
      ]
    }
    enter code here
    

    Update: Turns out it is not S3 or internet, but the child_process which does not seem to have internet access. I've update my description above.

  • NodeJS stream MKV as MP4 video

    28 mars, par SirMissAlot

    I'm trying to stream MKV video as MP4 on the fly with out saving the converted file

    first I've tried without conversion:

    public async streamById(req: Request, res: Response) {
        const movieId = req.params.id;
        const movie = await MovieModel.findById(movieId);
        if (!movie) {
          return res.status(404).send({ message: 'Movie not found' });
        }
    
        const filePath = movie.path;
    
        const stat = fs.statSync(filePath);
        const fileSize = stat.size;
        const range = req.headers.range;
    
        if (range) {
          const parts = range.replace(/bytes=/, '').split('-');
          const start = parseInt(parts[0], 10);
          const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
    
          const chunksize = end - start + 1;
          const file = fs.createReadStream(filePath, { start, end });
          const head = {
            'Content-Range': `bytes ${start}-${end}/${fileSize}`,
            'Accept-Ranges': 'bytes',
            'Content-Length': chunksize,
            'Content-Type': 'video/mp4',
          };
    
          res.writeHead(206, head);
          file.pipe(res);
        } else {
          const head = {
            'Content-Length': fileSize,
            'Content-Type': 'video/mp4',
          };
          res.writeHead(200, head);
          fs.createReadStream(filePath).pipe(res);
        }
      }
    

    which is working but without audio

    With ffmpeg I'm getting error : "Error during conversion: Output stream closed" its not a

    const command = ffmpeg(file)
        .format('mp4')
        .audioCodec('aac')
        .videoCodec('libx264')
        .outputOptions('-movflags frag_keyframe+empty_moov')
        .outputOptions('-preset veryfast')
        .on('error', (err: any) => {
          console.error('Error during conversion:', err.message);
          res.end();
        })
        .on('end', () => {
          console.log('Conversion complete ');
          res.end();
        });
    
      // Pipe ffmpeg output directly to the response
      command.pipe(res, { end: true });
    
  • FFMPEG fast quality video encoding without quality loss & less storage occupancy (maybe using GPU)

    27 mars, par Diwash Mainali

    I Have written a go code but it is slow and the video compression rate is also not that impressive. I am new to FFMPEG and my entire project depends on FFMPEG. I have tried different video codecs like vp9, h264, h265, NVENC, AV1, etc. All of them were too slow (maybe I am not good enough to optimize it). My project is based on Go and the current codec that I am using is libx264. Can anyone help me optimize the video encoding part of my project.

    Libx264:

    func encodeVideo(fileName, bitrate, crf, preset, resolution string) *exec.Cmd {
        return exec.Command("C:\\ffmpeg-6.1-full_build\\bin\\ffmpeg",
            "-i", "./userUploadDatas/videos/"+fileName,
            "-c:v", "libx264",
            "-b:v", bitrate,
            "-crf", crf,
            "-preset", preset,
            "-vf", "scale="+resolution,
            "./userUploadDatas/videos/"+fileName+"_encoded"+".mp4")
    }
    

    Please provide static value of each parameters. Any codec will work for me as long as it is fast, occupies less space & doesn't loose spaces.

    The problems I have faces with different codecs are:

    1. NVENC: Fast but the size of video is doubled & loss of video quality.
    2. libx264: Best I can find currently, but is slow.
    3. h264, h265: Occupies more space
    4. Av1 & vp9: Was too slow and wasn't able to encode 30sec video in 1hrs.

    The specs of hardware that I am using is Ryzen7 5000 series CPU, NVIDIA RTX 3050 Ti Laptop GPU.

  • Batch reduce bitrate and size of mp3 audio files with ffmpeg

    27 mars, par Wes Modes

    I was looking for a way to batch reduce mp3 bitrate on my sizable collection of mp3 files. It was surprising difficult given that this must be a super common thing to want to do.

    In fact, there are dozens, maybe hundreds, of posts from people asking how to do it, and dozens of utilities available for varying amounts of money that claim to do just that. Looking around and trying some of the free software, I was surprised that none made the task of batch converting/adjustment easy.

    If I wanted to convert a single file, I'm told this is a decent way to do it:

    ffmpeg -y -loglevel "error" -i "my_music_file.mp3" -acodec libmp3lame  -ab $BITRATE "my_music_file_new.mp3"
    

    (Though I'd prefer if the file was changed in place and resulted in the same name.)

    I need a simple bash script using ffmpeg that will recursively go through my music directory and change the bitrate of my mp3 files.