Newest 'libx264' Questions - Stack Overflow

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

Les articles publiés sur le site

  • Getting Error message Unknown encoder 'libx264' , any help appreciated

    16 janvier 2022, par Alex.Foster

    I am trying to compress videos files to a target size within python using ffmpeg-python for an A level project as part of my coursework, I keep getting this error saying it doesn't know the encoder. Not sure what I'm meant to do as this is literally an entirely new space to me. Am I meant to have installed the codec or something, or is there an alternative I can use?

    import os, ffmpeg
    ##import section:this part is where I import all of the modules I will use
    import  tkinter
    import shutil
    from tkinter import filedialog
    import os
    
    
    def fileSelect():                                                                           #start of fileSelect function
        global startingLocation                                                                 #declares startingLocation as global variable
        global originalName                                                                     #declares originalName as global variable
        global fileType                                                                         #declares fileType as global variable
        startingLocation = filedialog.askopenfilename(initialdir="/", title="Select file",      #tkinter function that opens file explorer, lets user select file saves the file path as a variable
                        filetypes=(("video files", "*.mp4"),("images", "*.jpg*")))
        originalName = os.path.basename(startingLocation)                                       #os function that gets the actaul file name from the path string
        print (originalName)                                                                    #print statement to check if originalName has been found
        fileType = startingLocation.split('.')                                                  #splits original name where any full stop in found and saves array as variable
        fileType = fileType[-1]                                                                 #changes variable to have the str value of the final item in the array; the file type
        fileType = '.' + fileType                                                               #adds fullstop to the start of the file type so i dont have to repeatedly do it
        print (fileType)                                                                        #print statement to check file type is found correctly
    
    def outputSelect():                                                                         #start of outputSelect function
         global outputLocation                                                                  #declares outputLocation as global variable
         outputLocation = filedialog.askdirectory(initialdir="/", title="Select folder")        #tkinter function that opens file explorer, lets the user select of folder as saves the folder path as a variable
    
    def fileNewName():                                                                          #start of fileNewName function
        global customName                                                                       #declares customName as global variable
        customName = input("Enter the end name of your file")                                   #simple code assigning user input to the custom name vairable
        customName = customName + fileType                                                      #add the fileType onto the end of the custom name
    
    def compress():                                                                             #start of compress function
        fileSelect()                                                                            #calls the fileSelect function
        outputSelect()                                                                          #calls the outputSelect function
        fileNewName()
        global src
        global dst                                                                           #calls the fileNewName function
        src = startingLocation                                                                  #assigns startingLocation str as src, so the shutil module is able to use it in a cleaner way
        dst = outputLocation                                                                    #assigns outputLocation dst as src, so the shutil module is able to use it in a cleaner way
        shutil.copy(src, dst)                                                                   #shutil command that copies the file from src to dst
        src = outputLocation + '/' + originalName                                               #reassigns src as the location of the file copy
        dst = outputLocation + '/' + customName                                                 #reassigns dst as the location of the file copy but with a new name
        shutil.move(src,dst)
    
    
    def compress_video(video_full_path, output_file_name, target_size):
        # Reference: https://en.wikipedia.org/wiki/Bit_rate#Encoding_bit_rate
        min_audio_bitrate = 32000
        max_audio_bitrate = 256000
    
        probe = ffmpeg.probe(video_full_path)
        # Video duration, in s.
        duration = float(probe['format']['duration'])
        # Audio bitrate, in bps.
        audio_bitrate = float(next((s for s in probe['streams'] if s['codec_type'] == 'audio'), None)['bit_rate'])
        # Target total bitrate, in bps.
        target_total_bitrate = (target_size * 1024 * 8) / (1.073741824 * duration)
    
        # Target audio bitrate, in bps
        if 10 * audio_bitrate > target_total_bitrate:
            audio_bitrate = target_total_bitrate / 10
            if audio_bitrate < min_audio_bitrate < target_total_bitrate:
                audio_bitrate = min_audio_bitrate
            elif audio_bitrate > max_audio_bitrate:
                audio_bitrate = max_audio_bitrate
        # Target video bitrate, in bps.
        video_bitrate = target_total_bitrate - audio_bitrate
    
        i = ffmpeg.input(video_full_path)
        ffmpeg.output(i, os.devnull,
                      **{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 1, 'f': 'mp4'}
                      ).overwrite_output().run()
        ffmpeg.output(i, output_file_name,
                      **{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 2, 'c:a': 'aac', 'b:a': audio_bitrate}
                      ).overwrite_output().run()
    
    compress()
    compress_video(dst, outputLocation, 3 * 1000)
    
  • How to resolve "ERROR : libx264 not found" ?

    13 janvier 2022, par davidvarghese

    I needed to install ffmpeg with libx264 support for enabling H.264 encoding . I installed libx264 successfully using the below script with toolchains available in android-ndk-r9d .

     #!/bin/bash
     NDK=~/android-ndk-r9d
     SYSROOT=$NDK/platforms/android-8/arch-arm/
     TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64
     function build_one
     {
     ./configure \
     --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- \
     --sysroot="$SYSROOT" \
     --host=arm-linux \
     --enable-pic \
     --enable-shared \
     --disable-cli
     make clean
     make
     make install
     }
     build_one 
    

    Now I wanted to build ffmpeg with libx264 support . I used the below script with --enable-libx264 , --enable-nonfree , --enable-gpl options as in the below script .

    #!/bin/bash
    NDK=~/android-ndk-r9d
    SYSROOT=$NDK/platforms/android-8/arch-arm/
    TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64
    function build_one
    {
    ./configure \
    --prefix=$PREFIX \
    --enable-shared \
    --enable-nonfree \
    --enable-gpl \
    --enable-libx264 \
    --disable-doc \
    --disable-ffmpeg \
    --disable-ffplay \
    --disable-ffprobe \
    --disable-ffserver \
    --disable-avdevice \
    --disable-doc \
    --disable-symver \
    --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- \
    --target-os=linux \
    --arch=arm \
    --enable-cross-compile \
    --sysroot=$SYSROOT \
    --extra-cflags="-Os -fpic $ADDI_CFLAGS" \
    --extra-ldflags="$ADDI_LDFLAGS" \
    $ADDITIONAL_CONFIGURE_FLAG
    make clean
    make
    make install
    }
    CPU=arm
    PREFIX=$(pwd)/android/$CPU
    ADDI_CFLAGS="-marm"
    build_one
    

    But when I run the script I'm getting error "ERROR: libx264 not found" .

    I suppose ffmpeg is not able to figure out the installed location of libx264 . After libx264 installation I have libx264.so file in /usr/local/lib executable at /usr/local/bin and header files at /usr/local/include directories .

    What all changes do I need to make to the ffmpeg build script in-order to make it detect libx264?

    Note : I am using Ubuntu 12.04(64 bit) for cross compiling .

  • How to get FFMPEG to encode H264 using libx264 ?

    12 décembre 2021, par Basit Anwer

    FFMPEG encode example fails to create a H264 video. MPEG1 works fine though.

    Pasting the code here as well

    
         * @file
         * video encoding with libavcodec API example
         *
         * @example encode_video.c
         */
        #include 
        #include 
        #include 
        #include avcodec.h>
        #include opt.h>
        #include imgutils.h>
        static void encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt,
                           FILE *outfile)
        {
            int ret;
            /* send the frame to the encoder */
            if (frame)
                printf("Send frame %3"PRId64"\n", frame->pts);
            ret = avcodec_send_frame(enc_ctx, frame);
            if (ret < 0) {
                fprintf(stderr, "Error sending a frame for encoding\n");
                exit(1);
            }
            while (ret >= 0) {
                ret = avcodec_receive_packet(enc_ctx, pkt);
                if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                    return;
                else if (ret < 0) {
                    fprintf(stderr, "Error during encoding\n");
                    exit(1);
                }
                printf("Write packet %3"PRId64" (size=%5d)\n", pkt->pts, pkt->size);
                fwrite(pkt->data, 1, pkt->size, outfile);
                av_packet_unref(pkt);
            }
        }
    
        int main(int argc, char **argv)
        {
            const char *filename, *codec_name;
            const AVCodec *codec;
            AVCodecContext *c= NULL;
            int i, ret, x, y;
            FILE *f;
            AVFrame *frame;
            AVPacket *pkt;
            uint8_t endcode[] = { 0, 0, 1, 0xb7 };
            if (argc <= 2) {
                fprintf(stderr, "Usage: %s  \n", argv[0]);
                exit(0);
            }
            filename = argv[1];
            codec_name = argv[2];
            /* find the mpeg1video encoder */
            codec = avcodec_find_encoder_by_name(codec_name);
            if (!codec) {
                fprintf(stderr, "Codec '%s' not found\n", codec_name);
                exit(1);
            }
            c = avcodec_alloc_context3(codec);
            if (!c) {
                fprintf(stderr, "Could not allocate video codec context\n");
                exit(1);
            }
            pkt = av_packet_alloc();
            if (!pkt)
                exit(1);
            /* put sample parameters */
            c->bit_rate = 400000;
            /* resolution must be a multiple of two */
            c->width = 352;
            c->height = 288;
            /* frames per second */
            c->time_base = (AVRational){1, 25};
            c->framerate = (AVRational){25, 1};
            /* emit one intra frame every ten frames
             * check frame pict_type before passing frame
             * to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
             * then gop_size is ignored and the output of encoder
             * will always be I frame irrespective to gop_size
             */
            c->gop_size = 10;
            c->max_b_frames = 1;
            c->pix_fmt = AV_PIX_FMT_YUV420P;
            if (codec->id == AV_CODEC_ID_H264)
                av_opt_set(c->priv_data, "preset", "slow", 0);
            /* open it */
            ret = avcodec_open2(c, codec, NULL);
            if (ret < 0) {
                fprintf(stderr, "Could not open codec: %s\n", av_err2str(ret));
                exit(1);
            }
            f = fopen(filename, "wb");
            if (!f) {
                fprintf(stderr, "Could not open %s\n", filename);
                exit(1);
            }
            frame = av_frame_alloc();
            if (!frame) {
                fprintf(stderr, "Could not allocate video frame\n");
                exit(1);
            }
            frame->format = c->pix_fmt;
            frame->width  = c->width;
            frame->height = c->height;
            ret = av_frame_get_buffer(frame, 32);
            if (ret < 0) {
                fprintf(stderr, "Could not allocate the video frame data\n");
                exit(1);
            }
            /* encode 1 second of video */
            for (i = 0; i < 25; i++) {
                fflush(stdout);
                /* make sure the frame data is writable */
                ret = av_frame_make_writable(frame);
                if (ret < 0)
                    exit(1);
                /* prepare a dummy image */
                /* Y */
                for (y = 0; y < c->height; y++) {
                    for (x = 0; x < c->width; x++) {
                        frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
                    }
                }
                /* Cb and Cr */
                for (y = 0; y < c->height/2; y++) {
                    for (x = 0; x < c->width/2; x++) {
                        frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
                        frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
                    }
                }
                frame->pts = i;
                /* encode the image */
                encode(c, frame, pkt, f);
            }
            /* flush the encoder */
            encode(c, NULL, pkt, f);
            /* add sequence end code to have a real MPEG file */
            if (codec->id == AV_CODEC_ID_MPEG1VIDEO || codec->id == AV_CODEC_ID_MPEG2VIDEO)
                fwrite(endcode, 1, sizeof(endcode), f);
            fclose(f);
            avcodec_free_context(&c);
            av_frame_free(&frame);
            av_packet_free(&pkt);
            return 0;
        }
    

    The code fails at encode call and every avcodec_receive_packet call returns AVERROR(EAGAIN)

    What am i missing here?

  • ffmpeg configure ERROR : libx264 not found

    1er décembre 2021, par Dion

    I want to configure ffmpeg on Ubuntu 64 bit, but I get an error: "ERROR: libx264 not found". ffmpeg doesn’t see libx264! Before that, I successfully configure it in QNX and Windows. I prevented a known bug with --disable-opencl , but it did not help. In my project the libx264 should be static.

    libx264 configure:

    ../configure --prefix=x264 --disable-cli --enable-static --disable-opencl
    
    platform:      X86_64
    byte order:    little-endian
    system:        LINUX
    cli:           no
    libx264:       internal
    shared:        no
    static:        yes
    asm:           yes
    interlaced:    yes
    avs:           no
    lavf:          no
    ffms:          no
    mp4:           no
    gpl:           yes
    thread:        posix
    opencl:        no
    filters:       crop select_every
    lto:           no
    debug:         no
    gprof:         no
    strip:         no
    PIC:           no
    bit depth:     all
    chroma format: all
    

    it's OK! Confused only platform: X86_64

    FFmpeg configure:

    ../configure --target-os=linux --prefix=ffmpeg --disable-programs \
    --disable-ffplay --disable-ffprobe --disable-doc \ 
    --disable-htmlpages --disable-manpages --disable-podpages \ 
    --disable-txtpages --disable-avdevice --disable-postproc \
    --disable-network --disable-encoders --enable-encoder=libx264 \
    --disable-decoders --enable-decoder=h264 --disable-hwaccels \
    --disable-muxers --enable-muxer=matroska --disable-demuxers \
    --disable-parsers --enable-parser=h264 --enable-gpl \
    --enable-libx264 \
    --extra-ldflags=-L../x264/lib \
    --extra-cflags=-I../x264/include
    
        ERROR: libx264 not found
    

    Paths exactly correct!

    if delete --enable-libx264:

    install prefix            ffmpeg
    source path               /home/osuser/develop/libs/source/ffmpeg-3.4.2
    C compiler                gcc
    C library                 glibc
    ARCH                      x86 (generic)
    big-endian                no
    runtime cpu detection     yes
    standalone assembly       yes
    x86 assembler             nasm
    ...
    

    This is what worries me... Why x86?

    ARCH x86 (generic)

    x86 assembler nasm

    Maybe this is the problem? How to configure ffmpeg in x86_64? --arch=x86_64 not help!

    UPDATE: The problem is fixed, when configure libx264, need to add --enable-pic

  • build x264 failed on apple M1, No working C compiler found

    29 novembre 2021, par louxiu
    1. Apple M1, clang
    Apple clang version 13.0.0 (clang-1300.0.29.3)
    Target: arm64-apple-darwin21.1.0
    Thread model: posix
    InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
    
    1. x264 version x264-snapshot-20191217-2245

    2. configure

     ./configure --prefix=/tmp/  --enable-static
    
    1. config.log
    checking for -Werror=unknown-warning-option... yes
    checking for -mdynamic-no-pic... yes
    x264 configure script
    Command line options: "--prefix=/tmp/" "--enable-static"
    
    checking whether gcc works... no
    Failed commandline was:
    --------------------------------------------------
    gcc conftest.c  -Wall -I. -I$(SRCPATH) -mdynamic-no-pic -arch armv7  -Werror=unknown-warning-option    -lm -arch armv7 -o conftest
    ld: warning: ignoring file /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/13.0.0/lib/darwin/libclang_rt.osx.a, missing required architecture armv7 in file /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/13.0.0/lib/darwin/libclang_rt.osx.a (5 slices)
    ld: warning: ignoring file /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/lib/libm.tbd, missing required architecture armv7 in file /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/lib/libm.tbd (3 slices)
    ld: warning: ignoring file /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/lib/libSystem.tbd, missing required architecture armv7 in file /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/lib/libSystem.tbd (3 slices)
    ld: dynamic main executables must link with libSystem.dylib for architecture armv7
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    --------------------------------------------------
    Failed program was:
    --------------------------------------------------
    int main (void) {  return 0; }
    --------------------------------------------------
    DIED: No working C compiler found.