diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c
index ed1e6b7c71d02318993da3798f4e944630e34e29..3b097e1dffa9513169bf0d21245e7662c57bb159 100644
--- a/libavcodec/mpegvideo.c
+++ b/libavcodec/mpegvideo.c
@@ -2015,6 +2015,12 @@ static void select_input_picture(MpegEncContext *s){
                 for(i=0; i<s->max_b_frames+1; i++){
                     int pict_num= s->input_picture[0]->display_picture_number + i;
                     int pict_type= s->rc_context.entry[pict_num].new_pict_type;
+
+                    if(!s->input_picture[i]){
+                        if(i>0)
+                            s->rc_context.entry[pict_num-1].new_pict_type = P_TYPE;
+                        break;
+                    }
                     s->input_picture[i]->pict_type= pict_type;
                     
                     if(i + 1 >= s->rc_context.num_entries) break;