# FFmpeg PR 24593, code backport to release 7.1 for CVE-2026-107678.
# Authors: Joshua Rogers (969c7eb09198), Michael Niedermayer (d1434518fbd0, 71403a21b02a).
# https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/24593
diff --git a/libavutil/encryption_info.c b/libavutil/encryption_info.c
index a3eb955d2de..6fc3e338425 100644
--- a/libavutil/encryption_info.c
+++ b/libavutil/encryption_info.c
@@ -218,16 +218,19 @@ AVEncryptionInitInfo *av_encryption_init_info_alloc(
 
 void av_encryption_init_info_free(AVEncryptionInitInfo *info)
 {
-    uint32_t i;
-    if (info) {
+    while (info) {
+        AVEncryptionInitInfo *next = info->next;
+        uint32_t i;
+
         for (i = 0; i < info->num_key_ids; i++) {
             av_free(info->key_ids[i]);
         }
-        av_encryption_init_info_free(info->next);
         av_free(info->system_id);
         av_free(info->key_ids);
         av_free(info->data);
         av_free(info);
+
+        info = next;
     }
 }
 
diff --git a/libavutil/encryption_info.c b/libavutil/encryption_info.c
index 6fc3e338425..9643840157f 100644
--- a/libavutil/encryption_info.c
+++ b/libavutil/encryption_info.c
@@ -19,6 +19,7 @@
 #include <string.h>
 
 #include "encryption_info.h"
+#include "error.h"
 #include "mem.h"
 #include "intreadwrite.h"
 
@@ -295,37 +296,36 @@ AVEncryptionInitInfo *av_encryption_init_info_get_side_data(
     return ret;
 }
 
-uint8_t *av_encryption_init_info_add_side_data(const AVEncryptionInitInfo *info, size_t *side_data_size)
+int av_encryption_init_info_append_side_data(uint8_t **side_data, size_t *side_data_size,
+                                             unsigned int *allocated_size,
+                                             const AVEncryptionInitInfo *info)
 {
     const AVEncryptionInitInfo *cur_info;
     uint8_t *buffer, *cur_buffer;
-    uint32_t i, init_info_count;
-    uint64_t temp_side_data_size;
+    uint32_t i;
+    uint64_t init_info_count    = *side_data ? AV_RB32(*side_data) : 0;
+    size_t   old_side_data_size = *side_data ? *side_data_size : 4;
+    uint64_t new_side_data_size = old_side_data_size;
 
-    temp_side_data_size = 4;
-    init_info_count = 0;
     for (cur_info = info; cur_info; cur_info = cur_info->next) {
-        temp_side_data_size += (uint64_t)FF_ENCRYPTION_INIT_INFO_EXTRA + cur_info->system_id_size + cur_info->data_size;
-        if (init_info_count == UINT32_MAX || temp_side_data_size > UINT32_MAX) {
-            return NULL;
-        }
+        new_side_data_size += (uint64_t)FF_ENCRYPTION_INIT_INFO_EXTRA + cur_info->system_id_size + cur_info->data_size;
+        if (init_info_count == UINT32_MAX || new_side_data_size > UINT32_MAX)
+            return AVERROR(EINVAL);
         init_info_count++;
 
         if (cur_info->num_key_ids) {
-            temp_side_data_size += (uint64_t)cur_info->num_key_ids * cur_info->key_id_size;
-            if (temp_side_data_size > UINT32_MAX) {
-                return NULL;
-            }
+            new_side_data_size += (uint64_t)cur_info->num_key_ids * cur_info->key_id_size;
+            if (new_side_data_size > UINT32_MAX)
+                return AVERROR(EINVAL);
         }
     }
-    *side_data_size = temp_side_data_size;
 
-    cur_buffer = buffer = av_malloc(*side_data_size);
+    buffer = av_fast_realloc(*side_data, allocated_size, new_side_data_size);
     if (!buffer)
-        return NULL;
+        return AVERROR(ENOMEM);
 
-    AV_WB32(cur_buffer, init_info_count);
-    cur_buffer += 4;
+    AV_WB32(buffer, init_info_count);
+    cur_buffer = buffer + old_side_data_size;
     for (cur_info = info; cur_info; cur_info = cur_info->next) {
         AV_WB32(cur_buffer,      cur_info->system_id_size);
         AV_WB32(cur_buffer +  4, cur_info->num_key_ids);
@@ -345,5 +345,17 @@ uint8_t *av_encryption_init_info_add_side_data(const AVEncryptionInitInfo *info,
         }
     }
 
-    return buffer;
+    *side_data      = buffer;
+    *side_data_size = new_side_data_size;
+    return 0;
+}
+
+uint8_t *av_encryption_init_info_add_side_data(const AVEncryptionInitInfo *info, size_t *side_data_size)
+{
+    uint8_t *side_data = NULL;
+    unsigned int allocated_size = 0;
+
+    if (av_encryption_init_info_append_side_data(&side_data, side_data_size, &allocated_size, info) < 0)
+        return NULL;
+    return side_data;
 }
diff --git a/libavutil/encryption_info.h b/libavutil/encryption_info.h
index 8fe7ebfe432..6fd39cf02cd 100644
--- a/libavutil/encryption_info.h
+++ b/libavutil/encryption_info.h
@@ -202,4 +202,21 @@ AVEncryptionInitInfo *av_encryption_init_info_get_side_data(
 uint8_t *av_encryption_init_info_add_side_data(
     const AVEncryptionInitInfo *info, size_t *side_data_size);
 
+/**
+ * Appends a copy of the given encryption init info list to encryption init
+ * info side data, growing the side data with av_fast_realloc().
+ *
+ * @param side_data      Side data created by this function or
+ *                       av_encryption_init_info_add_side_data(), *side_data
+ *                       may be NULL to create new side data.
+ * @param side_data_size Size of *side_data.
+ * @param allocated_size Allocated size of *side_data, as for av_fast_realloc().
+ * @param info           The list to append.
+ * @return 0 on success, a negative AVERROR code on failure, in which case
+ *         *side_data and *side_data_size are unchanged.
+ */
+int av_encryption_init_info_append_side_data(
+    uint8_t **side_data, size_t *side_data_size, unsigned int *allocated_size,
+    const AVEncryptionInitInfo *info);
+
 #endif /* AVUTIL_ENCRYPTION_INFO_H */
diff --git a/libavutil/tests/encryption_info.c b/libavutil/tests/encryption_info.c
index 55c668c6d56..d8f0187ef97 100644
--- a/libavutil/tests/encryption_info.c
+++ b/libavutil/tests/encryption_info.c
@@ -141,8 +141,9 @@ static AVEncryptionInitInfo *create_init_info(void)
 static void run_encryption_init_info_test(void)
 {
     AVEncryptionInitInfo *info, *copy;
-    uint8_t *side_data;
-    size_t side_data_size;
+    uint8_t *side_data, *appended;
+    size_t side_data_size, appended_size;
+    unsigned int allocated_size = 0;
 
     info = create_init_info();
 
@@ -157,6 +158,8 @@ static void run_encryption_init_info_test(void)
 
     // Make the first init info different from the second to test the correct order.
     memset(info->system_id, 0, info->system_id_size);
+    appended = av_encryption_init_info_add_side_data(info, &appended_size);
+    av_assert0(appended);
     info->next = create_init_info();
     side_data = av_encryption_init_info_add_side_data(info, &side_data_size);
     av_assert0(side_data);
@@ -164,6 +167,11 @@ static void run_encryption_init_info_test(void)
     av_assert0(copy);
     av_assert0(compare_encryption_init_info(info, copy) == 0);
     av_encryption_init_info_free(copy);
+
+    av_assert0(av_encryption_init_info_append_side_data(&appended, &appended_size, &allocated_size, info->next) == 0);
+    av_assert0(appended_size == side_data_size);
+    av_assert0(memcmp(appended, side_data, side_data_size) == 0);
+    av_free(appended);
     av_free(side_data);
 
     av_encryption_init_info_free(info);
diff --git a/libavformat/isom.h b/libavformat/isom.h
index 42a124edb36..2af2d73df26 100644
--- a/libavformat/isom.h
+++ b/libavformat/isom.h
@@ -368,6 +368,8 @@ typedef struct MOVContext {
     int has_looked_for_mfra;
     int use_tfdt;
     MOVFragmentIndex frag_index;
+    uint8_t *pssh_side_data;
+    unsigned int pssh_side_data_allocated;
     int atom_depth;
     unsigned int aax_mode;  ///< 'aax' file has been detected
     uint8_t file_key[20];
diff --git a/libavformat/mov.c b/libavformat/mov.c
index f7c12922d93..79bbdb05692 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -8350,12 +8350,12 @@ static int mov_read_saio(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 
 static int mov_read_pssh(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
-    AVEncryptionInitInfo *info, *old_init_info;
+    AVEncryptionInitInfo *info;
     uint8_t **key_ids;
     AVStream *st;
-    const AVPacketSideData *old_side_data;
-    uint8_t *side_data, *extra_data;
-    size_t side_data_size;
+    AVPacketSideData *old_side_data = NULL;
+    uint8_t *side_data = NULL, *extra_data;
+    size_t side_data_size = 0;
     int ret = 0;
     unsigned int version, kid_count, extra_data_size, alloc_size = 0;
 
@@ -8432,37 +8432,35 @@ static int mov_read_pssh(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     info->data = extra_data;
     info->data_size = extra_data_size;
 
-    // If there is existing initialization data, append to the list.
-    old_side_data = av_packet_side_data_get(st->codecpar->coded_side_data, st->codecpar->nb_coded_side_data,
-                                            AV_PKT_DATA_ENCRYPTION_INIT_INFO);
-    if (old_side_data) {
-        old_init_info = av_encryption_init_info_get_side_data(old_side_data->data, old_side_data->size);
-        if (old_init_info) {
-            // Append to the end of the list.
-            for (AVEncryptionInitInfo *cur = old_init_info;; cur = cur->next) {
-                if (!cur->next) {
-                    cur->next = info;
-                    break;
-                }
-            }
-            info = old_init_info;
-        } else {
-            // Assume existing side-data will be valid, so the only error we could get is OOM.
-            ret = AVERROR(ENOMEM);
-            goto finish;
-        }
-    }
+    for (int i = 0; i < st->codecpar->nb_coded_side_data; i++)
+        if (st->codecpar->coded_side_data[i].type == AV_PKT_DATA_ENCRYPTION_INIT_INFO)
+            old_side_data = &st->codecpar->coded_side_data[i];
 
-    side_data = av_encryption_init_info_add_side_data(info, &side_data_size);
-    if (!side_data) {
+    // If there is existing initialization data, append the new record to it.
+    if (old_side_data) {
+        side_data      = old_side_data->data;
+        side_data_size = old_side_data->size;
+    }
+    if (!old_side_data || side_data != c->pssh_side_data)
+        c->pssh_side_data_allocated = 0;
+
+    ret = av_encryption_init_info_append_side_data(&side_data, &side_data_size,
+                                                   &c->pssh_side_data_allocated, info);
+    if (ret < 0)
+        goto finish;
+
+    if (old_side_data) {
+        old_side_data->data = side_data;
+        old_side_data->size = side_data_size;
+    } else if (!av_packet_side_data_add(&st->codecpar->coded_side_data,
+                                        &st->codecpar->nb_coded_side_data,
+                                        AV_PKT_DATA_ENCRYPTION_INIT_INFO,
+                                        side_data, side_data_size, 0)) {
+        av_free(side_data);
         ret = AVERROR(ENOMEM);
         goto finish;
     }
-    if (!av_packet_side_data_add(&st->codecpar->coded_side_data,
-                                 &st->codecpar->nb_coded_side_data,
-                                 AV_PKT_DATA_ENCRYPTION_INIT_INFO,
-                                 side_data, side_data_size, 0))
-        av_free(side_data);
+    c->pssh_side_data = side_data;
 
 finish:
     av_encryption_init_info_free(info);
@@ -12586,6 +12584,7 @@ static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
     }
 
     mov->found_mdat = 0;
+    mov->pssh_side_data = NULL;
 
     ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
     if (ret < 0)
