source: src/io/source_avcodec.c @ d2be104

feature/autosinkfeature/constantqfeature/pitchshiftfeature/pydocstringsfeature/timestretchpitchshiftsamplertimestretchyinfft+
Last change on this file since d2be104 was d2be104, checked in by Paul Brossier <piem@piem.org>, 4 years ago

src/io/: also copy null ending char

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