source: src/io/source_avcodec.c @ 618ebd5

sampler
Last change on this file since 618ebd5 was 618ebd5, checked in by Paul Brossier <piem@piem.org>, 7 years ago

src/io/source_avcodec.c: make thread safe using a global lock

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