+ for (next_code_idx = 0; next_code_idx < FF_ARRAY_ELEMS(mat_codes); next_code_idx++)
+ if (ctx->hd_buf_filled <= mat_codes[next_code_idx].pos)
+ break;
+
+ if (next_code_idx >= FF_ARRAY_ELEMS(mat_codes))
+ return AVERROR_BUG;
+
+ while (padding_remaining || data_remaining ||
+ mat_codes[next_code_idx].pos == ctx->hd_buf_filled) {
+
+ if (mat_codes[next_code_idx].pos == ctx->hd_buf_filled) {
+ /* time to insert MAT code */
+ int code_len = mat_codes[next_code_idx].len;
+ int code_len_remaining = code_len;
+ memcpy(hd_buf + mat_codes[next_code_idx].pos,
+ mat_codes[next_code_idx].code, code_len);
+ ctx->hd_buf_filled += code_len;
+
+ next_code_idx++;
+ if (next_code_idx == FF_ARRAY_ELEMS(mat_codes)) {
+ next_code_idx = 0;
+
+ /* this was the last code, move to the next MAT frame */
+ have_pkt = 1;
+ ctx->out_buf = hd_buf;
+ ctx->hd_buf_idx ^= 1;
+ hd_buf = ctx->hd_buf[ctx->hd_buf_idx];
+ ctx->hd_buf_filled = 0;
+
+ /* inter-frame gap has to be counted as well, add it */
+ code_len_remaining += MAT_PKT_OFFSET - MAT_FRAME_SIZE;
+ }
+
+ if (padding_remaining) {
+ /* consider the MAT code as padding */
+ int counted_as_padding = FFMIN(padding_remaining,
+ code_len_remaining);
+ padding_remaining -= counted_as_padding;
+ code_len_remaining -= counted_as_padding;
+ }
+ /* count the remainder of the code as part of frame size */
+ if (code_len_remaining)
+ total_frame_size += code_len_remaining;
+ }
+
+ if (padding_remaining) {
+ int padding_to_insert = FFMIN(mat_codes[next_code_idx].pos - ctx->hd_buf_filled,
+ padding_remaining);
+
+ memset(hd_buf + ctx->hd_buf_filled, 0, padding_to_insert);
+ ctx->hd_buf_filled += padding_to_insert;
+ padding_remaining -= padding_to_insert;
+
+ if (padding_remaining)
+ continue; /* time to insert MAT code */
+ }
+
+ if (data_remaining) {
+ int data_to_insert = FFMIN(mat_codes[next_code_idx].pos - ctx->hd_buf_filled,
+ data_remaining);
+
+ memcpy(hd_buf + ctx->hd_buf_filled, dataptr, data_to_insert);
+ ctx->hd_buf_filled += data_to_insert;
+ dataptr += data_to_insert;
+ data_remaining -= data_to_insert;
+ }
+ }
+
+ ctx->truehd_prev_size = total_frame_size;
+ ctx->truehd_prev_time = input_timing;
+
+ av_log(s, AV_LOG_TRACE, "TrueHD frame inserted, total size %d, buffer position %d\n",
+ total_frame_size, ctx->hd_buf_filled);