ffmpeg裡的時間計算和轉換

NAVYSUMMER發表於2024-05-26

main.c

#include "libavutil/log.h"
#include "libavformat/avformat.h"
#include "libavutil/avutil.h"
#include "libavcodec/avcodec.h"

int main(int argc, char *argv[]) {
    av_log_set_level(AV_LOG_DEBUG);
    if (argc < 2) {
        av_log(NULL, AV_LOG_ERROR, "Usage: %s inputFile\n", argv[0]);
        return -1;
    }
    const char *inputFile = argv[1];
    AVFormatContext *fCtx = NULL;
    avformat_open_input(&fCtx, inputFile, NULL, NULL);
    avformat_find_stream_info(fCtx, NULL);
    av_dump_format(fCtx, 0, inputFile, 0);
    av_log(NULL, AV_LOG_INFO, "input file duration:%ld us,%f s\n", fCtx->duration,
           fCtx->duration * av_q2d(AV_TIME_BASE_Q));
    AVRational videoTimeBase;
    AVRational audioTimeBase;
    for (int i = 0; i < fCtx->nb_streams; i++) {
        AVStream *inStream = fCtx->streams[i];
        if (inStream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoTimeBase = inStream->time_base;
            av_log(NULL, AV_LOG_INFO, "video time base:num=%d,den=%d\n", videoTimeBase.num, videoTimeBase.den);
        } else if (inStream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
            audioTimeBase = inStream->time_base;
            av_log(NULL, AV_LOG_INFO, "audio time base:num=%d,den=%d\n", audioTimeBase.num, audioTimeBase.den);
        }
    }
    AVPacket *packet = av_packet_alloc();
    while (av_read_frame(fCtx, packet) == 0) {
        AVStream *inStream = fCtx->streams[packet->stream_index];
        av_log(NULL, AV_LOG_INFO, "stream index=%d,pts=%ld,ptsTime=%lf,dts=%ld,dtsTime=%lf\n", packet->stream_index,
               packet->pts, packet->pts *
                            av_q2d(inStream->time_base), packet->dts, packet->dts *
                                                                      av_q2d(inStream->time_base));
    }
    return 0;
}

Makefile

TARGET=main
SRC=main.c
CC=gcc
CFLAGS=-I /usr/local/ffmpeg/include
LDFLAGS=-L /usr/local/ffmpeg/lib
LDFLAGS+= -lavutil -lavformat -lavcodec
all:$(TARGET)
$(TARGET):$(SRC)
    $(CC) $(SRC) $(CFLAGS) $(LDFLAGS) -o $(TARGET)
clean:
    rm -rf $(TARGET)

  

相關文章