src/io/source_avcodec.c: simplify, improve comments
[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_AVCODEC
25
26 #include <sndfile.h>
27 #include <libavcodec/avcodec.h>
28 #include <libavformat/avformat.h>
29 #include <libavresample/avresample.h>
30 #include <libavutil/opt.h>
31 #include <stdlib.h>
32
33 #include "aubio_priv.h"
34 #include "fvec.h"
35 #include "fmat.h"
36 #include "source_avcodec.h"
37
38 #define AUBIO_AVCODEC_MIN_BUFFER_SIZE FF_MIN_BUFFER_SIZE
39
40 #define SHORT_TO_FLOAT(x) (smpl_t)(x * 3.0517578125e-05)
41
42 struct _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   AVPacket avPacket;
57   AVAudioResampleContext *avr;
58   int16_t *output;
59   uint_t read_samples;
60   uint_t read_index;
61 };
62
63 aubio_source_avcodec_t * new_aubio_source_avcodec(char_t * path, uint_t samplerate, uint_t hop_size) {
64   aubio_source_avcodec_t * s = AUBIO_NEW(aubio_source_avcodec_t);
65   int err;
66
67   if (path == NULL) {
68     AUBIO_ERR("Aborted opening null path\n");
69     return NULL;
70   }
71
72   s->hop_size = hop_size;
73   s->channels = 1;
74   s->path = path;
75
76   // register all formats and codecs
77   av_register_all();
78
79   // try opening the file and get some info about it
80   AVFormatContext *avFormatCtx = s->avFormatCtx;
81   avFormatCtx = NULL;
82   if ( (err = avformat_open_input(&avFormatCtx, s->path, NULL, NULL) ) < 0 ) {
83     uint8_t errorstr_len = 128;
84     char errorstr[errorstr_len];
85     if (av_strerror (err, errorstr, errorstr_len) == 0) {
86       AUBIO_ERR("Failed opening %s (%s)\n", s->path, errorstr);
87     } else {
88       AUBIO_ERR("Failed opening %s (unknown error)\n", s->path);
89     }
90     goto beach;
91   }
92
93   // try to make sure max_analyze_duration is big enough for most songs
94   avFormatCtx->max_analyze_duration *= 100;
95
96   // retrieve stream information
97   if ( (err = avformat_find_stream_info(avFormatCtx, NULL)) < 0 ) {
98     uint8_t errorstr_len = 128;
99     char errorstr[errorstr_len];
100     if (av_strerror (err, errorstr, errorstr_len) == 0) {
101       AUBIO_ERR("Could not find stream information for %s (%s)\n", s->path, errorstr);
102     } else {
103       AUBIO_ERR("Could not find stream information for %s (unknown error)\n", s->path);
104     }
105     goto beach;
106   }
107
108   // Dump information about file onto standard error
109   //av_dump_format(avFormatCtx, 0, s->path, 0);
110
111   // look for the first audio stream, printing a warning if more than one is found
112   uint_t i;
113   sint_t selected_stream = -1;
114   for (i = 0; i < avFormatCtx->nb_streams; i++) {
115     if (avFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
116       if (selected_stream == -1) {
117         selected_stream = i;
118       } else {
119         AUBIO_WRN("More than one audio stream in %s, taking the first one\n", s->path);
120       }
121     }
122   }
123   if (selected_stream == -1) {
124     AUBIO_ERR("No audio stream in %s\n", s->path);
125     goto beach;
126   }
127   //AUBIO_DBG("Taking stream %d in file %s\n", selected_stream, s->path);
128
129   AVCodecContext *avCodecCtx = s->avCodecCtx;
130   avCodecCtx = avFormatCtx->streams[selected_stream]->codec;
131   AVCodec *codec = avcodec_find_decoder(avCodecCtx->codec_id);
132   if (codec == NULL) {
133     AUBIO_ERR("Could not find decoder for %s", s->path);
134     goto beach;
135   }
136
137   if ( ( err = avcodec_open2(avCodecCtx, codec, NULL) ) < 0) {
138     uint8_t errorstr_len = 128;
139     char errorstr[errorstr_len];
140     if (av_strerror (err, errorstr, errorstr_len) == 0) {
141       AUBIO_ERR("Could not load codec for %s (%s)\n", s->path, errorstr);
142     } else {
143       AUBIO_ERR("Could not load codec for %s (unknown error)\n", s->path);
144     }
145     goto beach;
146   }
147
148   /* get input specs */
149   s->input_samplerate = avCodecCtx->sample_rate;
150   s->input_channels   = avCodecCtx->channels;
151   //AUBIO_DBG("input_samplerate: %d\n", s->input_samplerate);
152   //AUBIO_DBG("input_channels: %d\n", s->input_channels);
153
154   if (samplerate == 0) {
155     samplerate = s->input_samplerate;
156     //AUBIO_DBG("sampling rate set to 0, automagically adjusting to %d\n", samplerate);
157   }
158   s->samplerate = samplerate;
159
160   int64_t input_layout = av_get_default_channel_layout(s->input_channels);
161   int64_t mono_layout = av_get_default_channel_layout(1);
162
163   AVAudioResampleContext *avr = s->avr;
164   avr = avresample_alloc_context();
165   av_opt_set_int(avr, "in_channel_layout",  input_layout,           0);
166   av_opt_set_int(avr, "out_channel_layout", mono_layout,            0);
167   av_opt_set_int(avr, "in_sample_rate",     s->input_samplerate,    0);
168   av_opt_set_int(avr, "out_sample_rate",    s->samplerate,          0);
169   av_opt_set_int(avr, "in_sample_fmt",      avCodecCtx->sample_fmt, 0);
170   av_opt_set_int(avr, "out_sample_fmt",     AV_SAMPLE_FMT_S16,      0);
171   if ( ( err = avresample_open(avr) ) < 0) {
172     uint8_t errorstr_len = 128;
173     char errorstr[errorstr_len];
174     if (av_strerror (err, errorstr, errorstr_len) == 0) {
175       AUBIO_ERR("Could not open AVAudioResampleContext for %s (%s)\n", s->path, errorstr);
176     } else {
177       AUBIO_ERR("Could not open AVAudioResampleContext for %s (unknown error)\n", s->path);
178     }
179     goto beach;
180   }
181
182   AVFrame *avFrame = s->avFrame;
183   avFrame = avcodec_alloc_frame();
184   if (!avFrame) {
185     AUBIO_ERR("Could not allocate frame for (%s)\n", s->path);
186   }
187   AVPacket avPacket = s->avPacket;
188   av_init_packet(&avPacket);
189
190   /* allocate output for avr */
191   s->output = (int16_t *)av_malloc(AUBIO_AVCODEC_MIN_BUFFER_SIZE * sizeof(int16_t));
192
193   s->read_samples = 0;
194   s->read_index = 0;
195
196   s->avFormatCtx = avFormatCtx;
197   s->avCodecCtx = avCodecCtx;
198   s->avFrame = avFrame;
199   s->avPacket = avPacket;
200   s->avr = avr;
201
202   //av_log_set_level(AV_LOG_QUIET);
203
204   return s;
205
206 beach:
207   AUBIO_ERR("can not read %s at samplerate %dHz with a hop_size of %d\n",
208       s->path, s->samplerate, s->hop_size);
209   del_aubio_source_avcodec(s);
210   return NULL;
211 }
212
213 void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples) {
214   AVFormatContext *avFormatCtx = s->avFormatCtx;
215   AVCodecContext *avCodecCtx = s->avCodecCtx;
216   AVFrame *avFrame = s->avFrame;
217   AVPacket avPacket = s->avPacket;
218   AVAudioResampleContext *avr = s->avr;
219   int16_t *output = s->output;
220
221   int err = av_read_frame (avFormatCtx, &avPacket);
222   if (err != 0) {
223     //AUBIO_ERR("Could not read frame for (%s)\n", s->path);
224     *read_samples = 0;
225     return;
226   }
227
228   int got_frame = 0;
229   int len = avcodec_decode_audio4(avCodecCtx, avFrame, &got_frame, &avPacket);
230
231   if (len < 0) {
232     AUBIO_ERR("Error while decoding %s\n", s->path);
233     return;
234   }
235   if (got_frame == 0) {
236     AUBIO_ERR("Could not get frame for (%s)\n", s->path);
237   } /* else {
238     int data_size =
239       av_samples_get_buffer_size(NULL,
240         avCodecCtx->channels, avFrame->nb_samples,
241         avCodecCtx->sample_fmt, 1);
242     AUBIO_WRN("Got data_size %d frame for (%s)\n", data_size, s->path);
243   } */
244
245   int in_samples = avFrame->nb_samples;
246   int in_plane_size = 0; //avFrame->linesize[0];
247   int out_plane_size = 0; //sizeof(float); //in_samples * sizeof(float);
248   int max_out_samples = AUBIO_AVCODEC_MIN_BUFFER_SIZE;
249   if (avresample_convert ( avr,
250         (uint8_t **)&output, out_plane_size, max_out_samples,
251         (uint8_t **)avFrame->data, in_plane_size, in_samples) < 0) {
252       AUBIO_ERR("Could not convert frame  (%s)\n", s->path);
253   }
254   //AUBIO_ERR("Got in_plane_size %d frame for (%s)\n", in_plane_size, s->path);
255   //AUBIO_WRN("Delay is %d for %s\n", avresample_get_delay(avr), s->path);
256   //AUBIO_WRN("max_out_samples is %d for AUBIO_AVCODEC_MIN_BUFFER_SIZE %d\n",
257   //    max_out_samples, AUBIO_AVCODEC_MIN_BUFFER_SIZE);
258
259   uint_t out_samples = avresample_available(avr) + (avresample_get_delay(avr)
260         + in_samples) * s->samplerate / s->input_samplerate;
261   //AUBIO_WRN("Converted %d to %d samples\n", in_samples, out_samples);
262   //for (i = 0; i < out_samples; i ++) {
263   //  AUBIO_DBG("%f\n", SHORT_TO_FLOAT(output[i]));
264   //}
265   s->avFormatCtx = avFormatCtx;
266   s->avCodecCtx = avCodecCtx;
267   s->avFrame = avFrame;
268   s->avPacket = avPacket;
269   s->avr = avr;
270   s->output = output;
271
272   *read_samples = out_samples;
273 }
274
275
276 void aubio_source_avcodec_do(aubio_source_avcodec_t * s, fvec_t * read_data, uint_t * read){
277   uint_t i;
278   //AUBIO_DBG("entering 'do' with %d, %d\n", s->read_samples, s->read_index);
279   if (s->read_samples < s->hop_size) {
280     // write the end of the buffer to the beginning of read_data
281     uint_t partial = s->read_samples;
282     for (i = 0; i < partial; i++) {
283       read_data->data[i] = SHORT_TO_FLOAT(s->output[i + s->read_index]);
284     }
285     // get more data
286     uint_t avcodec_read = 0;
287     aubio_source_avcodec_readframe(s, &avcodec_read);
288     s->read_samples = avcodec_read;
289     s->read_index = 0;
290     // write the beginning of the buffer to the end of read_data
291     uint_t end = MIN(s->hop_size, s->read_samples);
292     if (avcodec_read == 0) {
293       end = partial;
294     }
295     for (i = partial; i < end; i++) {
296       read_data->data[i] = SHORT_TO_FLOAT(s->output[i - partial + s->read_index]);
297     }
298     if (end < s->hop_size) {
299       for (i = end; i < s->hop_size; i++) {
300         read_data->data[i] = 0.;
301       }
302     }
303     s->read_index += end - partial;
304     s->read_samples -= end - partial;
305     *read = end;
306   } else {
307     for (i = 0; i < s->hop_size; i++) {
308       read_data->data[i] = SHORT_TO_FLOAT(s->output[i + s->read_index]);
309     }
310     s->read_index += s->hop_size;
311     s->read_samples -= s->hop_size;
312     *read = s->hop_size;
313   }
314 }
315
316 void aubio_source_avcodec_do_multi(aubio_source_avcodec_t * s, fmat_t * read_data, uint_t * read){
317   //uint_t i,j, input_channels = s->input_channels;
318 }
319
320 uint_t aubio_source_avcodec_get_samplerate(aubio_source_avcodec_t * s) {
321   return s->samplerate;
322 }
323
324 uint_t aubio_source_avcodec_get_channels(aubio_source_avcodec_t * s) {
325   return s->input_channels;
326 }
327
328 uint_t aubio_source_avcodec_seek (aubio_source_avcodec_t * s, uint_t pos) {
329   //uint_t resampled_pos = (uint_t)ROUND(pos * s->input_samplerate * 1. / s->samplerate);
330   return 0; //sf_seek (s->handle, resampled_pos, SEEK_SET);
331 }
332
333 void del_aubio_source_avcodec(aubio_source_avcodec_t * s){
334   if (!s) return;
335   if (s->output != NULL) {
336     av_free(s->output);
337   }
338   if (s->avr != NULL) {
339     avresample_close( s->avr );
340     av_free ( s->avr );
341   }
342   s->avr = NULL;
343   if (s->avFrame != NULL) {
344     avcodec_free_frame( &(s->avFrame) );
345   }
346   s->avFrame = NULL;
347   if ( &(s->avPacket) != NULL) {
348     av_free_packet( &(s->avPacket) );
349   }
350   if (s->avCodecCtx != NULL) {
351     avcodec_close ( s->avCodecCtx );
352   }
353   s->avCodecCtx = NULL;
354   if (s->avFormatCtx != NULL) {
355     avformat_close_input ( &(s->avFormatCtx) );
356   }
357   s->avFrame = NULL;
358   s->avFormatCtx = NULL;
359   AUBIO_FREE(s);
360 }
361
362 #endif /* HAVE_SNDFILE */