| 1 | #include <stdlib.h>
|
|---|
| 2 | #include <stdio.h>
|
|---|
| 3 |
|
|---|
| 4 | #include <libavcodec/avcodec.h>
|
|---|
| 5 | #include <libavformat/avformat.h>
|
|---|
| 6 |
|
|---|
| 7 | extern const char encoded_audio[];
|
|---|
| 8 | const int encoded_audio_len;
|
|---|
| 9 |
|
|---|
| 10 | #define CODEC_ID AV_CODEC_ID_MP2
|
|---|
| 11 | #define SAMPLERATE 48000
|
|---|
| 12 | #define CHANNELS 2
|
|---|
| 13 | #define BUFFER_SIZE 40
|
|---|
| 14 |
|
|---|
| 15 | int main(int argc, char *argv[])
|
|---|
| 16 | {
|
|---|
| 17 | AVCodecParserContext *parser_ctx;
|
|---|
| 18 | AVCodec *acodec;
|
|---|
| 19 | AVCodecContext *codec_ctx;
|
|---|
| 20 | int ret = 1;
|
|---|
| 21 | int i = 0;
|
|---|
| 22 |
|
|---|
| 23 | av_register_all();
|
|---|
| 24 |
|
|---|
| 25 | parser_ctx = av_parser_init(CODEC_ID);
|
|---|
| 26 | if (!parser_ctx) {
|
|---|
| 27 | printf("parser context not found\n");
|
|---|
| 28 | return -1;
|
|---|
| 29 | }
|
|---|
| 30 |
|
|---|
| 31 | acodec = avcodec_find_decoder(CODEC_ID);
|
|---|
| 32 | if (!acodec) {
|
|---|
| 33 | printf("AVcodec not found\n");
|
|---|
| 34 | goto close_avparser;
|
|---|
| 35 | }
|
|---|
| 36 |
|
|---|
| 37 | codec_ctx = avcodec_alloc_context3(acodec);
|
|---|
| 38 | if (!codec_ctx) {
|
|---|
| 39 | printf("Failed to allocate codec context\n");
|
|---|
| 40 | goto close_avparser;
|
|---|
| 41 | }
|
|---|
| 42 |
|
|---|
| 43 | codec_ctx->sample_rate = SAMPLERATE;
|
|---|
| 44 | codec_ctx->channels = CHANNELS;
|
|---|
| 45 |
|
|---|
| 46 | ret = avcodec_open2(codec_ctx, acodec, NULL);
|
|---|
| 47 | if (ret < 0) {
|
|---|
| 48 | printf("Failed to open avocdec (%d)\n", ret);
|
|---|
| 49 | return ret;
|
|---|
| 50 | }
|
|---|
| 51 |
|
|---|
| 52 | while (i < encoded_audio_len) {
|
|---|
| 53 | char *buf = av_malloc(BUFFER_SIZE);
|
|---|
| 54 | int buf_size = BUFFER_SIZE;
|
|---|
| 55 | AVPacket parsed_pkt;
|
|---|
| 56 |
|
|---|
| 57 | if (!buf) {
|
|---|
| 58 | goto close_avcodec;
|
|---|
| 59 | }
|
|---|
| 60 |
|
|---|
| 61 | if ((encoded_audio_len - i) < BUFFER_SIZE)
|
|---|
| 62 | buf_size = encoded_audio_len - i;
|
|---|
| 63 |
|
|---|
| 64 | av_init_packet(&parsed_pkt);
|
|---|
| 65 | memcpy(buf, &encoded_audio[i], buf_size);
|
|---|
| 66 |
|
|---|
| 67 | i += av_parser_parse2(parser_ctx, codec_ctx,
|
|---|
| 68 | &parsed_pkt.data, &parsed_pkt.size,
|
|---|
| 69 | buf, buf_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
|
|---|
| 70 |
|
|---|
| 71 | av_free(buf);
|
|---|
| 72 | }
|
|---|
| 73 |
|
|---|
| 74 | ret = 0;
|
|---|
| 75 |
|
|---|
| 76 | close_avcodec:
|
|---|
| 77 | avcodec_close(codec_ctx);
|
|---|
| 78 | av_free(codec_ctx);
|
|---|
| 79 | close_avparser:
|
|---|
| 80 | av_parser_close(parser_ctx);
|
|---|
| 81 |
|
|---|
| 82 | return ret;
|
|---|
| 83 | }
|
|---|