+}
+
+/**
+ * Initialize an MpegEncContext's thread contexts. Presumes that
+ * slice_context_count is already set and that all the fields
+ * that are freed/reset in free_duplicate_context() are NULL.
+ */
+static int init_duplicate_contexts(MpegEncContext *s)
+{
+ int nb_slices = s->slice_context_count, ret;
+
+ /* We initialize the copies before the original so that
+ * fields allocated in init_duplicate_context are NULL after
+ * copying. This prevents double-frees upon allocation error. */
+ for (int i = 1; i < nb_slices; i++) {
+ s->thread_context[i] = av_memdup(s, sizeof(MpegEncContext));
+ if (!s->thread_context[i])
+ return AVERROR(ENOMEM);
+ if ((ret = init_duplicate_context(s->thread_context[i])) < 0)
+ return ret;
+ s->thread_context[i]->start_mb_y =
+ (s->mb_height * (i ) + nb_slices / 2) / nb_slices;
+ s->thread_context[i]->end_mb_y =
+ (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;
+ }
+ s->start_mb_y = 0;
+ s->end_mb_y = nb_slices > 1 ? (s->mb_height + nb_slices / 2) / nb_slices
+ : s->mb_height;
+ return init_duplicate_context(s);