2 Copyright (C) 2013 Paul Brossier <piem@aubio.org>
4 This file is part of aubio.
6 aubio is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 aubio is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with aubio. If not, see <http://www.gnu.org/licenses/>.
21 #include "aubio_priv.h"
25 #include <libavcodec/avcodec.h>
26 #include <libavformat/avformat.h>
27 #if defined(HAVE_SWRESAMPLE)
28 #include <libswresample/swresample.h>
29 #elif defined(HAVE_AVRESAMPLE)
30 #include <libavresample/avresample.h>
32 #include <libavutil/opt.h>
35 // determine whether we use libavformat from ffmpeg or from libav
36 #define FFMPEG_LIBAVFORMAT (LIBAVFORMAT_VERSION_MICRO > 99 )
37 // max_analyze_duration2 was used from ffmpeg libavformat 55.43.100 through 57.2.100
38 #define FFMPEG_LIBAVFORMAT_MAX_DUR2 FFMPEG_LIBAVFORMAT && ( \
39 (LIBAVFORMAT_VERSION_MAJOR == 55 && LIBAVFORMAT_VERSION_MINOR >= 43) \
40 || (LIBAVFORMAT_VERSION_MAJOR == 56) \
41 || (LIBAVFORMAT_VERSION_MAJOR == 57 && LIBAVFORMAT_VERSION_MINOR < 2) \
44 // backward compatibility with libavcodec55
45 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57,0,0)
46 #define HAVE_AUBIO_LIBAVCODEC_DEPRECATED 1
49 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
50 #warning "libavcodec < 56 is deprecated"
51 #define av_frame_alloc avcodec_alloc_frame
52 #define av_frame_free avcodec_free_frame
53 #define av_packet_unref av_free_packet
56 #include "aubio_priv.h"
59 #include "source_avcodec.h"
61 #define AUBIO_AVCODEC_MAX_BUFFER_SIZE FF_MIN_BUFFER_SIZE
63 struct _aubio_source_avcodec_t {
68 // some data about the file
70 uint_t input_samplerate;
71 uint_t input_channels;
74 AVFormatContext *avFormatCtx;
75 AVCodecContext *avCodecCtx;
78 #ifdef HAVE_AVRESAMPLE
79 AVAudioResampleContext *avr;
80 #elif defined(HAVE_SWRESAMPLE)
86 sint_t selected_stream;
91 // hack to create or re-create the context the first time _do or _do_multi is called
92 void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s, uint_t multi);
93 void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples);
95 uint_t aubio_source_avcodec_has_network_url(aubio_source_avcodec_t *s);
97 uint_t aubio_source_avcodec_has_network_url(aubio_source_avcodec_t *s) {
98 char proto[20], authorization[256], hostname[128], uripath[256];
99 int proto_size = 20, authorization_size = 256, hostname_size = 128,
100 *port_ptr = 0, path_size = 256;
101 av_url_split(proto, proto_size, authorization, authorization_size, hostname,
102 hostname_size, port_ptr, uripath, path_size, s->path);
110 aubio_source_avcodec_t * new_aubio_source_avcodec(const char_t * path, uint_t samplerate, uint_t hop_size) {
111 aubio_source_avcodec_t * s = AUBIO_NEW(aubio_source_avcodec_t);
112 AVFormatContext *avFormatCtx = s->avFormatCtx;
113 AVCodecContext *avCodecCtx = s->avCodecCtx;
115 AVFrame *avFrame = s->avFrame;
117 sint_t selected_stream = -1;
120 AUBIO_ERR("source_avcodec: Aborted opening null path\n");
123 if ((sint_t)samplerate < 0) {
124 AUBIO_ERR("source_avcodec: Can not open %s with samplerate %d\n", path, samplerate);
127 if ((sint_t)hop_size <= 0) {
128 AUBIO_ERR("source_avcodec: Can not open %s with hop_size %d\n", path, hop_size);
132 s->hop_size = hop_size;
135 if (s->path) AUBIO_FREE(s->path);
136 s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
137 strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
139 // register all formats and codecs
142 if (aubio_source_avcodec_has_network_url(s)) {
143 avformat_network_init();
146 // try opening the file and get some info about it
148 if ( (err = avformat_open_input(&avFormatCtx, s->path, NULL, NULL) ) < 0 ) {
150 av_strerror (err, errorstr, sizeof(errorstr));
151 AUBIO_ERR("source_avcodec: Failed opening %s (%s)\n", s->path, errorstr);
155 // try to make sure max_analyze_duration is big enough for most songs
156 #if FFMPEG_LIBAVFORMAT_MAX_DUR2
157 avFormatCtx->max_analyze_duration2 *= 100;
159 avFormatCtx->max_analyze_duration *= 100;
162 // retrieve stream information
163 if ( (err = avformat_find_stream_info(avFormatCtx, NULL)) < 0 ) {
165 av_strerror (err, errorstr, sizeof(errorstr));
166 AUBIO_ERR("source_avcodec: Could not find stream information " "for %s (%s)\n", s->path,
171 // dump information about file onto standard error
172 //av_dump_format(avFormatCtx, 0, s->path, 0);
174 // look for the first audio stream
175 for (i = 0; i < avFormatCtx->nb_streams; i++) {
176 #if FF_API_LAVF_AVCTX
177 if (avFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
179 if (avFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
181 if (selected_stream == -1) {
184 AUBIO_WRN("source_avcodec: More than one audio stream in %s, "
185 "taking the first one\n", s->path);
189 if (selected_stream == -1) {
190 AUBIO_ERR("source_avcodec: No audio stream in %s\n", s->path);
193 //AUBIO_DBG("Taking stream %d in file %s\n", selected_stream, s->path);
194 s->selected_stream = selected_stream;
196 #if FF_API_LAVF_AVCTX
197 AVCodecParameters *codecpar = avFormatCtx->streams[selected_stream]->codecpar;
198 if (codecpar == NULL) {
199 AUBIO_ERR("source_avcodec: Could not find decoder for %s", s->path);
202 codec = avcodec_find_decoder(codecpar->codec_id);
204 /* Allocate a codec context for the decoder */
205 avCodecCtx = avcodec_alloc_context3(codec);
207 AUBIO_ERR("source_avcodec: Failed to allocate the %s codec context for path %s\n",
208 av_get_media_type_string(AVMEDIA_TYPE_AUDIO), s->path);
212 avCodecCtx = avFormatCtx->streams[selected_stream]->codec;
213 AVCodec *codec = avcodec_find_decoder(avCodecCtx->codec_id);
216 AUBIO_ERR("source_avcodec: Could not find decoder for %s", s->path);
220 #if FF_API_LAVF_AVCTX
221 /* Copy codec parameters from input stream to output codec context */
222 if ((err = avcodec_parameters_to_context(avCodecCtx, codecpar)) < 0) {
223 AUBIO_ERR("source_avcodec: Failed to copy %s codec parameters to decoder context for %s\n",
224 av_get_media_type_string(AVMEDIA_TYPE_AUDIO), s->path);
229 if ( ( err = avcodec_open2(avCodecCtx, codec, NULL) ) < 0) {
231 av_strerror (err, errorstr, sizeof(errorstr));
232 AUBIO_ERR("source_avcodec: Could not load codec for %s (%s)\n", s->path, errorstr);
236 /* get input specs */
237 s->input_samplerate = avCodecCtx->sample_rate;
238 s->input_channels = avCodecCtx->channels;
239 //AUBIO_DBG("input_samplerate: %d\n", s->input_samplerate);
240 //AUBIO_DBG("input_channels: %d\n", s->input_channels);
242 if (samplerate == 0) {
243 s->samplerate = s->input_samplerate;
245 s->samplerate = samplerate;
248 if (s->samplerate > s->input_samplerate) {
249 AUBIO_WRN("source_avcodec: upsampling %s from %d to %d\n", s->path,
250 s->input_samplerate, s->samplerate);
253 avFrame = av_frame_alloc();
255 AUBIO_ERR("source_avcodec: Could not allocate frame for (%s)\n", s->path);
258 /* allocate output for avr */
259 s->output = (smpl_t *)av_malloc(AUBIO_AVCODEC_MAX_BUFFER_SIZE * sizeof(smpl_t));
264 s->avFormatCtx = avFormatCtx;
265 s->avCodecCtx = avCodecCtx;
266 s->avFrame = avFrame;
268 // default to mono output
269 aubio_source_avcodec_reset_resampler(s, 0);
274 //av_log_set_level(AV_LOG_QUIET);
279 //AUBIO_ERR("can not read %s at samplerate %dHz with a hop_size of %d\n",
280 // s->path, s->samplerate, s->hop_size);
281 del_aubio_source_avcodec(s);
285 void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s, uint_t multi) {
286 // create or reset resampler to/from mono/multi-channel
287 if ( (multi != s->multi) || (s->avr == NULL) ) {
288 int64_t input_layout = av_get_default_channel_layout(s->input_channels);
289 uint_t output_channels = multi ? s->input_channels : 1;
290 int64_t output_layout = av_get_default_channel_layout(output_channels);
291 #ifdef HAVE_AVRESAMPLE
292 AVAudioResampleContext *avr = avresample_alloc_context();
293 AVAudioResampleContext *oldavr = s->avr;
294 #elif defined(HAVE_SWRESAMPLE)
295 SwrContext *avr = swr_alloc();
296 SwrContext *oldavr = s->avr;
297 #endif /* HAVE_AVRESAMPLE || HAVE_SWRESAMPLE */
299 av_opt_set_int(avr, "in_channel_layout", input_layout, 0);
300 av_opt_set_int(avr, "out_channel_layout", output_layout, 0);
301 av_opt_set_int(avr, "in_sample_rate", s->input_samplerate, 0);
302 av_opt_set_int(avr, "out_sample_rate", s->samplerate, 0);
303 av_opt_set_int(avr, "in_sample_fmt", s->avCodecCtx->sample_fmt, 0);
304 #if HAVE_AUBIO_DOUBLE
305 av_opt_set_int(avr, "out_sample_fmt", AV_SAMPLE_FMT_DBL, 0);
307 av_opt_set_int(avr, "out_sample_fmt", AV_SAMPLE_FMT_FLT, 0);
310 //av_opt_set_int(avr, "out_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
312 #ifdef HAVE_AVRESAMPLE
313 if ( ( err = avresample_open(avr) ) < 0) {
314 #elif defined(HAVE_SWRESAMPLE)
315 if ( ( err = swr_init(avr) ) < 0) {
316 #endif /* HAVE_AVRESAMPLE || HAVE_SWRESAMPLE */
318 av_strerror (err, errorstr, sizeof(errorstr));
319 AUBIO_ERR("source_avcodec: Could not open AVAudioResampleContext for %s (%s)\n",
325 if (oldavr != NULL) {
326 #ifdef HAVE_AVRESAMPLE
327 avresample_close( oldavr );
328 #elif defined(HAVE_SWRESAMPLE)
329 swr_close ( oldavr );
330 #endif /* HAVE_AVRESAMPLE || HAVE_SWRESAMPLE */
338 void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples) {
339 AVFormatContext *avFormatCtx = s->avFormatCtx;
340 AVCodecContext *avCodecCtx = s->avCodecCtx;
341 AVFrame *avFrame = s->avFrame;
342 AVPacket avPacket = s->avPacket;
343 av_init_packet (&avPacket);
344 #ifdef HAVE_AVRESAMPLE
345 AVAudioResampleContext *avr = s->avr;
346 #elif defined(HAVE_SWRESAMPLE)
347 SwrContext *avr = s->avr;
348 #endif /* HAVE_AVRESAMPLE || HAVE_SWRESAMPLE */
349 smpl_t *output = s->output;
354 int err = av_read_frame (avFormatCtx, &avPacket);
355 if (err == AVERROR_EOF) {
361 av_strerror (err, errorstr, sizeof(errorstr));
362 AUBIO_ERR("source_avcodec: could not read frame in %s (%s)\n", s->path, errorstr);
366 } while (avPacket.stream_index != s->selected_stream);
369 #if FF_API_LAVF_AVCTX
370 int ret = avcodec_send_packet(avCodecCtx, &avPacket);
371 if (ret < 0 && ret != AVERROR_EOF) {
372 AUBIO_ERR("source_avcodec: error when sending packet for %s\n", s->path);
375 ret = avcodec_receive_frame(avCodecCtx, avFrame);
380 if (ret == AVERROR(EAGAIN)) {
381 //AUBIO_WRN("source_avcodec: output is not available right now - user must try to send new input\n");
383 } else if (ret == AVERROR_EOF) {
384 AUBIO_WRN("source_avcodec: the decoder has been fully flushed, and there will be no more output frames\n");
386 AUBIO_ERR("source_avcodec: decoding errors on %s\n", s->path);
391 int len = avcodec_decode_audio4(avCodecCtx, avFrame, &got_frame, &avPacket);
394 AUBIO_ERR("source_avcodec: error while decoding %s\n", s->path);
398 if (got_frame == 0) {
399 AUBIO_WRN("source_avcodec: did not get a frame when reading %s\n", s->path);
403 #ifdef HAVE_AVRESAMPLE
405 av_samples_get_buffer_size(&in_linesize, avCodecCtx->channels,
406 avFrame->nb_samples, avCodecCtx->sample_fmt, 1);
407 int in_samples = avFrame->nb_samples;
408 int out_linesize = 0;
409 int max_out_samples = AUBIO_AVCODEC_MAX_BUFFER_SIZE;
410 int out_samples = avresample_convert ( avr,
411 (uint8_t **)&output, out_linesize, max_out_samples,
412 (uint8_t **)avFrame->data, in_linesize, in_samples);
413 #elif defined(HAVE_SWRESAMPLE)
414 int in_samples = avFrame->nb_samples;
415 int max_out_samples = AUBIO_AVCODEC_MAX_BUFFER_SIZE / avCodecCtx->channels;
416 int out_samples = swr_convert( avr,
417 (uint8_t **)&output, max_out_samples,
418 (const uint8_t **)avFrame->data, in_samples);
419 #endif /* HAVE_AVRESAMPLE || HAVE_SWRESAMPLE */
420 if (out_samples <= 0) {
421 AUBIO_WRN("source_avcodec: no sample found while converting frame (%s)\n", s->path);
425 *read_samples = out_samples;
428 s->avFormatCtx = avFormatCtx;
429 s->avCodecCtx = avCodecCtx;
430 s->avFrame = avFrame;
431 #if defined(HAVE_AVRESAMPLE) || defined(HAVE_SWRESAMPLE)
433 #endif /* HAVE_AVRESAMPLE || HAVE_SWRESAMPLE */
436 av_packet_unref(&avPacket);
439 void aubio_source_avcodec_do(aubio_source_avcodec_t * s, fvec_t * read_data, uint_t * read){
442 uint_t total_wrote = 0;
444 if (s->multi == 1) aubio_source_avcodec_reset_resampler(s, 0);
445 while (total_wrote < s->hop_size) {
446 end = MIN(s->read_samples - s->read_index, s->hop_size - total_wrote);
447 for (i = 0; i < end; i++) {
448 read_data->data[i + total_wrote] = s->output[i + s->read_index];
451 if (total_wrote < s->hop_size) {
452 uint_t avcodec_read = 0;
453 aubio_source_avcodec_readframe(s, &avcodec_read);
454 s->read_samples = avcodec_read;
460 s->read_index += end;
463 if (total_wrote < s->hop_size) {
464 for (i = total_wrote; i < s->hop_size; i++) {
465 read_data->data[i] = 0.;
471 void aubio_source_avcodec_do_multi(aubio_source_avcodec_t * s, fmat_t * read_data, uint_t * read){
474 uint_t total_wrote = 0;
476 if (s->multi == 0) aubio_source_avcodec_reset_resampler(s, 1);
477 while (total_wrote < s->hop_size) {
478 end = MIN(s->read_samples - s->read_index, s->hop_size - total_wrote);
479 for (j = 0; j < read_data->height; j++) {
480 for (i = 0; i < end; i++) {
481 read_data->data[j][i + total_wrote] =
482 s->output[(i + s->read_index) * s->input_channels + j];
486 if (total_wrote < s->hop_size) {
487 uint_t avcodec_read = 0;
488 aubio_source_avcodec_readframe(s, &avcodec_read);
489 s->read_samples = avcodec_read;
495 s->read_index += end;
498 if (total_wrote < s->hop_size) {
499 for (j = 0; j < read_data->height; j++) {
500 for (i = total_wrote; i < s->hop_size; i++) {
501 read_data->data[j][i] = 0.;
508 uint_t aubio_source_avcodec_get_samplerate(const aubio_source_avcodec_t * s) {
509 return s->samplerate;
512 uint_t aubio_source_avcodec_get_channels(const aubio_source_avcodec_t * s) {
513 return s->input_channels;
516 uint_t aubio_source_avcodec_seek (aubio_source_avcodec_t * s, uint_t pos) {
517 int64_t resampled_pos = (uint_t)ROUND(pos * (s->input_samplerate * 1. / s->samplerate));
518 int64_t min_ts = MAX(resampled_pos - 2000, 0);
519 int64_t max_ts = MIN(resampled_pos + 2000, INT64_MAX);
520 int seek_flags = AVSEEK_FLAG_FRAME | AVSEEK_FLAG_ANY;
521 int ret = AUBIO_FAIL;
522 if (s->avFormatCtx != NULL && s->avr != NULL) {
525 AUBIO_ERR("source_avcodec: failed seeking in %s (file not opened?)", s->path);
528 if ((sint_t)pos < 0) {
529 AUBIO_ERR("source_avcodec: could not seek %s at %d (seeking position"
530 " should be >= 0)\n", s->path, pos);
533 ret = avformat_seek_file(s->avFormatCtx, s->selected_stream,
534 min_ts, resampled_pos, max_ts, seek_flags);
536 AUBIO_ERR("source_avcodec: failed seeking to %d in file %s", pos, s->path);
542 #ifdef HAVE_AVRESAMPLE
543 // reset the AVAudioResampleContext
544 avresample_close(s->avr);
545 avresample_open(s->avr);
546 #elif defined(HAVE_SWRESAMPLE)
553 uint_t aubio_source_avcodec_get_duration (aubio_source_avcodec_t * s) {
554 if (s && &(s->avFormatCtx) != NULL) {
555 int64_t duration = s->avFormatCtx->duration;
556 return s->samplerate * ((uint_t)duration / 1e6 );
561 uint_t aubio_source_avcodec_close(aubio_source_avcodec_t * s) {
562 if (s->avr != NULL) {
563 #ifdef HAVE_AVRESAMPLE
564 avresample_close( s->avr );
565 #elif defined(HAVE_SWRESAMPLE)
566 swr_close ( s->avr );
571 if (s->avCodecCtx != NULL) {
572 #ifndef HAVE_AUBIO_LIBAVCODEC_DEPRECATED
573 avcodec_free_context( &s->avCodecCtx );
575 avcodec_close ( s->avCodecCtx );
578 s->avCodecCtx = NULL;
579 if (s->avFormatCtx != NULL) {
580 avformat_close_input(&s->avFormatCtx);
581 s->avFormatCtx = NULL;
583 av_packet_unref(&s->avPacket);
587 void del_aubio_source_avcodec(aubio_source_avcodec_t * s){
589 aubio_source_avcodec_close(s);
590 if (s->output != NULL) {
594 if (s->avFrame != NULL) {
595 av_frame_free( &(s->avFrame) );
605 #endif /* HAVE_LIBAV */