diff --git a/libavcodec/aaccoder.c b/libavcodec/aaccoder.c
index 25187b7c870299b1f1a84b293ec3333fa8abb4c6..b6fefd3e62239ef767f5058345eb7857bab20a4c 100644
--- a/libavcodec/aaccoder.c
+++ b/libavcodec/aaccoder.c
@@ -721,6 +721,9 @@ static void search_for_quantizers_twoloop(AVCodecContext *avctx,
     int allz = 0;
     float minthr = INFINITY;
 
+    // for values above this the decoder might end up in an endless loop
+    // due to always having more bits than what can be encoded.
+    destbits = FFMIN(destbits, 5800);
     //XXX: some heuristic to determine initial quantizers will reduce search time
     //determine zero bands and upper limits
     for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c
index 3ac2ad890dcead90213302f6bdee3c46501b7d5b..76e4e8753ebba4c7ad71d8034013f5a047d7c9d8 100644
--- a/libavcodec/aacenc.c
+++ b/libavcodec/aacenc.c
@@ -571,11 +571,11 @@ static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
         }
         start_ch += chans;
     }
+    if ((ret = ff_alloc_packet2(avctx, avpkt, 768 * s->channels)))
+        return ret;
     do {
         int frame_bits;
 
-        if ((ret = ff_alloc_packet2(avctx, avpkt, 768 * s->channels)))
-            return ret;
         init_put_bits(&s->pb, avpkt->data, avpkt->size);
 
         if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))