Newest 'libx264' Questions - Stack Overflow

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

Les articles publiés sur le site

  • ffmpeg memory leak when opening libx264 encoder

    18 octobre 2023, par ksb496

    I have spotted a memory leak issue when I use the libx264 encoder in the FFmpeg C API. Specifically, when it comes to deallocate memory after encoding a video. After tracking the factor that causes it, I realized that it happens after invoking avcodec_open2, which allocates some memory that afterwards cannot be freed. Once the video is processed, calling avcodec_close and then avcodec_free_context does not entirely free all the allocated memory.

    After some investigation, I found out that the problem could be located in AVCodecContext::priv_data being allocated but not being freed afterwards. In this question a solution to the issue is proposed. However, I tried to implement it without success (the memory being leaked seems to be exactly the same).

    As a matter of fact, the following simple code (which includes the patch that was proposed in the aforementioned question), in which the codec is being opened and closed multiple times without even writing a single frame or allocating an AVFormatContext, illustrates the memory leak.

    #include 
    extern "C"{
    #include 
    #include avcodec.h>
    #include opt.h>
    }
    
    int main()
    {
        avcodec_register_all();
    
        AVCodec *codec;
        AVCodecContext *c;
        for (int n=0; n<2000; n++)
        {
            codec = avcodec_find_encoder_by_name("libx264");
            c=avcodec_alloc_context3(codec);
            c->pix_fmt=AV_PIX_FMT_YUV420P;
            c->width=1920;
            c->height=1080;
            c->time_base=(AVRational){1, 30};
            c->framerate=(AVRational){30, 1};
            avcodec_open2(c, codec, NULL);
            avcodec_close(c);
            av_opt_free(c->priv_data);
            av_freep(&c->priv_data);
            avcodec_free_context(&c);
        }
        return 0;
    }
    

    It must be remarked that if the line codec = avcodec_find_encoder_by_name("libx264") is replaced to an invocation to an internal/native encoder, e.g., codec = avcodec_find_encoder(AV_CODEC_ID_MPEG4), then the memory leak issue completely disappears. Hence, it certainly seems to be an issue related to some private data of the external encoder not being properly freed.

    It is also worth mentioning that I am using an old version of ffmpeg and libx264. To be more precise, ffmpeg version 2.8git and libx264 version 0.136.x. For technical reasons that are beyond the scope of this question, it is not possible to upgrade the libraries to newer versions onto the project in which these are being used. I am fully aware that most of the involved ffmpeg/libx264 code has been probably changed along the years and many functions became deprecated or fixed, and thus reporting this as a possible bug in the ffmpeg developer's mailbox is out of the question.

    Nevertheless, I am still asking this here because I would like to know whether it is just some mistake on my end and/or something I am not taking into account when it comes to free all the memory relative to an external encoder (best case scenario). Otherwise, I would like to know whether there can be some reasonably cheap solution through some custom code or function that can be implemented as a patch (assuming it is indeed an issue related to ffmpeg/libx264), no matter if it makes the whole deallocation code less elegant or concise. If someone is still working on these older versions of ffmpeg and can come up with a workaround, that would be highly appreciated.

  • Why does moviepy complain about bitrate while generating audiofile ?

    6 octobre 2023, par Roman

    I have just try to use moviepy library for the first time. Generation of movies from numpy arrays was really simple, intuitive and worked out of box. This is what I tried:

    from moviepy.editor import VideoClip
    import numpy as np
    
    def make_frame(t):
    
        val = int(255.0*(t/3.0))
    
        ls = []
        for height in range(100):
            row = []
            for width in range(300):
                row.append([val,0,0])
            ls.append(row)
        frame = np.array(ls)
        return frame
    
    animation = VideoClip(make_frame, duration = 3)
    
    animation.write_gif('first_try.gif', fps=24)
    animation.write_videofile('first_try.mp4', fps=24)
    

    Then I wanted to use moviepy to generate sound. In theory it should work in a very similar way. Here is what I tried:

    from moviepy.editor import AudioClip
    import numpy as np
    
    make_frame = lambda t : 2*[ np.sin(404 * 2 * np.pi * t) ]
    clip = AudioClip(make_frame, duration=5)
    
    clip.write_audiofile('sound.mp4')
    

    However, I got an error message:

    [MoviePy] Writing audio in sound.mp4
    |----------| 0/111   0% [elapsed: 00:00 left: ?, ? iters/sec]Traceback (most recent call last):
      File "sound.py", line 9, in 
        clip.write_audiofile('sound.mp4')
      File "", line 2, in write_audiofile
      File "/usr/local/lib/python2.7/dist-packages/moviepy/decorators.py", line 54, in requires_duration
        return f(clip, *a, **k)
      File "/usr/local/lib/python2.7/dist-packages/moviepy/audio/AudioClip.py", line 204, in write_audiofile
        verbose=verbose, ffmpeg_params=ffmpeg_params)
      File "", line 2, in ffmpeg_audiowrite
      File "/usr/local/lib/python2.7/dist-packages/moviepy/decorators.py", line 54, in requires_duration
        return f(clip, *a, **k)
      File "/usr/local/lib/python2.7/dist-packages/moviepy/audio/io/ffmpeg_audiowriter.py", line 162, in ffmpeg_audiowrite
        writer.write_frames(chunk)
      File "/usr/local/lib/python2.7/dist-packages/moviepy/audio/io/ffmpeg_audiowriter.py", line 122, in write_frames
        raise IOError(error)
    IOError: [Errno 32] Broken pipe
    
    MoviePy error: FFMPEG encountered the following error while writing file sound.mp4:
    
    Invalid encoder type 'libx264'
    
    
    The audio export failed, possily because the bitrate you specified was two high or too low for the video codec.
    

    Does anybody know what this error means and how this problem can be resolved?

  • ffmpeg video has no preview/thumbnail with codec H.265

    5 octobre 2023, par Eva Silviana

    I have videos with large file size. I want to reduce the file size and I found this answer https://unix.stackexchange.com/a/38380/587749

    ffmpeg -i input.mp4 -c:v libx265 output.mp4
    

    It works perfectly, my video file size becomes smaller. But, my problem is that the video doesn't have a preview when I want to send it to WhatsApp.

    Am I missing some additional settings? Because, there are no problems when using video codec libx264

    The image below is an example:

    Red area is video file with Codec H.265 and green area is video file with Codec H.264 (as you can see, you can play videos directly on WhatsApp)

    enter image description here

  • broken ffmpeg default settings detected

    4 octobre 2023, par Ramakrishna

    I am getting broken ffmpeg error while VideoWrite using X264 Fourcc codec.I have install all the dependencies.How can I rectify this problem.The sample code that I have been using is as follows.

    VideoWriter oVideoWriter ("path.mp4", CV_FOURCC('X','2','6','4'), 15, frameSize, false);
    

    Operating system : Ubuntu 14.04 64-bit

    Console Error:

    [libx264 @ 0x8d6220] broken ffmpeg default settings detected
    [libx264 @ 0x8d6220] use an encoding preset (e.g. -vpre medium)
    [libx264 @ 0x8d6220] preset usage: -vpre  -vpre 
    [libx264 @ 0x8d6220] speed presets are listed in x264 --help
    [libx264 @ 0x8d6220] profile is optional; x264 defaults to high
    Could not open codec 'libx264': Unspecified errorOpenCV Error: Unsupported format or combination of formats (Your version of Gstreamer doesn't support this codec acutally or needed plugin missing.) in CvVideoWriter_GStreamer::open, file /home/mbox140/Development/opencv-2.4.9/modules/highgui/src/cap_gstreamer.cpp, line 518
    terminate called after throwing an instance of 'cv::Exception'
      what():  /home/mbox140/Development/opencv-2.4.9/modules/highgui/src/cap_gstreamer.cpp:518: error: (-210) Your version of Gstreamer doesn't support this codec acutally or needed plugin missing. in function CvVideoWriter_GStreamer::open
    

    Suggest me any solution for this.

  • FFMPEG (libx264) "height not divisible by 2"

    3 octobre 2023, par Andy Hin

    I am trying to encode a .mp4 video from a set of frames using FFMPEG using the libx264 codec.

    This is the command I am running:

    /usr/local/bin/ffmpeg -r 24 -i frame_%05d.jpg -vcodec libx264 -y -an video.mp4
    

    I sometimes get the following error:

    [libx264 @ 0xa3b85a0] height not divisible by 2 (520x369)
    

    After searching around a bit it seems that the issue has something to do with the scaling algorithm and can be fixed by adding a -vf argument.

    However, in my case I don't want to do any scaling. Ideally, I want to keep the dimensions exactly the same as the frames. Any advice? Is there some sort of aspect ratio that h264 enforces?