+ // Get the audio channel mapping
+ sprintf( key, "%d.channels", i );
+ map_channels = mlt_properties_get_int( frame_meta_properties, key );
+ sprintf( key, "%d.start", i );
+ if ( mlt_properties_get( frame_meta_properties, key ) )
+ map_start = mlt_properties_get_int( frame_meta_properties, key );
+ else
+ map_start = -1;
+
+ // Optimized for no channel remapping.
+ if ( !map_channels && map_start == -1 )
+ {
+ // Encode the audio.
+ pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
+ }
+ else
+ {
+ int ch; // channel offset into interleaved dest buffer
+
+ // If last map..channels not specific, use the remaining channels.
+ if ( !map_channels )
+ map_channels = channels - j;
+
+ // Clear or allocate the audio buffer.
+ if ( !audio_buf_2 )
+ audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
+ else
+ memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
+
+ // Interleave the audio buffer with the #channels for this stream.
+ for ( ch = 0; ch < map_channels && j < channels; ch++, j++ )
+ {
+ int16_t *src = audio_buf_1 + ( map_start > -1 ? ( map_start + ch ) : j );
+ int16_t *dest = audio_buf_2 + ch;
+ int s = samples + 1;
+
+ while ( --s ) {
+ *dest = *src;
+ dest += map_channels;
+ src += channels;
+ }
+ }
+
+ // Encode the audio.
+ pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
+ }
+
+ // Write the compressed frame in the media file
+ if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
+ {
+ pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
+ mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio stream %d pkt pts %lld frame pts %lld",
+ stream->index, pkt.pts, codec->coded_frame->pts );
+ }
+ pkt.flags |= PKT_FLAG_KEY;
+ pkt.stream_index = stream->index;
+ pkt.data = audio_outbuf;
+
+ if ( pkt.size > 0 && stream->pts.den )
+ {
+ if ( av_interleaved_write_frame( oc, &pkt ) )
+ mlt_log_error( MLT_CONSUMER_SERVICE( this ), "error writing audio frame %d\n", frames - 1 );
+ }
+
+ mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", codec->frame_size );
+ if ( i == 0 )
+ {
+ if ( audio_codec_id == CODEC_ID_VORBIS )
+ audio_pts = (double)codec->coded_frame->pts * av_q2d( stream->time_base );
+ else
+ audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
+ }
+ }