I am trying to use libavcodec and libavformat to write an mp4 video file in realtime using h264. I am using an approach heavily inspired by this answer here This works well as a non-realtime solution however, avcodec_receive_packet() starts running much slower after 20 frames or so (this is usually around the first time it returns success and thus av_interleaved_write_frame() is called for the first time). This is so slow that my writing cannot work in realtime.
Solutions I have tried:
- Enabling multithreading on my codec context
 - Running 
avcodec_receive_packet()andav_interleaved_write_frame()on a separate thread to my capture from the realtime video source - Changing the 
gop_sizein the video context - Lowering my bitrate in the video context
 
Is there anything I'm missing? Possibly some fundamental rules to capturing video in realtime. I am not very experienced with programming with video.