From cf1e845a1eabaaf19890f44bccb7419cda3e14be Mon Sep 17 00:00:00 2001
From: erankor <eran.kornblau@kaltura.com>
Date: Thu, 3 Dec 2015 17:18:22 +0200
Subject: [PATCH 2/2] bug fix invalid encryption key/kid crashes

need to validate the keys after allocating the tracks, otherwise mov_free
will try to walk a null tracks array in case of error
---
 libavformat/movenc.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/libavformat/movenc.c b/libavformat/movenc.c
index f1323e4..5712337 100644
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -5157,6 +5157,12 @@ static int mov_write_header(AVFormatContext *s)
         mov->nb_streams += mov->nb_meta_tmcd;
     }
 
+    // Reserve an extra stream for chapters for the case where chapters
+    // are written in the trailer
+    mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
+    if (!mov->tracks)
+        return AVERROR(ENOMEM);
+    
     if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
         if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
             mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
@@ -5183,12 +5189,6 @@ static int mov_write_header(AVFormatContext *s)
         }
     }
 
-    // Reserve an extra stream for chapters for the case where chapters
-    // are written in the trailer
-    mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
-    if (!mov->tracks)
-        return AVERROR(ENOMEM);
-
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st= s->streams[i];
         MOVTrack *track= &mov->tracks[i];
-- 
1.9.0.msysgit.0

