source: src/io/source_avcodec.c @ b1d37c0

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5pitchshiftsamplertimestretchyinfft+
Last change on this file since b1d37c0 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
Line 
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
24#ifdef HAVE_LIBAV
25
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
29#define FFMPEG_LIBAVFORMAT_MAX_DUR2 FFMPEG_LIBAVFORMAT && ( \
30      (LIBAVFORMAT_VERSION_MAJOR == 55 && LIBAVFORMAT_VERSION_MINOR >= 43) \
31      || (LIBAVFORMAT_VERSION_MAJOR == 56) \
32      || (LIBAVFORMAT_VERSION_MAJOR == 57 && LIBAVFORMAT_VERSION_MINOR < 2) \
33      )
34
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
46#define AUBIO_AVCODEC_MAX_BUFFER_SIZE FF_MIN_BUFFER_SIZE
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;
55  uint_t input_samplerate;
56  uint_t input_channels;
57
58  // avcodec stuff
59  AVFormatContext *avFormatCtx;
60  AVCodecContext *avCodecCtx;
61  AVFrame *avFrame;
62  AVAudioResampleContext *avr;
63  float *output;
64  uint_t read_samples;
65  uint_t read_index;
66  sint_t selected_stream;
67  uint_t eof;
68  uint_t multi;
69};
70
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);
73void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples);
74
75aubio_source_avcodec_t * new_aubio_source_avcodec(const char_t * path, uint_t samplerate, uint_t hop_size) {
76  aubio_source_avcodec_t * s = AUBIO_NEW(aubio_source_avcodec_t);
77  int err;
78  if (path == NULL) {
79    AUBIO_ERR("source_avcodec: Aborted opening null path\n");
80    goto beach;
81  }
82  if ((sint_t)samplerate < 0) {
83    AUBIO_ERR("source_avcodec: Can not open %s with samplerate %d\n", path, samplerate);
84    goto beach;
85  }
86  if ((sint_t)hop_size <= 0) {
87    AUBIO_ERR("source_avcodec: Can not open %s with hop_size %d\n", path, hop_size);
88    goto beach;
89  }
90
91  s->hop_size = hop_size;
92  s->channels = 1;
93
94  if (s->path) AUBIO_FREE(s->path);
95  s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
96  strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
97
98  // register all formats and codecs
99  av_register_all();
100
101  // if path[0] != '/'
102  //avformat_network_init();
103
104  // try opening the file and get some info about it
105  AVFormatContext *avFormatCtx = s->avFormatCtx;
106  avFormatCtx = NULL;
107  if ( (err = avformat_open_input(&avFormatCtx, s->path, NULL, NULL) ) < 0 ) {
108    char errorstr[256];
109    av_strerror (err, errorstr, sizeof(errorstr));
110    AUBIO_ERR("source_avcodec: Failed opening %s (%s)\n", s->path, errorstr);
111    goto beach;
112  }
113
114  // try to make sure max_analyze_duration is big enough for most songs
115#if FFMPEG_LIBAVFORMAT_MAX_DUR2
116  avFormatCtx->max_analyze_duration2 *= 100;
117#else
118  avFormatCtx->max_analyze_duration *= 100;
119#endif
120
121  // retrieve stream information
122  if ( (err = avformat_find_stream_info(avFormatCtx, NULL)) < 0 ) {
123    char errorstr[256];
124    av_strerror (err, errorstr, sizeof(errorstr));
125    AUBIO_ERR("source_avcodec: Could not find stream information " "for %s (%s)\n", s->path,
126        errorstr);
127    goto beach;
128  }
129
130  // dump information about file onto standard error
131  //av_dump_format(avFormatCtx, 0, s->path, 0);
132
133  // look for the first audio stream
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 {
141        AUBIO_WRN("source_avcodec: More than one audio stream in %s, "
142            "taking the first one\n", s->path);
143      }
144    }
145  }
146  if (selected_stream == -1) {
147    AUBIO_ERR("source_avcodec: No audio stream in %s\n", s->path);
148    goto beach;
149  }
150  //AUBIO_DBG("Taking stream %d in file %s\n", selected_stream, s->path);
151  s->selected_stream = selected_stream;
152
153  AVCodecContext *avCodecCtx = s->avCodecCtx;
154  avCodecCtx = avFormatCtx->streams[selected_stream]->codec;
155  AVCodec *codec = avcodec_find_decoder(avCodecCtx->codec_id);
156  if (codec == NULL) {
157    AUBIO_ERR("source_avcodec: Could not find decoder for %s", s->path);
158    goto beach;
159  }
160
161  if ( ( err = avcodec_open2(avCodecCtx, codec, NULL) ) < 0) {
162    char errorstr[256];
163    av_strerror (err, errorstr, sizeof(errorstr));
164    AUBIO_ERR("source_avcodec: Could not load codec for %s (%s)\n", s->path, errorstr);
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) {
175    s->samplerate = s->input_samplerate;
176  } else {
177    s->samplerate = samplerate;
178  }
179
180  if (s->samplerate >  s->input_samplerate) {
181    AUBIO_WRN("source_avcodec: upsampling %s from %d to %d\n", s->path,
182        s->input_samplerate, s->samplerate);
183  }
184
185  AVFrame *avFrame = s->avFrame;
186  avFrame = av_frame_alloc();
187  if (!avFrame) {
188    AUBIO_ERR("source_avcodec: Could not allocate frame for (%s)\n", s->path);
189  }
190
191  /* allocate output for avr */
192  s->output = (float *)av_malloc(AUBIO_AVCODEC_MAX_BUFFER_SIZE * sizeof(float));
193
194  s->read_samples = 0;
195  s->read_index = 0;
196
197  s->avFormatCtx = avFormatCtx;
198  s->avCodecCtx = avCodecCtx;
199  s->avFrame = avFrame;
200
201  // default to mono output
202  aubio_source_avcodec_reset_resampler(s, 0);
203
204  s->eof = 0;
205  s->multi = 0;
206
207  //av_log_set_level(AV_LOG_QUIET);
208
209  return s;
210
211beach:
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);
214  del_aubio_source_avcodec(s);
215  return NULL;
216}
217
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));
241      AUBIO_ERR("source_avcodec: Could not open AVAudioResampleContext for %s (%s)\n",
242          s->path, errorstr);
243      //goto beach;
244      return;
245    }
246    s->avr = avr;
247    s->multi = multi;
248  }
249}
250
251void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples) {
252  AVFormatContext *avFormatCtx = s->avFormatCtx;
253  AVCodecContext *avCodecCtx = s->avCodecCtx;
254  AVFrame *avFrame = s->avFrame;
255  AVPacket avPacket;
256  av_init_packet (&avPacket);
257  AVAudioResampleContext *avr = s->avr;
258  float *output = s->output;
259  *read_samples = 0;
260
261  do
262  {
263    int err = av_read_frame (avFormatCtx, &avPacket);
264    if (err == AVERROR_EOF) {
265      s->eof = 1;
266      goto beach;
267    }
268    if (err != 0) {
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;
273    }
274  } while (avPacket.stream_index != s->selected_stream);
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);
281    goto beach;
282  }
283  if (got_frame == 0) {
284    //AUBIO_ERR("Could not get frame for (%s)\n", s->path);
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);
291  int in_samples = avFrame->nb_samples;
292  int out_linesize = 0;
293  int max_out_samples = AUBIO_AVCODEC_MAX_BUFFER_SIZE;
294  int out_samples = avresample_convert ( avr,
295        (uint8_t **)&output, out_linesize, max_out_samples,
296        (uint8_t **)avFrame->data, in_linesize, in_samples);
297  if (out_samples <= 0) {
298    //AUBIO_ERR("No sample found while converting frame (%s)\n", s->path);
299    goto beach;
300  }
301
302  *read_samples = out_samples;
303
304beach:
305  s->avFormatCtx = avFormatCtx;
306  s->avCodecCtx = avCodecCtx;
307  s->avFrame = avFrame;
308  s->avr = avr;
309  s->output = output;
310
311  av_packet_unref(&avPacket);
312}
313
314void aubio_source_avcodec_do(aubio_source_avcodec_t * s, fvec_t * read_data, uint_t * read){
315  if (s->multi == 1) aubio_source_avcodec_reset_resampler(s, 0);
316  uint_t i;
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++) {
322      read_data->data[i + total_wrote] = s->output[i + s->read_index];
323    }
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;
332      }
333    } else {
334      s->read_index += end;
335    }
336  }
337  if (total_wrote < s->hop_size) {
338    for (i = end; i < s->hop_size; i++) {
339      read_data->data[i] = 0.;
340    }
341  }
342  *read = total_wrote;
343}
344
345void aubio_source_avcodec_do_multi(aubio_source_avcodec_t * s, fmat_t * read_data, uint_t * read){
346  if (s->multi == 0) aubio_source_avcodec_reset_resampler(s, 1);
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;
379}
380
381uint_t aubio_source_avcodec_get_samplerate(const aubio_source_avcodec_t * s) {
382  return s->samplerate;
383}
384
385uint_t aubio_source_avcodec_get_channels(const aubio_source_avcodec_t * s) {
386  return s->input_channels;
387}
388
389uint_t aubio_source_avcodec_seek (aubio_source_avcodec_t * s, uint_t pos) {
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;
407}
408
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
417uint_t aubio_source_avcodec_close(aubio_source_avcodec_t * s) {
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;
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) {
442    av_frame_free( &(s->avFrame) );
443  }
444  if (s->path) AUBIO_FREE(s->path);
445  s->avFrame = NULL;
446  AUBIO_FREE(s);
447}
448
449#endif /* HAVE_LIBAV */
Note: See TracBrowser for help on using the repository browser.