source: src/io/source_avcodec.c @ a0a073f

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5sampleryinfft+
Last change on this file since a0a073f was 261836d, checked in by Paul Brossier <piem@piem.org>, 8 years ago

src/io/source_avcodec.c: keep a reference to packet to remove it when closing file

  • Property mode set to 100644
File size: 16.1 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  AVPacket avPacket;
63  AVAudioResampleContext *avr;
64  smpl_t *output;
65  uint_t read_samples;
66  uint_t read_index;
67  sint_t selected_stream;
68  uint_t eof;
69  uint_t multi;
70};
71
72// hack to create or re-create the context the first time _do or _do_multi is called
73void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s, uint_t multi);
74void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples);
75
76uint_t aubio_source_avcodec_has_network_url(aubio_source_avcodec_t *s);
77
78uint_t aubio_source_avcodec_has_network_url(aubio_source_avcodec_t *s) {
79  char proto[20], authorization[256], hostname[128], uripath[256];
80  int proto_size = 20, authorization_size = 256, hostname_size = 128,
81      *port_ptr = 0, path_size = 256;
82  av_url_split(proto, proto_size, authorization, authorization_size, hostname,
83      hostname_size, port_ptr, uripath, path_size, s->path);
84  if (strlen(proto)) {
85    return 1;
86  }
87  return 0;
88}
89
90
91aubio_source_avcodec_t * new_aubio_source_avcodec(const char_t * path, uint_t samplerate, uint_t hop_size) {
92  aubio_source_avcodec_t * s = AUBIO_NEW(aubio_source_avcodec_t);
93  int err;
94  if (path == NULL) {
95    AUBIO_ERR("source_avcodec: Aborted opening null path\n");
96    goto beach;
97  }
98  if ((sint_t)samplerate < 0) {
99    AUBIO_ERR("source_avcodec: Can not open %s with samplerate %d\n", path, samplerate);
100    goto beach;
101  }
102  if ((sint_t)hop_size <= 0) {
103    AUBIO_ERR("source_avcodec: Can not open %s with hop_size %d\n", path, hop_size);
104    goto beach;
105  }
106
107  s->hop_size = hop_size;
108  s->channels = 1;
109
110  if (s->path) AUBIO_FREE(s->path);
111  s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
112  strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
113
114  // register all formats and codecs
115  av_register_all();
116
117  if (aubio_source_avcodec_has_network_url(s)) {
118    avformat_network_init();
119  }
120
121  // try opening the file and get some info about it
122  AVFormatContext *avFormatCtx = s->avFormatCtx;
123  avFormatCtx = NULL;
124  if ( (err = avformat_open_input(&avFormatCtx, s->path, NULL, NULL) ) < 0 ) {
125    char errorstr[256];
126    av_strerror (err, errorstr, sizeof(errorstr));
127    AUBIO_ERR("source_avcodec: Failed opening %s (%s)\n", s->path, errorstr);
128    goto beach;
129  }
130
131  // try to make sure max_analyze_duration is big enough for most songs
132#if FFMPEG_LIBAVFORMAT_MAX_DUR2
133  avFormatCtx->max_analyze_duration2 *= 100;
134#else
135  avFormatCtx->max_analyze_duration *= 100;
136#endif
137
138  // retrieve stream information
139  if ( (err = avformat_find_stream_info(avFormatCtx, NULL)) < 0 ) {
140    char errorstr[256];
141    av_strerror (err, errorstr, sizeof(errorstr));
142    AUBIO_ERR("source_avcodec: Could not find stream information " "for %s (%s)\n", s->path,
143        errorstr);
144    goto beach;
145  }
146
147  // dump information about file onto standard error
148  //av_dump_format(avFormatCtx, 0, s->path, 0);
149
150  // look for the first audio stream
151  uint_t i;
152  sint_t selected_stream = -1;
153  for (i = 0; i < avFormatCtx->nb_streams; i++) {
154#if FF_API_LAVF_AVCTX
155    if (avFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
156#else
157    if (avFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
158#endif
159      if (selected_stream == -1) {
160        selected_stream = i;
161      } else {
162        AUBIO_WRN("source_avcodec: More than one audio stream in %s, "
163            "taking the first one\n", s->path);
164      }
165    }
166  }
167  if (selected_stream == -1) {
168    AUBIO_ERR("source_avcodec: No audio stream in %s\n", s->path);
169    goto beach;
170  }
171  //AUBIO_DBG("Taking stream %d in file %s\n", selected_stream, s->path);
172  s->selected_stream = selected_stream;
173
174  AVCodecContext *avCodecCtx = s->avCodecCtx;
175#if FF_API_LAVF_AVCTX
176  AVCodecParameters *codecpar = avFormatCtx->streams[selected_stream]->codecpar;
177  if (codecpar == NULL) {
178    AUBIO_ERR("source_avcodec: Could not find decoder for %s", s->path);
179    goto beach;
180  }
181  AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
182
183  /* Allocate a codec context for the decoder */
184  avCodecCtx = avcodec_alloc_context3(codec);
185  if (!avCodecCtx) {
186    AUBIO_ERR("source_avcodec: Failed to allocate the %s codec context for path %s\n",
187        av_get_media_type_string(AVMEDIA_TYPE_AUDIO), s->path);
188    goto beach;
189  }
190#else
191  avCodecCtx = avFormatCtx->streams[selected_stream]->codec;
192  AVCodec *codec = avcodec_find_decoder(avCodecCtx->codec_id);
193#endif
194  if (codec == NULL) {
195    AUBIO_ERR("source_avcodec: Could not find decoder for %s", s->path);
196    goto beach;
197  }
198
199#if FF_API_LAVF_AVCTX
200  /* Copy codec parameters from input stream to output codec context */
201  if ((err = avcodec_parameters_to_context(avCodecCtx, codecpar)) < 0) {
202    AUBIO_ERR("source_avcodec: Failed to copy %s codec parameters to decoder context for %s\n",
203       av_get_media_type_string(AVMEDIA_TYPE_AUDIO), s->path);
204    goto beach;
205  }
206#endif
207
208  if ( ( err = avcodec_open2(avCodecCtx, codec, NULL) ) < 0) {
209    char errorstr[256];
210    av_strerror (err, errorstr, sizeof(errorstr));
211    AUBIO_ERR("source_avcodec: Could not load codec for %s (%s)\n", s->path, errorstr);
212    goto beach;
213  }
214
215  /* get input specs */
216  s->input_samplerate = avCodecCtx->sample_rate;
217  s->input_channels   = avCodecCtx->channels;
218  //AUBIO_DBG("input_samplerate: %d\n", s->input_samplerate);
219  //AUBIO_DBG("input_channels: %d\n", s->input_channels);
220
221  if (samplerate == 0) {
222    s->samplerate = s->input_samplerate;
223  } else {
224    s->samplerate = samplerate;
225  }
226
227  if (s->samplerate >  s->input_samplerate) {
228    AUBIO_WRN("source_avcodec: upsampling %s from %d to %d\n", s->path,
229        s->input_samplerate, s->samplerate);
230  }
231
232  AVFrame *avFrame = s->avFrame;
233  avFrame = av_frame_alloc();
234  if (!avFrame) {
235    AUBIO_ERR("source_avcodec: Could not allocate frame for (%s)\n", s->path);
236  }
237
238  /* allocate output for avr */
239  s->output = (smpl_t *)av_malloc(AUBIO_AVCODEC_MAX_BUFFER_SIZE * sizeof(smpl_t));
240
241  s->read_samples = 0;
242  s->read_index = 0;
243
244  s->avFormatCtx = avFormatCtx;
245  s->avCodecCtx = avCodecCtx;
246  s->avFrame = avFrame;
247
248  // default to mono output
249  aubio_source_avcodec_reset_resampler(s, 0);
250
251  s->eof = 0;
252  s->multi = 0;
253
254  //av_log_set_level(AV_LOG_QUIET);
255
256  return s;
257
258beach:
259  //AUBIO_ERR("can not read %s at samplerate %dHz with a hop_size of %d\n",
260  //    s->path, s->samplerate, s->hop_size);
261  del_aubio_source_avcodec(s);
262  return NULL;
263}
264
265void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s, uint_t multi) {
266  // create or reset resampler to/from mono/multi-channel
267  if ( (multi != s->multi) || (s->avr == NULL) ) {
268    int64_t input_layout = av_get_default_channel_layout(s->input_channels);
269    uint_t output_channels = multi ? s->input_channels : 1;
270    int64_t output_layout = av_get_default_channel_layout(output_channels);
271    AVAudioResampleContext *avr = avresample_alloc_context();
272    AVAudioResampleContext *oldavr = s->avr;
273
274    av_opt_set_int(avr, "in_channel_layout",  input_layout,           0);
275    av_opt_set_int(avr, "out_channel_layout", output_layout,          0);
276    av_opt_set_int(avr, "in_sample_rate",     s->input_samplerate,    0);
277    av_opt_set_int(avr, "out_sample_rate",    s->samplerate,          0);
278    av_opt_set_int(avr, "in_sample_fmt",      s->avCodecCtx->sample_fmt, 0);
279#if HAVE_AUBIO_DOUBLE
280    av_opt_set_int(avr, "out_sample_fmt",     AV_SAMPLE_FMT_DBL,      0);
281#else
282    av_opt_set_int(avr, "out_sample_fmt",     AV_SAMPLE_FMT_FLT,      0);
283#endif
284    // TODO: use planar?
285    //av_opt_set_int(avr, "out_sample_fmt",     AV_SAMPLE_FMT_FLTP,      0);
286    int err;
287    if ( ( err = avresample_open(avr) ) < 0) {
288      char errorstr[256];
289      av_strerror (err, errorstr, sizeof(errorstr));
290      AUBIO_ERR("source_avcodec: Could not open AVAudioResampleContext for %s (%s)\n",
291          s->path, errorstr);
292      //goto beach;
293      return;
294    }
295    s->avr = avr;
296    if (oldavr != NULL) {
297      avresample_close( oldavr );
298      av_free ( oldavr );
299      oldavr = NULL;
300    }
301    s->multi = multi;
302  }
303}
304
305void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples) {
306  AVFormatContext *avFormatCtx = s->avFormatCtx;
307  AVCodecContext *avCodecCtx = s->avCodecCtx;
308  AVFrame *avFrame = s->avFrame;
309  AVPacket avPacket = s->avPacket;
310  av_init_packet (&avPacket);
311  AVAudioResampleContext *avr = s->avr;
312  smpl_t *output = s->output;
313  *read_samples = 0;
314
315  do
316  {
317    int err = av_read_frame (avFormatCtx, &avPacket);
318    if (err == AVERROR_EOF) {
319      s->eof = 1;
320      goto beach;
321    }
322    if (err != 0) {
323      char errorstr[256];
324      av_strerror (err, errorstr, sizeof(errorstr));
325      AUBIO_ERR("source_avcodec: could not read frame in %s (%s)\n", s->path, errorstr);
326      goto beach;
327    }
328  } while (avPacket.stream_index != s->selected_stream);
329
330  int got_frame = 0;
331#if FF_API_LAVF_AVCTX
332  int ret = avcodec_send_packet(avCodecCtx, &avPacket);
333  if (ret < 0 && ret != AVERROR_EOF) {
334    AUBIO_ERR("source_avcodec: error when sending packet for %s\n", s->path);
335    goto beach;
336  }
337  ret = avcodec_receive_frame(avCodecCtx, avFrame);
338  if (ret >= 0) {
339    got_frame = 1;
340  }
341  if (ret < 0) {
342    if (ret == AVERROR(EAGAIN)) {
343      AUBIO_WRN("source_avcodec: output is not available right now - user must try to send new input\n");
344    } else if (ret == AVERROR_EOF) {
345      AUBIO_WRN("source_avcodec: the decoder has been fully flushed, and there will be no more output frames\n");
346    } else {
347      AUBIO_ERR("source_avcodec: decoding errors on %s\n", s->path);
348      goto beach;
349    }
350  }
351#else
352  int len = avcodec_decode_audio4(avCodecCtx, avFrame, &got_frame, &avPacket);
353
354  if (len < 0) {
355    AUBIO_ERR("source_avcodec: error while decoding %s\n", s->path);
356    goto beach;
357  }
358#endif
359  if (got_frame == 0) {
360    AUBIO_WRN("source_avcodec: did not get a frame when reading %s\n", s->path);
361    goto beach;
362  }
363
364  int in_linesize = 0;
365  av_samples_get_buffer_size(&in_linesize, avCodecCtx->channels,
366      avFrame->nb_samples, avCodecCtx->sample_fmt, 1);
367  int in_samples = avFrame->nb_samples;
368  int out_linesize = 0;
369  int max_out_samples = AUBIO_AVCODEC_MAX_BUFFER_SIZE;
370  int out_samples = avresample_convert ( avr,
371        (uint8_t **)&output, out_linesize, max_out_samples,
372        (uint8_t **)avFrame->data, in_linesize, in_samples);
373  if (out_samples <= 0) {
374    AUBIO_WRN("source_avcodec: no sample found while converting frame (%s)\n", s->path);
375    goto beach;
376  }
377
378  *read_samples = out_samples;
379
380beach:
381  s->avFormatCtx = avFormatCtx;
382  s->avCodecCtx = avCodecCtx;
383  s->avFrame = avFrame;
384  s->avr = avr;
385  s->output = output;
386
387  av_packet_unref(&avPacket);
388}
389
390void aubio_source_avcodec_do(aubio_source_avcodec_t * s, fvec_t * read_data, uint_t * read){
391  uint_t i;
392  uint_t end = 0;
393  uint_t total_wrote = 0;
394  // switch from multi
395  if (s->multi == 1) aubio_source_avcodec_reset_resampler(s, 0);
396  while (total_wrote < s->hop_size) {
397    end = MIN(s->read_samples - s->read_index, s->hop_size - total_wrote);
398    for (i = 0; i < end; i++) {
399      read_data->data[i + total_wrote] = s->output[i + s->read_index];
400    }
401    total_wrote += end;
402    if (total_wrote < s->hop_size) {
403      uint_t avcodec_read = 0;
404      aubio_source_avcodec_readframe(s, &avcodec_read);
405      s->read_samples = avcodec_read;
406      s->read_index = 0;
407      if (s->eof) {
408        break;
409      }
410    } else {
411      s->read_index += end;
412    }
413  }
414  if (total_wrote < s->hop_size) {
415    for (i = total_wrote; i < s->hop_size; i++) {
416      read_data->data[i] = 0.;
417    }
418  }
419  *read = total_wrote;
420}
421
422void aubio_source_avcodec_do_multi(aubio_source_avcodec_t * s, fmat_t * read_data, uint_t * read){
423  uint_t i,j;
424  uint_t end = 0;
425  uint_t total_wrote = 0;
426  // switch from mono
427  if (s->multi == 0) aubio_source_avcodec_reset_resampler(s, 1);
428  while (total_wrote < s->hop_size) {
429    end = MIN(s->read_samples - s->read_index, s->hop_size - total_wrote);
430    for (j = 0; j < read_data->height; j++) {
431      for (i = 0; i < end; i++) {
432        read_data->data[j][i + total_wrote] =
433          s->output[(i + s->read_index) * s->input_channels + j];
434      }
435    }
436    total_wrote += end;
437    if (total_wrote < s->hop_size) {
438      uint_t avcodec_read = 0;
439      aubio_source_avcodec_readframe(s, &avcodec_read);
440      s->read_samples = avcodec_read;
441      s->read_index = 0;
442      if (s->eof) {
443        break;
444      }
445    } else {
446      s->read_index += end;
447    }
448  }
449  if (total_wrote < s->hop_size) {
450    for (j = 0; j < read_data->height; j++) {
451      for (i = total_wrote; i < s->hop_size; i++) {
452        read_data->data[j][i] = 0.;
453      }
454    }
455  }
456  *read = total_wrote;
457}
458
459uint_t aubio_source_avcodec_get_samplerate(const aubio_source_avcodec_t * s) {
460  return s->samplerate;
461}
462
463uint_t aubio_source_avcodec_get_channels(const aubio_source_avcodec_t * s) {
464  return s->input_channels;
465}
466
467uint_t aubio_source_avcodec_seek (aubio_source_avcodec_t * s, uint_t pos) {
468  int64_t resampled_pos = (uint_t)ROUND(pos * (s->input_samplerate * 1. / s->samplerate));
469  int64_t min_ts = MAX(resampled_pos - 2000, 0);
470  int64_t max_ts = MIN(resampled_pos + 2000, INT64_MAX);
471  int seek_flags = AVSEEK_FLAG_FRAME | AVSEEK_FLAG_ANY;
472  int ret = avformat_seek_file(s->avFormatCtx, s->selected_stream,
473      min_ts, resampled_pos, max_ts, seek_flags);
474  if (ret < 0) {
475    AUBIO_ERR("Failed seeking to %d in file %s", pos, s->path);
476  }
477  // reset read status
478  s->eof = 0;
479  s->read_index = 0;
480  s->read_samples = 0;
481  // reset the AVAudioResampleContext
482  avresample_close(s->avr);
483  avresample_open(s->avr);
484  return ret;
485}
486
487uint_t aubio_source_avcodec_get_duration (aubio_source_avcodec_t * s) {
488  if (s && &(s->avFormatCtx) != NULL) {
489    int64_t duration = s->avFormatCtx->duration;
490    return s->samplerate * ((uint_t)duration / 1e6 );
491  }
492  return 0;
493}
494
495uint_t aubio_source_avcodec_close(aubio_source_avcodec_t * s) {
496  if (s->avr != NULL) {
497    avresample_close( s->avr );
498    av_free ( s->avr );
499  }
500  s->avr = NULL;
501  if (s->avCodecCtx != NULL) {
502    avcodec_close ( s->avCodecCtx );
503  }
504  s->avCodecCtx = NULL;
505  if (s->avFormatCtx != NULL) {
506    avformat_close_input(&s->avFormatCtx);
507    avformat_free_context(s->avFormatCtx);
508    s->avFormatCtx = NULL;
509  }
510#if FF_API_LAVF_AVCTX
511  av_packet_unref(&s->avPacket);
512#else
513  av_free_packet(&s->avPacket);
514#endif
515  return AUBIO_OK;
516}
517
518void del_aubio_source_avcodec(aubio_source_avcodec_t * s){
519  if (!s) return;
520  aubio_source_avcodec_close(s);
521  if (s->output != NULL) {
522    av_free(s->output);
523  }
524  s->output = NULL;
525  if (s->avFrame != NULL) {
526    av_frame_free( &(s->avFrame) );
527  }
528  if (s->path) AUBIO_FREE(s->path);
529  s->avFrame = NULL;
530  AUBIO_FREE(s);
531}
532
533#endif /* HAVE_LIBAV */
Note: See TracBrowser for help on using the repository browser.