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