summaryrefslogtreecommitdiff
path: root/src/codec/ffmpeg/common.c
blob: 59f59b7d9c3489bf76aac7e5a7ac12d3ebb77c34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#define AL_LOG_SECTION "ff"
//#define AL_LOG_ENABLE_TRACE
#include <al/log.h>
#include <al/lib.h>
#include <libavutil/log.h>
#include <libavformat/avformat.h>

#include "common.h"

s64 camu_ff_frame_duration(AVFrame *frame)
{
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 30, 100)
    return frame->duration;
#else
    return frame->pkt_duration;
#endif
}

static __thread struct {
    char buf[AL_LOG_MESSAGE_SIZE];
    size_t pos;
} log_context;

// If a line takes more than 1 step to print, make sure we stay within AL_LOG_MESSAGE_SIZE.
#define AV_LOG_MAX_CHUNK (AL_LOG_MESSAGE_SIZE / 2)

static void av_log_callback(void *userdata, s32 level, const char *fmt, va_list args)
{
    (void)userdata;

    char *offset = log_context.buf + log_context.pos;
    s32 ret = al_vsnprintf(offset, AV_LOG_MAX_CHUNK, fmt, args);
    al_assert(ret > 0);

    offset += ret;
    log_context.pos += ret;

    if ((log_context.pos > 0 && *(offset - 1) == '\n') || log_context.pos >= AV_LOG_MAX_CHUNK) {
        if (level < AV_LOG_WARNING) {
            log_info(log_context.buf);
        } else if (level < AL_LOG_DEBUG) {
            log_debug(log_context.buf);
        } else {
            log_trace(log_context.buf);
        }
        log_context.pos = 0;
    }
}

void camu_ff_set_log_callback(void (*callback)(void *, s32, const char *, va_list))
{
    av_log_set_callback(callback);
}

void camu_ff_common_init(void)
{

#ifdef CAMU_OLD_FFMPEG
    log_info("Using FFmpeg version "FFMPEG_VERSION" (old).");
    AL_IGNORE_WARNING("-Wdeprecated-declarations")
    av_register_all();
    AL_IGNORE_WARNING_END
#else
    log_info("Using FFmpeg version "FFMPEG_VERSION".");
#endif
    camu_ff_set_log_callback(av_log_callback);
}

AVCodecContext *camu_ff_alloc_codec_context(const AVCodec *codec, AVCodecParameters *codecpar)
{
    AVCodecContext *codec_context = avcodec_alloc_context3(codec);
    if (!codec_context) {
        log_error("Failed to alloc codec context.");
        return NULL;
    }

    s32 ret = avcodec_parameters_to_context(codec_context, codecpar);
    if (ret < 0) {
        log_error("Failed to copy codec parameters (%s).", av_err2str(ret));
        return NULL;
    }

    return codec_context;
}

bool camu_ff_open_avcodec(AVCodecContext *codec_context, const AVCodec *codec, AVDictionary *opts)
{
    s32 ret = avcodec_open2(codec_context, codec, &opts);
    if (ret < 0) {
        log_error("Failed to open codec %s (%s).", codec->name, av_err2str(ret));
        return false;
    }
    av_dict_free(&opts);
    return true;
}