[Libav-user] How to modify the start time of an audio stream?

Gustav González xtingray at gmail.com
Sat Apr 23 02:57:28 EEST 2022


Currently, I am working on a new feature for my software using the Libav
API. I was able to merge a video file with an audio file, the output is an
MP4 file and the source code works perfectly.

Right now, I have a new requirement: the start time for the video and the
audio streams are the same. Both start at 00:00. My next challenge is to
add an option to shift the start time for the audio stream based on a
variable. For example, if the audio start variable is equal to 10 seconds,
then the audio stream should be played at time 00:10.

So I wonder, what is the best approach to implement this feature? Should I
insert silent packets before the audio start time is reached? Or should I
modify the timestamp information for every audio stream packet before it is
written into the output container?

Here is the piece of code I use to write the audio stream into the MP4
file. Right now it works like a charm, but I guess this is the place where
I should implement the new requirement. Any suggestion is pretty welcome!

while (1) {
    AVStream *in_stream;

    int ret = av_read_frame(audioInputFormatContext, pkt);
    if (ret < 0)

    in_stream  = audioInputFormatContext->streams[pkt->stream_index];
    pkt->stream_index = outIndex;

    AVRational out_time_base = audioStreamList.at(i)->time_base;

    // copy packet
    pkt->pts = av_rescale_q_rnd(pkt->pts, in_stream->time_base,

    pkt->dts = av_rescale_q_rnd(pkt->dts, in_stream->time_base,

    pkt->duration = av_rescale_q(pkt->duration, in_stream->time_base,
    pkt->pos = -1;

    ret = av_interleaved_write_frame(formatContext, pkt);
    if (ret < 0) {
        fprintf(stderr, "Error muxing packet\n");

  Gustav Gonzalez
  xtingray at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://ffmpeg.org/pipermail/libav-user/attachments/20220422/17552a83/attachment.htm>

More information about the Libav-user mailing list