source: src/io/source_avcodec.c @ 2f4d9b7

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5pitchshiftsamplertimestretchyinfft+
Last change on this file since 2f4d9b7 was 9ac77ac, checked in by Paul Brossier <piem@piem.org>, 9 years ago

src/io/source_avcodec.c: really fix #53

  • Property mode set to 100644
File size: 13.2 KB
RevLine 
[ba0ba10]1/*
2  Copyright (C) 2013 Paul Brossier <piem@aubio.org>
3
4  This file is part of aubio.
5
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.
10
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.
15
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/>.
18
19*/
20
21
22#include "config.h"
23
[549928e]24#ifdef HAVE_LIBAV
[ba0ba10]25
[a9c33a2]26// determine whether we use libavformat from ffmpeg or from libav
27#define FFMPEG_LIBAVFORMAT (LIBAVFORMAT_VERSION_MICRO > 99 )
28// max_analyze_duration2 was used from ffmpeg libavformat 55.43.100 through 57.2.100
[9ac77ac]29#define FFMPEG_LIBAVFORMAT_MAX_DUR2 FFMPEG_LIBAVFORMAT && ( \
[a9c33a2]30      (LIBAVFORMAT_VERSION_MAJOR == 55 && LIBAVFORMAT_VERSION_MINOR >= 43) \
31      || (LIBAVFORMAT_VERSION_MAJOR == 56) \
32      || (LIBAVFORMAT_VERSION_MAJOR == 57 && LIBAVFORMAT_VERSION_MINOR < 2) \
33      )
[2a32644]34
[ba0ba10]35#include <libavcodec/avcodec.h>
36#include <libavformat/avformat.h>
37#include <libavresample/avresample.h>
38#include <libavutil/opt.h>
39#include <stdlib.h>
40
41#include "aubio_priv.h"
42#include "fvec.h"
43#include "fmat.h"
44#include "source_avcodec.h"
45
[0af9003]46#define AUBIO_AVCODEC_MAX_BUFFER_SIZE FF_MIN_BUFFER_SIZE
[ba0ba10]47
48struct _aubio_source_avcodec_t {
49  uint_t hop_size;
50  uint_t samplerate;
51  uint_t channels;
52
53  // some data about the file
54  char_t *path;
[d3b9fe4]55  uint_t input_samplerate;
56  uint_t input_channels;
[ba0ba10]57
58  // avcodec stuff
59  AVFormatContext *avFormatCtx;
60  AVCodecContext *avCodecCtx;
61  AVFrame *avFrame;
62  AVAudioResampleContext *avr;
[3d5cddf]63  float *output;
[d3b9fe4]64  uint_t read_samples;
65  uint_t read_index;
[7760b40]66  sint_t selected_stream;
[eadd8d5]67  uint_t eof;
[fcd963a]68  uint_t multi;
[ba0ba10]69};
70
[61ecd1a]71// hack to create or re-create the context the first time _do or _do_multi is called
72void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s, uint_t multi);
[029bf4e]73void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples);
[fcd963a]74
[ae5d58a]75aubio_source_avcodec_t * new_aubio_source_avcodec(const char_t * path, uint_t samplerate, uint_t hop_size) {
[ba0ba10]76  aubio_source_avcodec_t * s = AUBIO_NEW(aubio_source_avcodec_t);
77  int err;
78  if (path == NULL) {
[491e6ea]79    AUBIO_ERR("source_avcodec: Aborted opening null path\n");
[b294b3e]80    goto beach;
81  }
82  if ((sint_t)samplerate < 0) {
[491e6ea]83    AUBIO_ERR("source_avcodec: Can not open %s with samplerate %d\n", path, samplerate);
[b294b3e]84    goto beach;
85  }
86  if ((sint_t)hop_size <= 0) {
[491e6ea]87    AUBIO_ERR("source_avcodec: Can not open %s with hop_size %d\n", path, hop_size);
[b294b3e]88    goto beach;
[ba0ba10]89  }
90
91  s->hop_size = hop_size;
92  s->channels = 1;
[b643a33]93
94  if (s->path) AUBIO_FREE(s->path);
[d2be104]95  s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
96  strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
[ba0ba10]97
98  // register all formats and codecs
99  av_register_all();
100
[eadd8d5]101  // if path[0] != '/'
102  //avformat_network_init();
103
[d75e2d5]104  // try opening the file and get some info about it
[ba0ba10]105  AVFormatContext *avFormatCtx = s->avFormatCtx;
106  avFormatCtx = NULL;
107  if ( (err = avformat_open_input(&avFormatCtx, s->path, NULL, NULL) ) < 0 ) {
[0af9003]108    char errorstr[256];
109    av_strerror (err, errorstr, sizeof(errorstr));
[491e6ea]110    AUBIO_ERR("source_avcodec: Failed opening %s (%s)\n", s->path, errorstr);
[ba0ba10]111    goto beach;
112  }
113
[6abb4de]114  // try to make sure max_analyze_duration is big enough for most songs
[a9c33a2]115#if FFMPEG_LIBAVFORMAT_MAX_DUR2
[2a32644]116  avFormatCtx->max_analyze_duration2 *= 100;
117#else
[6abb4de]118  avFormatCtx->max_analyze_duration *= 100;
[2a32644]119#endif
[6abb4de]120
[ba0ba10]121  // retrieve stream information
122  if ( (err = avformat_find_stream_info(avFormatCtx, NULL)) < 0 ) {
[0af9003]123    char errorstr[256];
124    av_strerror (err, errorstr, sizeof(errorstr));
[491e6ea]125    AUBIO_ERR("source_avcodec: Could not find stream information " "for %s (%s)\n", s->path,
[0af9003]126        errorstr);
[ba0ba10]127    goto beach;
128  }
129
[1fe3ac2]130  // dump information about file onto standard error
[ba0ba10]131  //av_dump_format(avFormatCtx, 0, s->path, 0);
132
[1fe3ac2]133  // look for the first audio stream
[ba0ba10]134  uint_t i;
135  sint_t selected_stream = -1;
136  for (i = 0; i < avFormatCtx->nb_streams; i++) {
137    if (avFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
138      if (selected_stream == -1) {
139        selected_stream = i;
140      } else {
[491e6ea]141        AUBIO_WRN("source_avcodec: More than one audio stream in %s, "
[1fe3ac2]142            "taking the first one\n", s->path);
[ba0ba10]143      }
144    }
145  }
146  if (selected_stream == -1) {
[491e6ea]147    AUBIO_ERR("source_avcodec: No audio stream in %s\n", s->path);
[ba0ba10]148    goto beach;
[d3b9fe4]149  }
[eadd8d5]150  //AUBIO_DBG("Taking stream %d in file %s\n", selected_stream, s->path);
[7760b40]151  s->selected_stream = selected_stream;
[ba0ba10]152
153  AVCodecContext *avCodecCtx = s->avCodecCtx;
[d3b9fe4]154  avCodecCtx = avFormatCtx->streams[selected_stream]->codec;
[ba0ba10]155  AVCodec *codec = avcodec_find_decoder(avCodecCtx->codec_id);
156  if (codec == NULL) {
[491e6ea]157    AUBIO_ERR("source_avcodec: Could not find decoder for %s", s->path);
[ba0ba10]158    goto beach;
159  }
160
161  if ( ( err = avcodec_open2(avCodecCtx, codec, NULL) ) < 0) {
[0af9003]162    char errorstr[256];
163    av_strerror (err, errorstr, sizeof(errorstr));
[491e6ea]164    AUBIO_ERR("source_avcodec: Could not load codec for %s (%s)\n", s->path, errorstr);
[ba0ba10]165    goto beach;
166  }
167
168  /* get input specs */
169  s->input_samplerate = avCodecCtx->sample_rate;
170  s->input_channels   = avCodecCtx->channels;
171  //AUBIO_DBG("input_samplerate: %d\n", s->input_samplerate);
172  //AUBIO_DBG("input_channels: %d\n", s->input_channels);
173
174  if (samplerate == 0) {
[26a6af7]175    s->samplerate = s->input_samplerate;
176  } else {
177    s->samplerate = samplerate;
[ba0ba10]178  }
179
[018e511]180  if (s->samplerate >  s->input_samplerate) {
[491e6ea]181    AUBIO_WRN("source_avcodec: upsampling %s from %d to %d\n", s->path,
[018e511]182        s->input_samplerate, s->samplerate);
183  }
184
[ba0ba10]185  AVFrame *avFrame = s->avFrame;
[cd4c997]186  avFrame = av_frame_alloc();
[ba0ba10]187  if (!avFrame) {
[491e6ea]188    AUBIO_ERR("source_avcodec: Could not allocate frame for (%s)\n", s->path);
[ba0ba10]189  }
190
[d3b9fe4]191  /* allocate output for avr */
[0af9003]192  s->output = (float *)av_malloc(AUBIO_AVCODEC_MAX_BUFFER_SIZE * sizeof(float));
[ba0ba10]193
194  s->read_samples = 0;
195  s->read_index = 0;
196
197  s->avFormatCtx = avFormatCtx;
198  s->avCodecCtx = avCodecCtx;
199  s->avFrame = avFrame;
[fcd963a]200
201  // default to mono output
[61ecd1a]202  aubio_source_avcodec_reset_resampler(s, 0);
[ba0ba10]203
[eadd8d5]204  s->eof = 0;
[fcd963a]205  s->multi = 0;
[eadd8d5]206
[ba0ba10]207  //av_log_set_level(AV_LOG_QUIET);
208
209  return s;
210
211beach:
[fcd963a]212  //AUBIO_ERR("can not read %s at samplerate %dHz with a hop_size of %d\n",
213  //    s->path, s->samplerate, s->hop_size);
[ba0ba10]214  del_aubio_source_avcodec(s);
215  return NULL;
216}
217
[61ecd1a]218void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s, uint_t multi) {
219  if ( (multi != s->multi) || (s->avr == NULL) ) {
220    int64_t input_layout = av_get_default_channel_layout(s->input_channels);
221    uint_t output_channels = multi ? s->input_channels : 1;
222    int64_t output_layout = av_get_default_channel_layout(output_channels);
223    if (s->avr != NULL) {
224      avresample_close( s->avr );
225      av_free ( s->avr );
226      s->avr = NULL;
227    }
228    AVAudioResampleContext *avr = s->avr;
229    avr = avresample_alloc_context();
230
231    av_opt_set_int(avr, "in_channel_layout",  input_layout,           0);
232    av_opt_set_int(avr, "out_channel_layout", output_layout,          0);
233    av_opt_set_int(avr, "in_sample_rate",     s->input_samplerate,    0);
234    av_opt_set_int(avr, "out_sample_rate",    s->samplerate,          0);
235    av_opt_set_int(avr, "in_sample_fmt",      s->avCodecCtx->sample_fmt, 0);
236    av_opt_set_int(avr, "out_sample_fmt",     AV_SAMPLE_FMT_FLT,      0);
237    int err;
238    if ( ( err = avresample_open(avr) ) < 0) {
239      char errorstr[256];
240      av_strerror (err, errorstr, sizeof(errorstr));
[491e6ea]241      AUBIO_ERR("source_avcodec: Could not open AVAudioResampleContext for %s (%s)\n",
[61ecd1a]242          s->path, errorstr);
243      //goto beach;
244      return;
245    }
246    s->avr = avr;
247    s->multi = multi;
248  }
249}
250
[d3b9fe4]251void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples) {
[ba0ba10]252  AVFormatContext *avFormatCtx = s->avFormatCtx;
253  AVCodecContext *avCodecCtx = s->avCodecCtx;
254  AVFrame *avFrame = s->avFrame;
[f3b93c6]255  AVPacket avPacket;
256  av_init_packet (&avPacket);
[ba0ba10]257  AVAudioResampleContext *avr = s->avr;
[3d5cddf]258  float *output = s->output;
[0af9003]259  *read_samples = 0;
[ba0ba10]260
[7760b40]261  do
262  {
263    int err = av_read_frame (avFormatCtx, &avPacket);
[0af9003]264    if (err == AVERROR_EOF) {
265      s->eof = 1;
266      goto beach;
267    }
[7760b40]268    if (err != 0) {
[0af9003]269      char errorstr[256];
270      av_strerror (err, errorstr, sizeof(errorstr));
271      AUBIO_ERR("Could not read frame in %s (%s)\n", s->path, errorstr);
272      goto beach;
[7760b40]273    }
274  } while (avPacket.stream_index != s->selected_stream);
[ba0ba10]275
276  int got_frame = 0;
277  int len = avcodec_decode_audio4(avCodecCtx, avFrame, &got_frame, &avPacket);
278
279  if (len < 0) {
280    AUBIO_ERR("Error while decoding %s\n", s->path);
[0af9003]281    goto beach;
[ba0ba10]282  }
283  if (got_frame == 0) {
[eadd8d5]284    //AUBIO_ERR("Could not get frame for (%s)\n", s->path);
[0af9003]285    goto beach;
286  }
287
288  int in_linesize = 0;
289  av_samples_get_buffer_size(&in_linesize, avCodecCtx->channels,
290      avFrame->nb_samples, avCodecCtx->sample_fmt, 1);
[ba0ba10]291  int in_samples = avFrame->nb_samples;
[0af9003]292  int out_linesize = 0;
293  int max_out_samples = AUBIO_AVCODEC_MAX_BUFFER_SIZE;
[0044b43]294  int out_samples = avresample_convert ( avr,
[0af9003]295        (uint8_t **)&output, out_linesize, max_out_samples,
296        (uint8_t **)avFrame->data, in_linesize, in_samples);
297  if (out_samples <= 0) {
[5c6acbb2]298    //AUBIO_ERR("No sample found while converting frame (%s)\n", s->path);
[0af9003]299    goto beach;
[ba0ba10]300  }
301
[0af9003]302  *read_samples = out_samples;
303
304beach:
[ba0ba10]305  s->avFormatCtx = avFormatCtx;
306  s->avCodecCtx = avCodecCtx;
307  s->avFrame = avFrame;
308  s->avr = avr;
309  s->output = output;
310
[a9c33a2]311  av_packet_unref(&avPacket);
[ba0ba10]312}
313
314void aubio_source_avcodec_do(aubio_source_avcodec_t * s, fvec_t * read_data, uint_t * read){
[61ecd1a]315  if (s->multi == 1) aubio_source_avcodec_reset_resampler(s, 0);
[ba0ba10]316  uint_t i;
[eadd8d5]317  uint_t end = 0;
318  uint_t total_wrote = 0;
319  while (total_wrote < s->hop_size) {
320    end = MIN(s->read_samples - s->read_index, s->hop_size - total_wrote);
321    for (i = 0; i < end; i++) {
[3d5cddf]322      read_data->data[i + total_wrote] = s->output[i + s->read_index];
[ba0ba10]323    }
[eadd8d5]324    total_wrote += end;
325    if (total_wrote < s->hop_size) {
326      uint_t avcodec_read = 0;
327      aubio_source_avcodec_readframe(s, &avcodec_read);
328      s->read_samples = avcodec_read;
329      s->read_index = 0;
330      if (s->eof) {
331        break;
[ba0ba10]332      }
[eadd8d5]333    } else {
334      s->read_index += end;
[ba0ba10]335    }
[eadd8d5]336  }
337  if (total_wrote < s->hop_size) {
338    for (i = end; i < s->hop_size; i++) {
339      read_data->data[i] = 0.;
[ba0ba10]340    }
341  }
[eadd8d5]342  *read = total_wrote;
[ba0ba10]343}
344
345void aubio_source_avcodec_do_multi(aubio_source_avcodec_t * s, fmat_t * read_data, uint_t * read){
[61ecd1a]346  if (s->multi == 0) aubio_source_avcodec_reset_resampler(s, 1);
[fcd963a]347  uint_t i,j;
348  uint_t end = 0;
349  uint_t total_wrote = 0;
350  while (total_wrote < s->hop_size) {
351    end = MIN(s->read_samples - s->read_index, s->hop_size - total_wrote);
352    for (j = 0; j < read_data->height; j++) {
353      for (i = 0; i < end; i++) {
354        read_data->data[j][i + total_wrote] =
355          s->output[(i + s->read_index) * s->input_channels + j];
356      }
357    }
358    total_wrote += end;
359    if (total_wrote < s->hop_size) {
360      uint_t avcodec_read = 0;
361      aubio_source_avcodec_readframe(s, &avcodec_read);
362      s->read_samples = avcodec_read;
363      s->read_index = 0;
364      if (s->eof) {
365        break;
366      }
367    } else {
368      s->read_index += end;
369    }
370  }
371  if (total_wrote < s->hop_size) {
372    for (j = 0; j < read_data->height; j++) {
373      for (i = end; i < s->hop_size; i++) {
374        read_data->data[j][i] = 0.;
375      }
376    }
377  }
378  *read = total_wrote;
[ba0ba10]379}
380
[ae5d58a]381uint_t aubio_source_avcodec_get_samplerate(const aubio_source_avcodec_t * s) {
[ba0ba10]382  return s->samplerate;
383}
384
[ae5d58a]385uint_t aubio_source_avcodec_get_channels(const aubio_source_avcodec_t * s) {
[ba0ba10]386  return s->input_channels;
387}
388
389uint_t aubio_source_avcodec_seek (aubio_source_avcodec_t * s, uint_t pos) {
[50bb325]390  int64_t resampled_pos = (uint_t)ROUND(pos * (s->input_samplerate * 1. / s->samplerate));
391  int64_t min_ts = MAX(resampled_pos - 2000, 0);
392  int64_t max_ts = MIN(resampled_pos + 2000, INT64_MAX);
393  int seek_flags = AVSEEK_FLAG_FRAME | AVSEEK_FLAG_ANY;
394  int ret = avformat_seek_file(s->avFormatCtx, s->selected_stream,
395      min_ts, resampled_pos, max_ts, seek_flags);
396  if (ret < 0) {
397    AUBIO_ERR("Failed seeking to %d in file %s", pos, s->path);
398  }
399  // reset read status
400  s->eof = 0;
401  s->read_index = 0;
402  s->read_samples = 0;
403  // reset the AVAudioResampleContext
404  avresample_close(s->avr);
405  avresample_open(s->avr);
406  return ret;
[ba0ba10]407}
408
[2d071ad]409uint_t aubio_source_avcodec_get_duration (aubio_source_avcodec_t * s) {
410  if (s && &(s->avFormatCtx) != NULL) {
411    int64_t duration = s->avFormatCtx->duration;
412    return s->samplerate * ((uint_t)duration / 1e6 );
413  }
414  return 0;
415}
416
[422452b]417uint_t aubio_source_avcodec_close(aubio_source_avcodec_t * s) {
[ba0ba10]418  if (s->avr != NULL) {
419    avresample_close( s->avr );
420    av_free ( s->avr );
421  }
422  s->avr = NULL;
423  if (s->avCodecCtx != NULL) {
424    avcodec_close ( s->avCodecCtx );
425  }
426  s->avCodecCtx = NULL;
427  if (s->avFormatCtx != NULL) {
428    avformat_close_input ( &(s->avFormatCtx) );
429  }
430  s->avFormatCtx = NULL;
[422452b]431  return AUBIO_OK;
432}
433
434void del_aubio_source_avcodec(aubio_source_avcodec_t * s){
435  if (!s) return;
436  aubio_source_avcodec_close(s);
437  if (s->output != NULL) {
438    av_free(s->output);
439  }
440  s->output = NULL;
441  if (s->avFrame != NULL) {
[cd4c997]442    av_frame_free( &(s->avFrame) );
[422452b]443  }
[b643a33]444  if (s->path) AUBIO_FREE(s->path);
[422452b]445  s->avFrame = NULL;
[ba0ba10]446  AUBIO_FREE(s);
447}
448
[549928e]449#endif /* HAVE_LIBAV */
Note: See TracBrowser for help on using the repository browser.