Merge with trunk r37677
[blender.git] / intern / audaspace / ffmpeg / AUD_FFMPEGReader.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * Copyright 2009-2011 Jörg Hermann Müller
7  *
8  * This file is part of AudaSpace.
9  *
10  * Audaspace is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * AudaSpace is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Audaspace; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file audaspace/ffmpeg/AUD_FFMPEGReader.cpp
28  *  \ingroup audffmpeg
29  */
30
31
32 // needed for INT64_C
33 #ifndef __STDC_CONSTANT_MACROS
34 #define __STDC_CONSTANT_MACROS
35 #endif
36
37 #include "AUD_FFMPEGReader.h"
38
39 extern "C" {
40 #include <libavcodec/avcodec.h>
41 #include <libavformat/avformat.h>
42 #include "ffmpeg_compat.h"
43 }
44
45 int AUD_FFMPEGReader::decode(AVPacket* packet, AUD_Buffer& buffer)
46 {
47         // save packet parameters
48         uint8_t *audio_pkg_data = packet->data;
49         int audio_pkg_size = packet->size;
50
51         int buf_size = buffer.getSize();
52         int buf_pos = 0;
53
54         int read_length, data_size;
55
56         AVPacket tmp_pkt;
57         
58         av_init_packet(&tmp_pkt);
59
60         // as long as there is still data in the package
61         while(audio_pkg_size > 0)
62         {
63                 // resize buffer if needed
64                 if(buf_size - buf_pos < AVCODEC_MAX_AUDIO_FRAME_SIZE)
65                 {
66                         buffer.resize(buf_size + AVCODEC_MAX_AUDIO_FRAME_SIZE, true);
67                         buf_size += AVCODEC_MAX_AUDIO_FRAME_SIZE;
68                 }
69
70                 // read samples from the packet
71                 data_size = buf_size - buf_pos;
72
73                 tmp_pkt.data = audio_pkg_data;
74                 tmp_pkt.size = audio_pkg_size;
75
76                 read_length = avcodec_decode_audio3(
77                         m_codecCtx,
78                         (int16_t*)(((data_t*)buffer.getBuffer()) + buf_pos),
79                         &data_size, &tmp_pkt);
80
81                 // read error, next packet!
82                 if(read_length < 0)
83                         break;
84
85                 buf_pos += data_size;
86
87                 // move packet parameters
88                 audio_pkg_data += read_length;
89                 audio_pkg_size -= read_length;
90         }
91
92         return buf_pos;
93 }
94
95 static const char* streaminfo_error = "AUD_FFMPEGReader: Stream info couldn't "
96                                                                           "be found.";
97 static const char* noaudio_error = "AUD_FFMPEGReader: File doesn't include an "
98                                                                    "audio stream.";
99 static const char* nodecoder_error = "AUD_FFMPEGReader: No decoder found for "
100                                                                          "the audio stream.";
101 static const char* codecopen_error = "AUD_FFMPEGReader: Codec couldn't be "
102                                                                          "opened.";
103 static const char* format_error = "AUD_FFMPEGReader: Unsupported sample "
104                                                                   "format.";
105
106 void AUD_FFMPEGReader::init()
107 {
108         m_position = 0;
109         m_pkgbuf_left = 0;
110
111         if(av_find_stream_info(m_formatCtx)<0)
112                 AUD_THROW(AUD_ERROR_FFMPEG, streaminfo_error);
113
114         // find audio stream and codec
115         m_stream = -1;
116
117         for(unsigned int i = 0; i < m_formatCtx->nb_streams; i++)
118         {
119                 if((m_formatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
120                         && (m_stream < 0))
121                 {
122                         m_stream=i;
123                         break;
124                 }
125         }
126
127         if(m_stream == -1)
128                 AUD_THROW(AUD_ERROR_FFMPEG, noaudio_error);
129
130         m_codecCtx = m_formatCtx->streams[m_stream]->codec;
131
132         // get a decoder and open it
133         AVCodec *aCodec = avcodec_find_decoder(m_codecCtx->codec_id);
134         if(!aCodec)
135                 AUD_THROW(AUD_ERROR_FFMPEG, nodecoder_error);
136
137         if(avcodec_open(m_codecCtx, aCodec)<0)
138                 AUD_THROW(AUD_ERROR_FFMPEG, codecopen_error);
139
140         // XXX this prints file information to stdout:
141         //dump_format(m_formatCtx, 0, NULL, 0);
142
143         m_specs.channels = (AUD_Channels) m_codecCtx->channels;
144
145         switch(m_codecCtx->sample_fmt)
146         {
147         case SAMPLE_FMT_U8:
148                 m_convert = AUD_convert_u8_float;
149                 m_specs.format = AUD_FORMAT_U8;
150                 break;
151         case SAMPLE_FMT_S16:
152                 m_convert = AUD_convert_s16_float;
153                 m_specs.format = AUD_FORMAT_S16;
154                 break;
155         case SAMPLE_FMT_S32:
156                 m_convert = AUD_convert_s32_float;
157                 m_specs.format = AUD_FORMAT_S32;
158                 break;
159         case SAMPLE_FMT_FLT:
160                 m_convert = AUD_convert_copy<float>;
161                 m_specs.format = AUD_FORMAT_FLOAT32;
162                 break;
163         case SAMPLE_FMT_DBL:
164                 m_convert = AUD_convert_double_float;
165                 m_specs.format = AUD_FORMAT_FLOAT64;
166                 break;
167         default:
168                 AUD_THROW(AUD_ERROR_FFMPEG, format_error);
169         }
170
171         m_specs.rate = (AUD_SampleRate) m_codecCtx->sample_rate;
172 }
173
174 static const char* fileopen_error = "AUD_FFMPEGReader: File couldn't be "
175                                                                         "opened.";
176
177 AUD_FFMPEGReader::AUD_FFMPEGReader(std::string filename) :
178         m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
179         m_byteiocontext(NULL),
180         m_membuf(NULL)
181 {
182         // open file
183         if(av_open_input_file(&m_formatCtx, filename.c_str(), NULL, 0, NULL)!=0)
184                 AUD_THROW(AUD_ERROR_FILE, fileopen_error);
185
186         try
187         {
188                 init();
189         }
190         catch(AUD_Exception&)
191         {
192                 av_close_input_file(m_formatCtx);
193                 throw;
194         }
195 }
196
197 static const char* streamopen_error = "AUD_FFMPEGReader: Stream couldn't be "
198                                                                           "opened.";
199
200 AUD_FFMPEGReader::AUD_FFMPEGReader(AUD_Reference<AUD_Buffer> buffer) :
201                 m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
202                 m_membuffer(buffer),
203                 m_membufferpos(0)
204 {
205         m_membuf = reinterpret_cast<data_t*>(av_malloc(FF_MIN_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE));
206
207         m_byteiocontext = av_alloc_put_byte(m_membuf, FF_MIN_BUFFER_SIZE, 0, this,
208                                                                                 read_packet, NULL, seek_packet);
209
210         if(!m_byteiocontext)
211         {
212                 av_free(m_byteiocontext);
213                 AUD_THROW(AUD_ERROR_FILE, fileopen_error);
214         }
215
216         AVProbeData probe_data;
217         probe_data.filename = "";
218         probe_data.buf = reinterpret_cast<data_t*>(buffer.get()->getBuffer());
219         probe_data.buf_size = buffer.get()->getSize();
220         AVInputFormat* fmt = av_probe_input_format(&probe_data, 1);
221
222         // open stream
223         if(av_open_input_stream(&m_formatCtx, m_byteiocontext, "", fmt, NULL)!=0)
224         {
225                 av_free(m_byteiocontext);
226                 AUD_THROW(AUD_ERROR_FILE, streamopen_error);
227         }
228
229         try
230         {
231                 init();
232         }
233         catch(AUD_Exception&)
234         {
235                 av_close_input_stream(m_formatCtx);
236                 av_free(m_byteiocontext);
237                 throw;
238         }
239 }
240
241 AUD_FFMPEGReader::~AUD_FFMPEGReader()
242 {
243         avcodec_close(m_codecCtx);
244
245         if(m_byteiocontext)
246         {
247                 av_close_input_stream(m_formatCtx);
248                 av_free(m_byteiocontext);
249         }
250         else
251                 av_close_input_file(m_formatCtx);
252 }
253
254 int AUD_FFMPEGReader::read_packet(void* opaque, uint8_t* buf, int buf_size)
255 {
256         AUD_FFMPEGReader* reader = reinterpret_cast<AUD_FFMPEGReader*>(opaque);
257
258         int size = AUD_MIN(buf_size, reader->m_membuffer->getSize() - reader->m_membufferpos);
259
260         if(size < 0)
261                 return -1;
262
263         memcpy(buf, ((data_t*)reader->m_membuffer->getBuffer()) + reader->m_membufferpos, size);
264         reader->m_membufferpos += size;
265
266         return size;
267 }
268
269 int64_t AUD_FFMPEGReader::seek_packet(void* opaque, int64_t offset, int whence)
270 {
271         AUD_FFMPEGReader* reader = reinterpret_cast<AUD_FFMPEGReader*>(opaque);
272
273         switch(whence)
274         {
275         case SEEK_SET:
276                 reader->m_membufferpos = 0;
277                 break;
278         case SEEK_END:
279                 reader->m_membufferpos = reader->m_membuffer->getSize();
280                 break;
281         case AVSEEK_SIZE:
282                 return reader->m_membuffer->getSize();
283         }
284
285         return (reader->m_membufferpos += offset);
286 }
287
288 bool AUD_FFMPEGReader::isSeekable() const
289 {
290         return true;
291 }
292
293 void AUD_FFMPEGReader::seek(int position)
294 {
295         if(position >= 0)
296         {
297                 uint64_t st_time = m_formatCtx->start_time;
298                 uint64_t seek_pos = ((uint64_t)position) * ((uint64_t)AV_TIME_BASE) / ((uint64_t)m_specs.rate);
299
300                 if (seek_pos < 0) {
301                         seek_pos = 0;
302                 }
303
304                 if (st_time != AV_NOPTS_VALUE) {
305                         seek_pos += st_time;
306                 }
307
308                 double pts_time_base = 
309                         av_q2d(m_formatCtx->streams[m_stream]->time_base);
310                 uint64_t pts_st_time =
311                         ((st_time != AV_NOPTS_VALUE) ? st_time : 0)
312                         / pts_time_base / (uint64_t) AV_TIME_BASE;
313
314                 // a value < 0 tells us that seeking failed
315                 if(av_seek_frame(m_formatCtx, -1, seek_pos,
316                                  AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY) >= 0)
317                 {
318                         avcodec_flush_buffers(m_codecCtx);
319                         m_position = position;
320
321                         AVPacket packet;
322                         bool search = true;
323
324                         while(search && av_read_frame(m_formatCtx, &packet) >= 0)
325                         {
326                                 // is it a frame from the audio stream?
327                                 if(packet.stream_index == m_stream)
328                                 {
329                                         // decode the package
330                                         m_pkgbuf_left = decode(&packet, m_pkgbuf);
331                                         search = false;
332
333                                         // check position
334                                         if(packet.pts != AV_NOPTS_VALUE)
335                                         {
336                                                 // calculate real position, and read to frame!
337                                                 m_position = (packet.pts - 
338                                                         pts_st_time) * pts_time_base * m_specs.rate;
339
340                                                 if(m_position < position)
341                                                 {
342                                                         // read until we're at the right position
343                                                         int length = AUD_DEFAULT_BUFFER_SIZE;
344                                                         AUD_Buffer buffer(length * AUD_SAMPLE_SIZE(m_specs));
345                                                         for(int len = position - m_position;
346                                                                 length == AUD_DEFAULT_BUFFER_SIZE;
347                                                                 len -= AUD_DEFAULT_BUFFER_SIZE)
348                                                         {
349                                                                 if(len < AUD_DEFAULT_BUFFER_SIZE)
350                                                                         length = len;
351                                                                 read(length, buffer.getBuffer());
352                                                         }
353                                                 }
354                                         }
355                                 }
356                                 av_free_packet(&packet);
357                         }
358                 }
359                 else
360                 {
361                         fprintf(stderr, "seeking failed!\n");
362                         // Seeking failed, do nothing.
363                 }
364         }
365 }
366
367 int AUD_FFMPEGReader::getLength() const
368 {
369         // return approximated remaning size
370         return (int)((m_formatCtx->duration * m_codecCtx->sample_rate)
371                                  / AV_TIME_BASE)-m_position;
372 }
373
374 int AUD_FFMPEGReader::getPosition() const
375 {
376         return m_position;
377 }
378
379 AUD_Specs AUD_FFMPEGReader::getSpecs() const
380 {
381         return m_specs.specs;
382 }
383
384 void AUD_FFMPEGReader::read(int & length, sample_t* buffer)
385 {
386         // read packages and decode them
387         AVPacket packet;
388         int data_size = 0;
389         int pkgbuf_pos;
390         int left = length;
391         int sample_size = AUD_DEVICE_SAMPLE_SIZE(m_specs);
392
393         sample_t* buf = buffer;
394         pkgbuf_pos = m_pkgbuf_left;
395         m_pkgbuf_left = 0;
396
397         // there may still be data in the buffer from the last call
398         if(pkgbuf_pos > 0)
399         {
400                 data_size = AUD_MIN(pkgbuf_pos, left * sample_size);
401                 m_convert((data_t*) buf, (data_t*) m_pkgbuf.getBuffer(),
402                                   data_size / AUD_FORMAT_SIZE(m_specs.format));
403                 buf += data_size / AUD_FORMAT_SIZE(m_specs.format);
404                 left -= data_size/sample_size;
405         }
406
407         // for each frame read as long as there isn't enough data already
408         while((left > 0) && (av_read_frame(m_formatCtx, &packet) >= 0))
409         {
410                 // is it a frame from the audio stream?
411                 if(packet.stream_index == m_stream)
412                 {
413                         // decode the package
414                         pkgbuf_pos = decode(&packet, m_pkgbuf);
415
416                         // copy to output buffer
417                         data_size = AUD_MIN(pkgbuf_pos, left * sample_size);
418                         m_convert((data_t*) buf, (data_t*) m_pkgbuf.getBuffer(),
419                                           data_size / AUD_FORMAT_SIZE(m_specs.format));
420                         buf += data_size / AUD_FORMAT_SIZE(m_specs.format);
421                         left -= data_size/sample_size;
422                 }
423                 av_free_packet(&packet);
424         }
425         // read more data than necessary?
426         if(pkgbuf_pos > data_size)
427         {
428                 m_pkgbuf_left = pkgbuf_pos-data_size;
429                 memmove(m_pkgbuf.getBuffer(),
430                                 ((data_t*)m_pkgbuf.getBuffer())+data_size,
431                                 pkgbuf_pos-data_size);
432         }
433
434         if(left > 0)
435                 length -= left;
436         m_position += length;
437 }