Skip to content

Instantly share code, notes, and snippets.

@jcelerier
Created June 23, 2021 16:30
Show Gist options
  • Save jcelerier/fd2b0bbd216a34ad189dd80b1b08b47e to your computer and use it in GitHub Desktop.
Save jcelerier/fd2b0bbd216a34ad189dd80b1b08b47e to your computer and use it in GitHub Desktop.
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/frame.h>
#include <libavutil/mem.h>
}
#include <cassert>
#include <iostream>
void check(int ret)
{
if (ret < 0 && ret != AVERROR_EOF)
{
char err[100]{0};
av_make_error_string(err, 100, ret);
std::cerr << ret << ": " << err << "\n";
}
}
int main() {
const char *filename = "04 - Rat King.flac";
int ret{};
av_register_all();
avcodec_register_all();
AVFormatContext *fmt_ctx{};
ret = avformat_open_input(&fmt_ctx, filename, nullptr, nullptr);
check(ret);
assert(fmt_ctx);
ret = avformat_find_stream_info(fmt_ctx, nullptr);
check(ret);
AVStream *stream{};
for (std::size_t i = 0; i < fmt_ctx->nb_streams; i++) {
if (fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
stream = fmt_ctx->streams[i];
break;
}
}
assert(stream);
auto codec = avcodec_find_decoder(stream->codecpar->codec_id);
assert(codec);
auto codec_ctx = avcodec_alloc_context3(codec);
assert(codec_ctx);
ret = avcodec_parameters_to_context(codec_ctx, stream->codecpar);
check(ret);
ret = avcodec_open2(codec_ctx, codec, nullptr);
check(ret);
AVPacket packet;
AVFrame* frame = av_frame_alloc();
assert(frame);
ret = av_read_frame(fmt_ctx, &packet);
check(ret);
ret = avcodec_send_packet(codec_ctx, &packet);
check(ret);
ret = avcodec_receive_frame(codec_ctx, frame);
check(ret);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment