doxgyen: audaspace tagged.
[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 }
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         // as long as there is still data in the package
56         while(audio_pkg_size > 0)
57         {
58                 // resize buffer if needed
59                 if(buf_size - buf_pos < AVCODEC_MAX_AUDIO_FRAME_SIZE)
60                 {
61                         buffer.resize(buf_size + AVCODEC_MAX_AUDIO_FRAME_SIZE, true);
62                         buf_size += AVCODEC_MAX_AUDIO_FRAME_SIZE;
63                 }
64
65                 // read samples from the packet
66                 data_size = buf_size - buf_pos;
67                 /*read_length = avcodec_decode_audio3(m_codecCtx,
68                         (int16_t*)(((data_t*)buffer.getBuffer())+buf_pos),
69                         &data_size,
70                         packet);*/
71                 read_length = avcodec_decode_audio2(m_codecCtx,
72                                                 (int16_t*)(((data_t*)buffer.getBuffer()) + buf_pos),
73                                                 &data_size,
74                                                 audio_pkg_data,
75                                                 audio_pkg_size);
76
77                 // read error, next packet!
78                 if(read_length < 0)
79                         break;
80
81                 buf_pos += data_size;
82
83                 // move packet parameters
84                 audio_pkg_data += read_length;
85                 audio_pkg_size -= read_length;
86         }
87
88         return buf_pos;
89 }
90
91 static const char* streaminfo_error = "AUD_FFMPEGReader: Stream info couldn't "
92                                                                           "be found.";
93 static const char* noaudio_error = "AUD_FFMPEGReader: File doesn't include an "
94                                                                    "audio stream.";
95 static const char* nodecoder_error = "AUD_FFMPEGReader: No decoder found for "
96                                                                          "the audio stream.";
97 static const char* codecopen_error = "AUD_FFMPEGReader: Codec couldn't be "
98                                                                          "opened.";
99 static const char* format_error = "AUD_FFMPEGReader: Unsupported sample "
100                                                                   "format.";
101
102 void AUD_FFMPEGReader::init()
103 {
104         m_position = 0;
105         m_pkgbuf_left = 0;
106
107         if(av_find_stream_info(m_formatCtx)<0)
108                 AUD_THROW(AUD_ERROR_FFMPEG, streaminfo_error);
109
110         // find audio stream and codec
111         m_stream = -1;
112
113         for(unsigned int i = 0; i < m_formatCtx->nb_streams; i++)
114         {
115                 if((m_formatCtx->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO)
116                         && (m_stream < 0))
117                 {
118                         m_stream=i;
119                         break;
120                 }
121         }
122
123         if(m_stream == -1)
124                 AUD_THROW(AUD_ERROR_FFMPEG, noaudio_error);
125
126         m_codecCtx = m_formatCtx->streams[m_stream]->codec;
127
128         // get a decoder and open it
129         AVCodec *aCodec = avcodec_find_decoder(m_codecCtx->codec_id);
130         if(!aCodec)
131                 AUD_THROW(AUD_ERROR_FFMPEG, nodecoder_error);
132
133         if(avcodec_open(m_codecCtx, aCodec)<0)
134                 AUD_THROW(AUD_ERROR_FFMPEG, codecopen_error);
135
136         // XXX this prints file information to stdout:
137         //dump_format(m_formatCtx, 0, NULL, 0);
138
139         m_specs.channels = (AUD_Channels) m_codecCtx->channels;
140
141         switch(m_codecCtx->sample_fmt)
142         {
143         case SAMPLE_FMT_U8:
144                 m_convert = AUD_convert_u8_float;
145                 m_specs.format = AUD_FORMAT_U8;
146                 break;
147         case SAMPLE_FMT_S16:
148                 m_convert = AUD_convert_s16_float;
149                 m_specs.format = AUD_FORMAT_S16;
150                 break;
151         case SAMPLE_FMT_S32:
152                 m_convert = AUD_convert_s32_float;
153                 m_specs.format = AUD_FORMAT_S32;
154                 break;
155         case SAMPLE_FMT_FLT:
156                 m_convert = AUD_convert_copy<float>;
157                 m_specs.format = AUD_FORMAT_FLOAT32;
158                 break;
159         case SAMPLE_FMT_DBL:
160                 m_convert = AUD_convert_double_float;
161                 m_specs.format = AUD_FORMAT_FLOAT64;
162                 break;
163         default:
164                 AUD_THROW(AUD_ERROR_FFMPEG, format_error);
165         }
166
167         m_specs.rate = (AUD_SampleRate) m_codecCtx->sample_rate;
168 }
169
170 static const char* fileopen_error = "AUD_FFMPEGReader: File couldn't be "
171                                                                         "opened.";
172
173 AUD_FFMPEGReader::AUD_FFMPEGReader(std::string filename) :
174         m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
175         m_byteiocontext(NULL)
176 {
177         // open file
178         if(av_open_input_file(&m_formatCtx, filename.c_str(), NULL, 0, NULL)!=0)
179                 AUD_THROW(AUD_ERROR_FILE, fileopen_error);
180
181         try
182         {
183                 init();
184         }
185         catch(AUD_Exception&)
186         {
187                 av_close_input_file(m_formatCtx);
188                 throw;
189         }
190 }
191
192 static const char* streamopen_error = "AUD_FFMPEGReader: Stream couldn't be "
193                                                                           "opened.";
194
195 AUD_FFMPEGReader::AUD_FFMPEGReader(AUD_Reference<AUD_Buffer> buffer) :
196                 m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
197                 m_membuffer(buffer)
198 {
199         m_byteiocontext = (ByteIOContext*)av_mallocz(sizeof(ByteIOContext));
200
201         if(init_put_byte(m_byteiocontext, (data_t*)buffer.get()->getBuffer(),
202                                          buffer.get()->getSize(), 0, NULL, NULL, NULL, NULL) != 0)
203         {
204                 av_free(m_byteiocontext);
205                 AUD_THROW(AUD_ERROR_FILE, fileopen_error);
206         }
207
208         AVProbeData probe_data;
209         probe_data.filename = "";
210         probe_data.buf = (data_t*)buffer.get()->getBuffer();
211         probe_data.buf_size = buffer.get()->getSize();
212         AVInputFormat* fmt = av_probe_input_format(&probe_data, 1);
213
214         // open stream
215         if(av_open_input_stream(&m_formatCtx, m_byteiocontext, "", fmt, NULL)!=0)
216         {
217                 av_free(m_byteiocontext);
218                 AUD_THROW(AUD_ERROR_FILE, streamopen_error);
219         }
220
221         try
222         {
223                 init();
224         }
225         catch(AUD_Exception&)
226         {
227                 av_close_input_stream(m_formatCtx);
228                 av_free(m_byteiocontext);
229                 throw;
230         }
231 }
232
233 AUD_FFMPEGReader::~AUD_FFMPEGReader()
234 {
235         avcodec_close(m_codecCtx);
236
237         if(m_byteiocontext)
238         {
239                 av_close_input_stream(m_formatCtx);
240                 av_free(m_byteiocontext);
241         }
242         else
243                 av_close_input_file(m_formatCtx);
244 }
245
246 bool AUD_FFMPEGReader::isSeekable() const
247 {
248         return true;
249 }
250
251 void AUD_FFMPEGReader::seek(int position)
252 {
253         if(position >= 0)
254         {
255                 uint64_t st_time = m_formatCtx->start_time;
256                 uint64_t seek_pos = position * AV_TIME_BASE / m_specs.rate;
257
258                 if (seek_pos < 0) {
259                         seek_pos = 0;
260                 }
261
262                 if (st_time != AV_NOPTS_VALUE) {
263                         seek_pos += st_time;
264                 }
265
266                 double pts_time_base = 
267                         av_q2d(m_formatCtx->streams[m_stream]->time_base);
268                 uint64_t pts_st_time =
269                         ((st_time != AV_NOPTS_VALUE) ? st_time : 0)
270                         / pts_time_base / (uint64_t) AV_TIME_BASE;
271
272                 // a value < 0 tells us that seeking failed
273                 if(av_seek_frame(m_formatCtx, -1, seek_pos,
274                                  AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY) >= 0)
275                 {
276                         avcodec_flush_buffers(m_codecCtx);
277                         m_position = position;
278
279                         AVPacket packet;
280                         bool search = true;
281
282                         while(search && av_read_frame(m_formatCtx, &packet) >= 0)
283                         {
284                                 // is it a frame from the audio stream?
285                                 if(packet.stream_index == m_stream)
286                                 {
287                                         // decode the package
288                                         m_pkgbuf_left = decode(&packet, m_pkgbuf);
289                                         search = false;
290
291                                         // check position
292                                         if(packet.pts != AV_NOPTS_VALUE)
293                                         {
294                                                 // calculate real position, and read to frame!
295                                                 m_position = (packet.pts - 
296                                                         pts_st_time) * pts_time_base * m_specs.rate;
297
298                                                 if(m_position < position)
299                                                 {
300                                                         // read until we're at the right position
301                                                         int length = AUD_DEFAULT_BUFFER_SIZE;
302                                                         sample_t* buffer;
303                                                         for(int len = position - m_position;
304                                                                 length == AUD_DEFAULT_BUFFER_SIZE;
305                                                                 len -= AUD_DEFAULT_BUFFER_SIZE)
306                                                         {
307                                                                 if(len < AUD_DEFAULT_BUFFER_SIZE)
308                                                                         length = len;
309                                                                 read(length, buffer);
310                                                         }
311                                                 }
312                                         }
313                                 }
314                                 av_free_packet(&packet);
315                         }
316                 }
317                 else
318                 {
319                         fprintf(stderr, "seeking failed!\n");
320                         // Seeking failed, do nothing.
321                 }
322         }
323 }
324
325 int AUD_FFMPEGReader::getLength() const
326 {
327         // return approximated remaning size
328         return (int)((m_formatCtx->duration * m_codecCtx->sample_rate)
329                                  / AV_TIME_BASE)-m_position;
330 }
331
332 int AUD_FFMPEGReader::getPosition() const
333 {
334         return m_position;
335 }
336
337 AUD_Specs AUD_FFMPEGReader::getSpecs() const
338 {
339         return m_specs.specs;
340 }
341
342 void AUD_FFMPEGReader::read(int & length, sample_t* & buffer)
343 {
344         // read packages and decode them
345         AVPacket packet;
346         int data_size = 0;
347         int pkgbuf_pos;
348         int left = length;
349         int sample_size = AUD_DEVICE_SAMPLE_SIZE(m_specs);
350
351         // resize output buffer if necessary
352         if(m_buffer.getSize() < length * AUD_SAMPLE_SIZE(m_specs))
353                 m_buffer.resize(length * AUD_SAMPLE_SIZE(m_specs));
354
355         buffer = m_buffer.getBuffer();
356         pkgbuf_pos = m_pkgbuf_left;
357         m_pkgbuf_left = 0;
358
359         // there may still be data in the buffer from the last call
360         if(pkgbuf_pos > 0)
361         {
362                 data_size = AUD_MIN(pkgbuf_pos, left * sample_size);
363                 m_convert((data_t*) buffer, (data_t*) m_pkgbuf.getBuffer(),
364                                   data_size / AUD_FORMAT_SIZE(m_specs.format));
365                 buffer += data_size / AUD_FORMAT_SIZE(m_specs.format);
366                 left -= data_size/sample_size;
367         }
368
369         // for each frame read as long as there isn't enough data already
370         while((left > 0) && (av_read_frame(m_formatCtx, &packet) >= 0))
371         {
372                 // is it a frame from the audio stream?
373                 if(packet.stream_index == m_stream)
374                 {
375                         // decode the package
376                         pkgbuf_pos = decode(&packet, m_pkgbuf);
377
378                         // copy to output buffer
379                         data_size = AUD_MIN(pkgbuf_pos, left * sample_size);
380                         m_convert((data_t*) buffer, (data_t*) m_pkgbuf.getBuffer(),
381                                           data_size / AUD_FORMAT_SIZE(m_specs.format));
382                         buffer += data_size / AUD_FORMAT_SIZE(m_specs.format);
383                         left -= data_size/sample_size;
384                 }
385                 av_free_packet(&packet);
386         }
387         // read more data than necessary?
388         if(pkgbuf_pos > data_size)
389         {
390                 m_pkgbuf_left = pkgbuf_pos-data_size;
391                 memmove(m_pkgbuf.getBuffer(),
392                                 ((data_t*)m_pkgbuf.getBuffer())+data_size,
393                                 pkgbuf_pos-data_size);
394         }
395
396         buffer = m_buffer.getBuffer();
397
398         if(left > 0)
399                 length -= left;
400         m_position += length;
401 }