9 #include <libavcodec/avcodec.h>
10 #include <libavutil/avassert.h>
11 #include <libavutil/avutil.h>
12 #include <libavutil/channel_layout.h>
13 #include <libavutil/common.h>
14 #include <libavutil/dict.h>
15 #include <libavutil/error.h>
16 #include <libavutil/mem.h>
17 #include <libavutil/rational.h>
18 #include <libavutil/samplefmt.h>
19 #include <libswresample/swresample.h>
20 #include <libswscale/swscale.h>
26 #include <libavformat/avformat.h>
27 #include <libavformat/avio.h>
28 #include <libavutil/audio_fifo.h>
29 #include <libavutil/frame.h>
30 #include <libavutil/opt.h>
36 #define LOG_TAG "audio"
39 #define ANDROIDINCLOUD_PCM_CLIENT_PORT 24296
43 static char error_buffer[255];
44 av_strerror(error, error_buffer,
sizeof(error_buffer));
51 av_init_packet(packet);
60 if (!(*frame = av_frame_alloc()))
62 printf(
"Could not allocate input frame\n");
63 return AVERROR(ENOMEM);
73 int init_resampler(AVCodecContext* input_codec_context, AVCodecContext* output_codec_context,
74 SwrContext** resample_context)
85 *resample_context = swr_alloc_set_opts(
86 NULL, av_get_default_channel_layout(output_codec_context->channels),
87 output_codec_context->sample_fmt, output_codec_context->sample_rate,
88 av_get_default_channel_layout(input_codec_context->channels),
89 input_codec_context->sample_fmt, input_codec_context->sample_rate, 0, NULL);
90 if (!*resample_context)
92 printf(
"Could not allocate resample context\n");
93 return AVERROR(ENOMEM);
100 av_assert0(output_codec_context->sample_rate == input_codec_context->sample_rate);
103 if ((error = swr_init(*resample_context)) < 0)
105 printf(
"Could not open resample context\n");
106 swr_free(resample_context);
113 int init_fifo(AVAudioFifo** fifo, AVCodecContext* output_codec_context)
116 if (!(*fifo = av_audio_fifo_alloc(output_codec_context->sample_fmt,
117 output_codec_context->channels, 1)))
119 printf(
"Could not allocate FIFO\n");
120 return AVERROR(ENOMEM);
127 AVCodecContext* input_codec_context,
int* data_present,
int* finished)
130 AVPacket input_packet;
135 if ((error = av_read_frame(input_format_context, &input_packet)) < 0)
138 if (error == AVERROR_EOF)
142 printf(
"Could not read frame (error '%s')\n",
get_error_text(error));
153 if ((error = avcodec_decode_audio4(input_codec_context, frame, data_present, &input_packet)) <
156 printf(
"Could not decode frame (error '%s')\n",
get_error_text(error));
157 av_free_packet(&input_packet);
165 if (*finished && *data_present)
167 av_free_packet(&input_packet);
186 if (!(*converted_input_samples =
187 calloc(output_codec_context->channels,
sizeof(**converted_input_samples))))
189 printf(
"Could not allocate converted input sample pointers\n");
190 return AVERROR(ENOMEM);
197 if ((error = av_samples_alloc(*converted_input_samples, NULL, output_codec_context->channels,
198 frame_size, output_codec_context->sample_fmt, 0)) < 0)
200 fprintf(stderr,
"Could not allocate converted input samples (error '%s')\n",
202 av_freep(&(*converted_input_samples)[0]);
203 free(*converted_input_samples);
214 int convert_samples(
const uint8_t** input_data, uint8_t** converted_data,
const int frame_size,
215 SwrContext* resample_context)
221 swr_convert(resample_context, converted_data, frame_size, input_data, frame_size)) < 0)
223 printf(
"Could not convert input samples (error '%s')\n",
get_error_text(error));
239 if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0)
241 printf(
"Could not reallocate FIFO\n");
246 if (av_audio_fifo_write(fifo, (
void**) converted_input_samples, frame_size) < frame_size)
248 printf(
"Could not write data to FIFO\n");
263 if (!(*frame = av_frame_alloc()))
265 printf(
"Could not allocate output frame\n");
276 (*frame)->nb_samples = frame_size;
277 (*frame)->channel_layout = output_codec_context->channel_layout;
278 (*frame)->format = output_codec_context->sample_fmt;
279 (*frame)->sample_rate = output_codec_context->sample_rate;
285 if ((error = av_frame_get_buffer(*frame, 0)) < 0)
287 printf(
"Could allocate output frame samples (error '%s')\n",
get_error_text(error));
288 av_frame_free(frame);
296 static int64_t pts = 0;
300 AVCodecContext* output_codec_context,
int* data_present)
303 AVPacket output_packet;
311 pts += frame->nb_samples;
318 if ((error = avcodec_encode_audio2(output_codec_context, &output_packet, frame, data_present)) <
321 printf(
"Could not encode frame (error '%s')\n",
get_error_text(error));
322 av_free_packet(&output_packet);
329 if ((error = av_write_frame(output_format_context, &output_packet)) < 0)
331 printf(
"Could not write frame (error '%s')\n",
get_error_text(error));
332 av_free_packet(&output_packet);
336 av_free_packet(&output_packet);
347 AVCodecContext* output_codec_context)
350 AVFrame* output_frame;
356 const int frame_size = FFMIN(av_audio_fifo_size(fifo), output_codec_context->frame_size);
367 if (av_audio_fifo_read(fifo, (
void**) output_frame->data, frame_size) < frame_size)
369 printf(
"Could not read data from FIFO\n");
370 av_frame_free(&output_frame);
378 av_frame_free(&output_frame);
381 av_frame_free(&output_frame);
389 if ((error = av_write_trailer(output_format_context)) < 0)
391 printf(
"Could not write output file trailer (error '%s')\n",
get_error_text(error));
416 static void log_packet(
const AVFormatContext* fmt_ctx,
const AVPacket* pkt)
418 AVRational* time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
420 printf(
"pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
421 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, time_base), av_ts2str(pkt->dts),
422 av_ts2timestr(pkt->dts, time_base), av_ts2str(pkt->duration),
423 av_ts2timestr(pkt->duration, time_base), pkt->stream_index);
428 static void add_stream(
OutputStream* ost, AVFormatContext* oc, AVCodec** codec,
429 enum AVCodecID codec_id)
435 *codec = avcodec_find_encoder(codec_id);
438 printf(
"Could not find encoder for '%s'\n", avcodec_get_name(codec_id));
442 ost->
st = avformat_new_stream(oc, *codec);
445 printf(
"Could not allocate stream\n");
448 ost->
st->id = oc->nb_streams - 1;
450 switch ((*codec)->type)
452 case AVMEDIA_TYPE_AUDIO:
453 c->sample_fmt = (*codec)->sample_fmts ? (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLT;
455 c->sample_rate = 44100;
456 if ((*codec)->supported_samplerates)
458 c->sample_rate = (*codec)->supported_samplerates[0];
459 for (i = 0; (*codec)->supported_samplerates[i]; i++)
461 if ((*codec)->supported_samplerates[i] == 44100)
462 c->sample_rate = 44100;
465 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
466 c->channel_layout = AV_CH_LAYOUT_STEREO;
467 if ((*codec)->channel_layouts)
469 c->channel_layout = (*codec)->channel_layouts[0];
470 for (i = 0; (*codec)->channel_layouts[i]; i++)
472 if ((*codec)->channel_layouts[i] == AV_CH_LAYOUT_STEREO)
473 c->channel_layout = AV_CH_LAYOUT_STEREO;
476 ost->
st->time_base = (AVRational){1, c->sample_rate};
485 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
491 static AVFrame* alloc_audio_frame(
enum AVSampleFormat sample_fmt, uint64_t channel_layout,
492 int sample_rate,
int nb_samples)
494 AVFrame* frame = av_frame_alloc();
498 printf(
"Error allocating an audio frame\n");
502 frame->format = sample_fmt;
503 frame->channel_layout = channel_layout;
504 frame->sample_rate = sample_rate;
505 frame->nb_samples = nb_samples;
510 ret = av_frame_get_buffer(frame, 0);
513 printf(
"Error allocating an audio buffer\n");
521 static void open_audio(AVCodec* codec,
OutputStream* ost, AVDictionary* opt_arg)
526 AVDictionary* opt = NULL;
531 av_dict_copy(&opt, opt_arg, 0);
532 ret = avcodec_open2(c, codec, &opt);
536 printf(
"Could not open audio codec: %s\n", av_err2str(ret));
546 nb_samples = c->frame_size;
548 ost->
frame = alloc_audio_frame(c->sample_fmt, c->channel_layout, c->sample_rate, nb_samples);
550 alloc_audio_frame(AV_SAMPLE_FMT_FLT, c->channel_layout, c->sample_rate, nb_samples);
556 printf(
"Could not allocate resampler context\n");
561 av_opt_set_int(ost->
swr_ctx,
"in_channel_count", c->channels, 0);
562 av_opt_set_int(ost->
swr_ctx,
"in_sample_rate", c->sample_rate, 0);
563 av_opt_set_sample_fmt(ost->
swr_ctx,
"in_sample_fmt", AV_SAMPLE_FMT_FLT, 0);
564 av_opt_set_int(ost->
swr_ctx,
"out_channel_count", c->channels, 0);
565 av_opt_set_int(ost->
swr_ctx,
"out_sample_rate", c->sample_rate, 0);
566 av_opt_set_sample_fmt(ost->
swr_ctx,
"out_sample_fmt", AV_SAMPLE_FMT_FLT, 0);
569 if (swr_init(ost->
swr_ctx) < 0)
571 printf(
"Failed to initialize the resampling context\n");
577 int num_read,
int size)
579 avcodec_register_all();
582 AVCodecContext* codecContext = NULL;
584 uint8_t memBuffer[size + FF_INPUT_BUFFER_PADDING_SIZE];
586 AVFrame* decoded_frame_mem = NULL;
588 av_init_packet(&memPkt);
593 codec = avcodec_find_decoder(AV_CODEC_ID_PCM_S16LE);
596 printf(
"codec not found\n");
600 codecContext = avcodec_alloc_context3(codec);
602 codecContext->bit_rate = 64000;
603 codecContext->sample_fmt = AV_SAMPLE_FMT_S16;
604 codecContext->sample_rate = 44100;
605 codecContext->channel_layout = AV_CH_LAYOUT_STEREO;
606 codecContext->channels = av_get_channel_layout_nb_channels(codecContext->channel_layout);
609 if (avcodec_open2(codecContext, codec, NULL) < 0)
611 printf(
"could not open codec\n");
616 memPkt.data = memBuffer;
617 memPkt.size = num_read;
618 memcpy(memBuffer, inbuf, num_read);
620 AVCodecContext* output_codec_context = NULL;
621 SwrContext* resample_context = NULL;
622 uint8_t** converted_input_samples = NULL;
623 AVAudioFifo* fifo = NULL;
625 output_codec_context = ost->
st->codec;
627 init_resampler(codecContext, output_codec_context, &resample_context);
629 while (memPkt.size > 0)
631 int got_frame_mem = 0;
634 if (!decoded_frame_mem)
636 if (!(decoded_frame_mem = av_frame_alloc()))
638 printf(
"out of memory\n");
644 av_frame_unref(decoded_frame_mem);
647 length = avcodec_decode_audio4(codecContext, decoded_frame_mem, &got_frame_mem, &memPkt);
651 printf(
"Error while decoding\n");
656 av_samples_get_buffer_size(NULL, codecContext->channels, decoded_frame_mem->nb_samples,
657 codecContext->sample_fmt, 1);
659 output_codec_context->frame_size = decoded_frame_mem->nb_samples;
662 const int output_frame_size = output_codec_context->frame_size;
672 while (av_audio_fifo_size(fifo) < output_frame_size)
682 decoded_frame_mem->nb_samples))
683 printf(
"Audio decoding A\n");
690 if (
convert_samples((
const uint8_t**) decoded_frame_mem->extended_data,
691 converted_input_samples, decoded_frame_mem->nb_samples,
693 printf(
"Audio decoding B\n");
697 decoded_frame_mem->nb_samples))
698 printf(
"Audio decoding C\n");
714 while (av_audio_fifo_size(fifo) >= output_frame_size ||
715 (finished && av_audio_fifo_size(fifo) > 0))
723 printf(
"Audio decoding D\n");
728 memPkt.size -= length;
729 memPkt.data += length;
731 if (memPkt.size < 4090)
737 memmove(inbuf, memPkt.data, memPkt.size);
741 memPkt.size += length;
745 avcodec_close(codecContext);
746 av_free(codecContext);
756 unsigned char* buffer;
760 buffer = malloc(size);
765 num_read = recv(outsocket, buffer, size, 0);
767 }
while (num_read > 0);
775 avcodec_close(ost->
st->codec);
776 av_frame_free(&ost->
frame);
787 const char* filename;
790 AVCodec* audio_codec;
793 AVDictionary* opt = NULL;
795 LOGI(
"avcodec - register all formats and codecs");
797 avformat_network_init();
799 filename =
"http://ffserver:8090/audio.ffm";
802 avformat_alloc_output_context2(&oc, NULL,
"ffm", filename);
806 printf(
"Could not deduce output format from file extension: using OGG.\n");
807 avformat_alloc_output_context2(&oc, NULL,
"ogg", filename);
816 if (fmt->audio_codec != AV_CODEC_ID_NONE)
818 add_stream(&audio_st, oc, &audio_codec, AV_CODEC_ID_VORBIS);
820 LOGW(
"No audio stream");
826 open_audio(audio_codec, &audio_st, opt);
831 if (!(fmt->flags & AVFMT_NOFILE))
833 ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
836 printf(
"Could not open '%s': %s\n", filename, av_err2str(ret));
842 ret = avformat_write_header(oc, &opt);
845 printf(
"Error occurred when opening output file: %s\n", av_err2str(ret));
848 av_dump_format(oc, 0, filename, 1);
852 while (outsocket == -1)
854 LOGI(
" B outsocket -> %d", outsocket);
860 read_audio_frame(oc, &audio_st, outsocket);
871 close_stream(&audio_st);
873 if (!(fmt->flags & AVFMT_NOFILE))
875 avio_closep(&oc->pb);
878 avformat_free_context(oc);
Utilities to get config values from the environment.
A wrapper around a single output AVStream.
int init_output_frame(AVFrame **frame, AVCodecContext *output_codec_context, int frame_size)
int convert_samples(const uint8_t **input_data, uint8_t **converted_data, const int frame_size, SwrContext *resample_context)
void * aic_audioplayer(char *vmip)
int load_encode_and_write(AVAudioFifo *fifo, AVFormatContext *output_format_context, AVCodecContext *output_codec_context)
int init_fifo(AVAudioFifo **fifo, AVCodecContext *output_codec_context)
struct OutputStream OutputStream
int socket_t
Alias to differenciate between regular ints and socket fds.
const char * get_error_text(const int error)
void audiolive_decode_encode(AVFormatContext *oc, OutputStream *ost, unsigned char *inbuf, int num_read, int size)
socket_t open_socket(const char *ip, short port)
Connect to a host:port couple.
char * configvar_string(char *varname)
Get the value of a config variable from the env.
int encode_audio_frame(AVFrame *frame, AVFormatContext *output_format_context, AVCodecContext *output_codec_context, int *data_present)
void init_packet(AVPacket *packet)
int decode_audio_frame(AVFrame *frame, AVFormatContext *input_format_context, AVCodecContext *input_codec_context, int *data_present, int *finished)
struct SwrContext * swr_ctx
int init_input_frame(AVFrame **frame)
int init_resampler(AVCodecContext *input_codec_context, AVCodecContext *output_codec_context, SwrContext **resample_context)
int add_samples_to_fifo(AVAudioFifo *fifo, uint8_t **converted_input_samples, const int frame_size)
int init_converted_samples(uint8_t ***converted_input_samples, AVCodecContext *output_codec_context, int frame_size)
#define ANDROIDINCLOUD_PCM_CLIENT_PORT
#define LOGW(...)
Log at WARNING level.
Define socket utilities to simplify networking.
struct SwsContext * sws_ctx
int write_output_file_trailer(AVFormatContext *output_format_context)
#define LOGI(...)
Log at INFO level.