I think it's because you call the encoding function(flushing encoder) even when av_read_frame returns an error. try commenting it.
av_read_frame