Audaspace: HUGE Refactor.
[blender.git] / intern / audaspace / ffmpeg / AUD_FFMPEGReader.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN LGPL LICENSE BLOCK *****
5  *
6  * Copyright 2009 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 Lesser General Public License as published by
12  * the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with AudaSpace.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * ***** END LGPL LICENSE BLOCK *****
24  */
25
26 // needed for INT64_C
27 #ifndef __STDC_CONSTANT_MACROS
28 #define __STDC_CONSTANT_MACROS
29 #endif
30
31 #include "AUD_FFMPEGReader.h"
32
33 extern "C" {
34 #include <libavcodec/avcodec.h>
35 #include <libavformat/avformat.h>
36 }
37
38 int AUD_FFMPEGReader::decode(AVPacket* packet, AUD_Buffer& buffer)
39 {
40         // save packet parameters
41         uint8_t *audio_pkg_data = packet->data;
42         int audio_pkg_size = packet->size;
43
44         int buf_size = buffer.getSize();
45         int buf_pos = 0;
46
47         int read_length, data_size;
48
49         // as long as there is still data in the package
50         while(audio_pkg_size > 0)
51         {
52                 // resize buffer if needed
53                 if(buf_size - buf_pos < AVCODEC_MAX_AUDIO_FRAME_SIZE)
54                 {
55                         buffer.resize(buf_size + AVCODEC_MAX_AUDIO_FRAME_SIZE, true);
56                         buf_size += AVCODEC_MAX_AUDIO_FRAME_SIZE;
57                 }
58
59                 // read samples from the packet
60                 data_size = buf_size - buf_pos;
61                 read_length = avcodec_decode_audio3(m_codecCtx,
62                         (int16_t*)(((data_t*)buffer.getBuffer())+buf_pos),
63                         &data_size,
64                         packet);
65
66                 // read error, next packet!
67                 if(read_length < 0)
68                         break;
69
70                 buf_pos += data_size;
71
72                 // move packet parameters
73                 audio_pkg_data += read_length;
74                 audio_pkg_size -= read_length;
75         }
76
77         return buf_pos;
78 }
79
80 void AUD_FFMPEGReader::init()
81 {
82         m_position = 0;
83         m_pkgbuf_left = 0;
84
85         if(av_find_stream_info(m_formatCtx)<0)
86                 AUD_THROW(AUD_ERROR_FFMPEG);
87
88         // find audio stream and codec
89         m_stream = -1;
90
91         for(unsigned int i = 0; i < m_formatCtx->nb_streams; i++)
92         {
93                 if((m_formatCtx->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO)
94                         && (m_stream < 0))
95                 {
96                         m_stream=i;
97                         break;
98                 }
99         }
100
101         if(m_stream == -1)
102                 AUD_THROW(AUD_ERROR_FFMPEG);
103
104         m_codecCtx = m_formatCtx->streams[m_stream]->codec;
105
106         // get a decoder and open it
107         AVCodec *aCodec = avcodec_find_decoder(m_codecCtx->codec_id);
108         if(!aCodec)
109                 AUD_THROW(AUD_ERROR_FFMPEG);
110
111         if(avcodec_open(m_codecCtx, aCodec)<0)
112                 AUD_THROW(AUD_ERROR_FFMPEG);
113
114         // XXX this prints file information to stdout:
115         //dump_format(m_formatCtx, 0, NULL, 0);
116
117         m_specs.channels = (AUD_Channels) m_codecCtx->channels;
118
119         switch(m_codecCtx->sample_fmt)
120         {
121         case SAMPLE_FMT_U8:
122                 m_convert = AUD_convert_u8_float;
123                 m_specs.format = AUD_FORMAT_U8;
124                 break;
125         case SAMPLE_FMT_S16:
126                 m_convert = AUD_convert_s16_float;
127                 m_specs.format = AUD_FORMAT_S16;
128                 break;
129         case SAMPLE_FMT_S32:
130                 m_convert = AUD_convert_s32_float;
131                 m_specs.format = AUD_FORMAT_S32;
132                 break;
133         case SAMPLE_FMT_FLT:
134                 m_convert = AUD_convert_copy<float>;
135                 m_specs.format = AUD_FORMAT_FLOAT32;
136                 break;
137         case SAMPLE_FMT_DBL:
138                 m_convert = AUD_convert_double_float;
139                 m_specs.format = AUD_FORMAT_FLOAT64;
140                 break;
141         default:
142                 AUD_THROW(AUD_ERROR_FILE);
143         }
144
145         m_specs.rate = (AUD_SampleRate) m_codecCtx->sample_rate;
146 }
147
148 AUD_FFMPEGReader::AUD_FFMPEGReader(std::string filename) :
149         m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
150         m_byteiocontext(NULL)
151 {
152         // open file
153         if(av_open_input_file(&m_formatCtx, filename.c_str(), NULL, 0, NULL)!=0)
154                 AUD_THROW(AUD_ERROR_FILE);
155
156         try
157         {
158                 init();
159         }
160         catch(AUD_Exception&)
161         {
162                 av_close_input_file(m_formatCtx);
163                 throw;
164         }
165 }
166
167 AUD_FFMPEGReader::AUD_FFMPEGReader(AUD_Reference<AUD_Buffer> buffer) :
168                 m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
169                 m_membuffer(buffer)
170 {
171         m_byteiocontext = (ByteIOContext*)av_mallocz(sizeof(ByteIOContext));
172
173         if(init_put_byte(m_byteiocontext, (data_t*)buffer.get()->getBuffer(),
174                                          buffer.get()->getSize(), 0, NULL, NULL, NULL, NULL) != 0)
175         {
176                 av_free(m_byteiocontext);
177                 AUD_THROW(AUD_ERROR_FILE);
178         }
179
180         AVProbeData probe_data;
181         probe_data.filename = "";
182         probe_data.buf = (data_t*)buffer.get()->getBuffer();
183         probe_data.buf_size = buffer.get()->getSize();
184         AVInputFormat* fmt = av_probe_input_format(&probe_data, 1);
185
186         // open stream
187         if(av_open_input_stream(&m_formatCtx, m_byteiocontext, "", fmt, NULL)!=0)
188         {
189                 av_free(m_byteiocontext);
190                 AUD_THROW(AUD_ERROR_FILE);
191         }
192
193         try
194         {
195                 init();
196         }
197         catch(AUD_Exception&)
198         {
199                 av_close_input_stream(m_formatCtx);
200                 av_free(m_byteiocontext);
201                 throw;
202         }
203 }
204
205 AUD_FFMPEGReader::~AUD_FFMPEGReader()
206 {
207         avcodec_close(m_codecCtx);
208
209         if(m_byteiocontext)
210         {
211                 av_close_input_stream(m_formatCtx);
212                 av_free(m_byteiocontext);
213         }
214         else
215                 av_close_input_file(m_formatCtx);
216 }
217
218 bool AUD_FFMPEGReader::isSeekable() const
219 {
220         return true;
221 }
222
223 void AUD_FFMPEGReader::seek(int position)
224 {
225         if(position >= 0)
226         {
227                 // a value < 0 tells us that seeking failed
228                 if(av_seek_frame(m_formatCtx,
229                                                  -1,
230                                                  (uint64_t)(((uint64_t)position *
231                                                                          (uint64_t)AV_TIME_BASE) /
232                                                                         (uint64_t)m_specs.rate),
233                                                  AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY) >= 0)
234                 {
235                         avcodec_flush_buffers(m_codecCtx);
236                         m_position = position;
237
238                         AVPacket packet;
239                         bool search = true;
240
241                         while(search && av_read_frame(m_formatCtx, &packet) >= 0)
242                         {
243                                 // is it a frame from the audio stream?
244                                 if(packet.stream_index == m_stream)
245                                 {
246                                         // decode the package
247                                         m_pkgbuf_left = decode(&packet, m_pkgbuf);
248                                         search = false;
249
250                                         // check position
251                                         if(packet.pts != AV_NOPTS_VALUE)
252                                         {
253                                                 // calculate real position, and read to frame!
254                                                 m_position = packet.pts *
255                                                         av_q2d(m_formatCtx->streams[m_stream]->time_base) *
256                                                         m_specs.rate;
257
258                                                 if(m_position < position)
259                                                 {
260                                                         // read until we're at the right position
261                                                         int length = AUD_DEFAULT_BUFFER_SIZE;
262                                                         sample_t* buffer;
263                                                         for(int len = position - m_position;
264                                                                 length == AUD_DEFAULT_BUFFER_SIZE;
265                                                                 len -= AUD_DEFAULT_BUFFER_SIZE)
266                                                         {
267                                                                 if(len < AUD_DEFAULT_BUFFER_SIZE)
268                                                                         length = len;
269                                                                 read(length, buffer);
270                                                         }
271                                                 }
272                                         }
273                                 }
274                                 av_free_packet(&packet);
275                         }
276                 }
277                 else
278                 {
279                         // Seeking failed, do nothing.
280                 }
281         }
282 }
283
284 int AUD_FFMPEGReader::getLength() const
285 {
286         // return approximated remaning size
287         return (int)((m_formatCtx->duration * m_codecCtx->sample_rate)
288                                  / AV_TIME_BASE)-m_position;
289 }
290
291 int AUD_FFMPEGReader::getPosition() const
292 {
293         return m_position;
294 }
295
296 AUD_Specs AUD_FFMPEGReader::getSpecs() const
297 {
298         return m_specs.specs;
299 }
300
301 void AUD_FFMPEGReader::read(int & length, sample_t* & buffer)
302 {
303         // read packages and decode them
304         AVPacket packet;
305         int data_size = 0;
306         int pkgbuf_pos;
307         int left = length;
308         int sample_size = AUD_DEVICE_SAMPLE_SIZE(m_specs);
309
310         // resize output buffer if necessary
311         if(m_buffer.getSize() < length * AUD_SAMPLE_SIZE(m_specs))
312                 m_buffer.resize(length * AUD_SAMPLE_SIZE(m_specs));
313
314         buffer = m_buffer.getBuffer();
315         pkgbuf_pos = m_pkgbuf_left;
316         m_pkgbuf_left = 0;
317
318         // there may still be data in the buffer from the last call
319         if(pkgbuf_pos > 0)
320         {
321                 data_size = AUD_MIN(pkgbuf_pos, left * sample_size);
322                 m_convert((data_t*) buffer, (data_t*) m_pkgbuf.getBuffer(),
323                                   data_size / AUD_FORMAT_SIZE(m_specs.format));
324                 buffer += data_size / AUD_FORMAT_SIZE(m_specs.format);
325                 left -= data_size/sample_size;
326         }
327
328         // for each frame read as long as there isn't enough data already
329         while((left > 0) && (av_read_frame(m_formatCtx, &packet) >= 0))
330         {
331                 // is it a frame from the audio stream?
332                 if(packet.stream_index == m_stream)
333                 {
334                         // decode the package
335                         pkgbuf_pos = decode(&packet, m_pkgbuf);
336
337                         // copy to output buffer
338                         data_size = AUD_MIN(pkgbuf_pos, left * sample_size);
339                         m_convert((data_t*) buffer, (data_t*) m_pkgbuf.getBuffer(),
340                                           data_size / AUD_FORMAT_SIZE(m_specs.format));
341                         buffer += data_size / AUD_FORMAT_SIZE(m_specs.format);
342                         left -= data_size/sample_size;
343                 }
344                 av_free_packet(&packet);
345         }
346         // read more data than necessary?
347         if(pkgbuf_pos > data_size)
348         {
349                 m_pkgbuf_left = pkgbuf_pos-data_size;
350                 memmove(m_pkgbuf.getBuffer(),
351                                 ((data_t*)m_pkgbuf.getBuffer())+data_size,
352                                 pkgbuf_pos-data_size);
353         }
354
355         buffer = m_buffer.getBuffer();
356
357         if(left > 0)
358                 length -= left;
359         m_position += length;
360 }