src/io/source_avcodec.c: added first draft
[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 MAX_CHANNELS 6
39 #define MAX_SIZE 4096
40 #define MAX_SAMPLES MAX_CHANNELS * MAX_SIZE
41
42 #define SHORT_TO_FLOAT(x) (smpl_t)(x * 3.0517578125e-05)
43
44 struct _aubio_source_avcodec_t {
45   uint_t hop_size;
46   uint_t samplerate;
47   uint_t channels;
48
49   // some data about the file
50   char_t *path;
51   int input_samplerate;
52   int input_channels;
53
54   // avcodec stuff
55   AVFormatContext *avFormatCtx;
56   AVCodecContext *avCodecCtx;
57   AVFrame *avFrame;
58   AVPacket avPacket;
59   AVAudioResampleContext *avr;
60   int16_t *output; 
61   int read_samples;
62   int read_index;
63 };
64
65 aubio_source_avcodec_t * new_aubio_source_avcodec(char_t * path, uint_t samplerate, uint_t hop_size) {
66   aubio_source_avcodec_t * s = AUBIO_NEW(aubio_source_avcodec_t);
67   int err;
68
69   if (path == NULL) {
70     AUBIO_ERR("Aborted opening null path\n");
71     return NULL;
72   }
73
74   s->hop_size = hop_size;
75   s->channels = 1;
76   s->path = path;
77
78   // try opening the file and get some info about it
79   // register all formats and codecs
80   av_register_all();
81
82   // open file
83   AVFormatContext *avFormatCtx = s->avFormatCtx;
84   avFormatCtx = NULL;
85   if ( (err = avformat_open_input(&avFormatCtx, s->path, NULL, NULL) ) < 0 ) {
86     uint8_t errorstr_len = 128;
87     char errorstr[errorstr_len];
88     if (av_strerror (err, errorstr, errorstr_len) == 0) {
89       AUBIO_ERR("Failed opening %s (%s)\n", s->path, errorstr);
90     } else {
91       AUBIO_ERR("Failed opening %s (unknown error)\n", s->path);
92     }
93     goto beach;
94   }
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   uint_t i;
112   sint_t selected_stream = -1;
113   for (i = 0; i < avFormatCtx->nb_streams; i++) {
114     if (avFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
115       if (selected_stream == -1) {
116         selected_stream = i;
117       } else {
118         AUBIO_WRN("More than one audio stream in %s, taking the first one\n", s->path);
119       }
120     }
121   }
122   if (selected_stream == -1) {
123     AUBIO_ERR("No audio stream in %s\n", s->path);
124     goto beach;
125   } 
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
152   //AUBIO_DBG("input_samplerate: %d\n", s->input_samplerate);
153   //AUBIO_DBG("input_channels: %d\n", s->input_channels);
154
155   if (samplerate == 0) {
156     samplerate = s->input_samplerate;
157     //AUBIO_DBG("sampling rate set to 0, automagically adjusting to %d\n", samplerate);
158   }
159   s->samplerate = samplerate;
160
161   int64_t input_layout = av_get_default_channel_layout(s->input_channels);
162   int64_t mono_layout = av_get_default_channel_layout(1);
163
164   AVAudioResampleContext *avr = s->avr;
165   avr = avresample_alloc_context();
166   av_opt_set_int(avr, "in_channel_layout",  input_layout,           0);
167   av_opt_set_int(avr, "out_channel_layout", mono_layout,            0);
168   av_opt_set_int(avr, "in_sample_rate",     s->input_samplerate,    0);
169   av_opt_set_int(avr, "out_sample_rate",    s->samplerate,          0);
170   av_opt_set_int(avr, "in_sample_fmt",      avCodecCtx->sample_fmt, 0);
171   av_opt_set_int(avr, "out_sample_fmt",     AV_SAMPLE_FMT_S16,      0);
172   if ( ( err = avresample_open(avr) ) < 0) {
173     uint8_t errorstr_len = 128;
174     char errorstr[errorstr_len];
175     if (av_strerror (err, errorstr, errorstr_len) == 0) {
176       AUBIO_ERR("Could not open AVAudioResampleContext for %s (%s)\n", s->path, errorstr);
177     } else {
178       AUBIO_ERR("Could not open AVAudioResampleContext for %s (unknown error)\n", s->path);
179     }
180     goto beach;
181   }
182
183   AVFrame *avFrame = s->avFrame;
184   avFrame = avcodec_alloc_frame();
185   if (!avFrame) {
186     AUBIO_ERR("Could not allocate frame for (%s)\n", s->path);
187   }
188   AVPacket avPacket = s->avPacket;
189   av_init_packet(&avPacket);
190
191   s->output = (int16_t *)av_malloc(FF_MIN_BUFFER_SIZE * sizeof(int16_t));
192
193
194   s->read_samples = 0;
195   s->read_index = 0;
196
197   //goto beach;
198
199   /* allocate data for de/interleaving reallocated when needed. */
200   //s->scratch_size = s->input_hop_size * s->input_channels;
201   //s->scratch_data = AUBIO_ARRAY(float,s->scratch_size);
202   s->avFormatCtx = avFormatCtx;
203   s->avCodecCtx = avCodecCtx;
204   s->avFrame = avFrame;
205   s->avPacket = avPacket;
206   s->avr = avr;
207
208   //av_log_set_level(AV_LOG_QUIET);
209
210   return s;
211
212 beach:
213   AUBIO_ERR("can not read %s at samplerate %dHz with a hop_size of %d\n",
214       s->path, s->samplerate, s->hop_size);
215   del_aubio_source_avcodec(s);
216   return NULL;
217 }
218
219 void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, int * read_samples) {
220   AVFormatContext *avFormatCtx = s->avFormatCtx;
221   AVCodecContext *avCodecCtx = s->avCodecCtx;
222   AVFrame *avFrame = s->avFrame;
223   AVPacket avPacket = s->avPacket;
224   AVAudioResampleContext *avr = s->avr;
225   int16_t *output = s->output;
226
227   uint_t i;
228   int err = av_read_frame (avFormatCtx, &avPacket);
229   if (err != 0) {
230     //AUBIO_ERR("Could not read frame for (%s)\n", s->path);
231     *read_samples = 0;
232     return;
233   }
234
235   int got_frame = 0;
236   int len = avcodec_decode_audio4(avCodecCtx, avFrame, &got_frame, &avPacket);
237
238   if (len < 0) {
239     AUBIO_ERR("Error while decoding %s\n", s->path);
240     //goto beach;
241     return;
242   }
243   if (got_frame == 0) {
244     AUBIO_ERR("Could not get frame for (%s)\n", s->path);
245   } else {
246     //int data_size = 
247       av_samples_get_buffer_size(NULL,
248         avCodecCtx->channels, avFrame->nb_samples,
249         avCodecCtx->sample_fmt, 1);
250     //AUBIO_WRN("Got data_size %d frame for (%s)\n", data_size, s->path);
251   }
252
253   int in_samples = avFrame->nb_samples;
254   for (i = 0; i < in_samples; i ++) {
255     //AUBIO_WRN("%d\n", avFrame->data[i]);
256   }
257
258
259 #if 1
260   int in_plane_size = 0; //avFrame->linesize[0];
261   int out_plane_size = 0; //sizeof(float); //in_samples * sizeof(float);
262   int max_out_samples = FF_MIN_BUFFER_SIZE;
263   if (avresample_convert ( avr,
264         (void **)&output, out_plane_size, max_out_samples,
265         (void **)avFrame->data, in_plane_size, in_samples) < 0) {
266       AUBIO_ERR("Could not convert frame  (%s)\n", s->path);
267   }
268   //AUBIO_ERR("Got in_plane_size %d frame for (%s)\n", in_plane_size, s->path);
269   //AUBIO_WRN("Delay is %d for %s\n", avresample_get_delay(avr), s->path);
270   //AUBIO_WRN("max_out_samples is %d for FF_MIN_BUFFER_SIZE %d\n", 
271   //    max_out_samples, FF_MIN_BUFFER_SIZE);
272
273   int out_samples = avresample_available(avr) + (avresample_get_delay(avr)
274         + in_samples) * s->samplerate / s->input_samplerate;
275   //AUBIO_WRN("Converted %d to %d samples\n", in_samples, out_samples);
276   for (i = 0; i < out_samples; i ++) {
277     //AUBIO_DBG("%f\n", SHORT_TO_FLOAT(output[i]));
278   }
279 #else
280   int in_plane_size = 0; //avFrame->linesize[0];
281   int out_plane_size = 0; //sizeof(float); //in_samples * sizeof(float);
282   int max_out_samples = FF_MIN_BUFFER_SIZE;
283   if (avresample_convert ( avr,
284         NULL, out_plane_size, max_out_samples,
285         (uint8_t **)avFrame->data, in_plane_size, in_samples) < 0) {
286       AUBIO_ERR("Could not convert frame  (%s)\n", s->path);
287   }
288   AUBIO_ERR("Got in_plane_size %d frame for (%s)\n", in_plane_size, s->path);
289   AUBIO_WRN("Delay is %d for %s\n", avresample_get_delay(avr), s->path);
290   AUBIO_WRN("max_out_samples is %d for FF_MIN_BUFFER_SIZE %d\n", 
291       max_out_samples, FF_MIN_BUFFER_SIZE);
292
293   //int out_samples = avresample_available (avr) + 
294   //  (avresample_get_delay(avr) + in_samples) * s->samplerate / s->input_samplerate;
295   int out_samples = avresample_available(avr);
296   AUBIO_WRN("Found %d samples available for %s\n", avresample_available(avr), s->path);
297   //
298   err = avresample_read (avr, (uint8_t **)output, out_samples);
299   if (err != 0) {
300     AUBIO_WRN("Error %d while reading %s\n", err, s->path);
301   }
302   AUBIO_WRN("Converted %d to %d samples\n", in_samples, out_samples);
303
304   for (i = 0; i < out_samples; i ++) {
305     AUBIO_WRN("%f\n", SHORT_TO_FLOAT(output[i]));
306   }
307 #endif
308   s->avFormatCtx = avFormatCtx;
309   s->avCodecCtx = avCodecCtx;
310   s->avFrame = avFrame;
311   s->avPacket = avPacket;
312   s->avr = avr;
313   s->output = output;
314
315   *read_samples = out_samples;
316 }
317
318
319 void aubio_source_avcodec_do(aubio_source_avcodec_t * s, fvec_t * read_data, uint_t * read){
320   uint_t i;
321   //AUBIO_DBG("entering 'do' with %d, %d\n", s->read_samples, s->read_index);
322   // begin reading
323   if (s->read_samples == 0) {
324     int avcodec_read = 0;
325     aubio_source_avcodec_readframe(s, &avcodec_read);
326     s->read_samples += avcodec_read;
327     s->read_index = 0;
328   }
329   if (s->read_samples < s->hop_size) {
330     // write the end of the buffer to the beginning of read_data
331     int partial = s->read_samples;
332     for (i = 0; i < partial; i++) {
333       read_data->data[i] = SHORT_TO_FLOAT(s->output[i + s->read_index]);
334     }
335     s->read_samples = 0;
336     s->read_index = 0;
337     // get more data
338     int avcodec_read = 0;
339     aubio_source_avcodec_readframe(s, &avcodec_read);
340     s->read_samples += avcodec_read;
341     s->read_index = 0;
342     // write the beginning of the buffer to the end of read_data
343     int end = MIN((int)(s->hop_size), s->read_samples);
344     if (avcodec_read == 0) { 
345       end = partial;
346     }
347     for (i = partial; i < end; i++) {
348       read_data->data[i] = SHORT_TO_FLOAT(s->output[i - partial + s->read_index]);
349     }
350     if (end < s->hop_size) {
351       for (i = end; i < s->hop_size; i++) {
352         read_data->data[i] = 0.;
353       }
354     }
355     s->read_index += partial;
356     s->read_samples -= partial;
357     *read = end;
358   } else {
359     for (i = 0; i < s->hop_size; i++) {
360       read_data->data[i] = SHORT_TO_FLOAT(s->output[i + s->read_index]);
361     }
362     s->read_index += s->hop_size;
363     s->read_samples -= s->hop_size;
364     *read = s->hop_size;
365   }
366 }
367
368 void aubio_source_avcodec_do_multi(aubio_source_avcodec_t * s, fmat_t * read_data, uint_t * read){
369   //uint_t i,j, input_channels = s->input_channels;
370 }
371
372 uint_t aubio_source_avcodec_get_samplerate(aubio_source_avcodec_t * s) {
373   return s->samplerate;
374 }
375
376 uint_t aubio_source_avcodec_get_channels(aubio_source_avcodec_t * s) {
377   return s->input_channels;
378 }
379
380 uint_t aubio_source_avcodec_seek (aubio_source_avcodec_t * s, uint_t pos) {
381   //uint_t resampled_pos = (uint_t)ROUND(pos * s->input_samplerate * 1. / s->samplerate);
382   return 0; //sf_seek (s->handle, resampled_pos, SEEK_SET);
383 }
384
385 void del_aubio_source_avcodec(aubio_source_avcodec_t * s){
386   if (!s) return;
387   if (s->output != NULL) {
388     av_free(s->output);
389   }
390   if (s->avr != NULL) {
391     avresample_close( s->avr );
392     av_free ( s->avr );
393   }
394   s->avr = NULL;
395   if (s->avFrame != NULL) {
396     avcodec_free_frame( &(s->avFrame) );
397   }
398   s->avFrame = NULL;
399   if ( &(s->avPacket) != NULL) {
400     av_free_packet( &(s->avPacket) );
401   }
402   if (s->avCodecCtx != NULL) {
403     avcodec_close ( s->avCodecCtx );
404   }
405   s->avCodecCtx = NULL;
406   if (s->avFormatCtx != NULL) {
407     avformat_close_input ( &(s->avFormatCtx) );
408   }
409   s->avFrame = NULL;
410   s->avFormatCtx = NULL;
411   AUBIO_FREE(s);
412 }
413
414 #endif /* HAVE_SNDFILE */