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