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