ea6e0c549fa871f606b55aeccd2c80bd378bf1de
[blender-staging.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         m_membuf(NULL)
177 {
178         // open file
179         if(av_open_input_file(&m_formatCtx, filename.c_str(), NULL, 0, NULL)!=0)
180                 AUD_THROW(AUD_ERROR_FILE, fileopen_error);
181
182         try
183         {
184                 init();
185         }
186         catch(AUD_Exception&)
187         {
188                 av_close_input_file(m_formatCtx);
189                 throw;
190         }
191 }
192
193 static const char* streamopen_error = "AUD_FFMPEGReader: Stream couldn't be "
194                                                                           "opened.";
195
196 AUD_FFMPEGReader::AUD_FFMPEGReader(AUD_Reference<AUD_Buffer> buffer) :
197                 m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
198                 m_membuffer(buffer),
199                 m_membufferpos(0)
200 {
201         m_membuf = reinterpret_cast<data_t*>(av_malloc(FF_MIN_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE));
202
203         m_byteiocontext = av_alloc_put_byte(m_membuf, FF_MIN_BUFFER_SIZE, 0, this,
204                                                                                 read_packet, NULL, seek_packet);
205
206         if(!m_byteiocontext)
207         {
208                 av_free(m_byteiocontext);
209                 AUD_THROW(AUD_ERROR_FILE, fileopen_error);
210         }
211
212         AVProbeData probe_data;
213         probe_data.filename = "";
214         probe_data.buf = reinterpret_cast<data_t*>(buffer.get()->getBuffer());
215         probe_data.buf_size = buffer.get()->getSize();
216         AVInputFormat* fmt = av_probe_input_format(&probe_data, 1);
217
218         // open stream
219         if(av_open_input_stream(&m_formatCtx, m_byteiocontext, "", fmt, NULL)!=0)
220         {
221                 av_free(m_byteiocontext);
222                 AUD_THROW(AUD_ERROR_FILE, streamopen_error);
223         }
224
225         try
226         {
227                 init();
228         }
229         catch(AUD_Exception&)
230         {
231                 av_close_input_stream(m_formatCtx);
232                 av_free(m_byteiocontext);
233                 throw;
234         }
235 }
236
237 AUD_FFMPEGReader::~AUD_FFMPEGReader()
238 {
239         avcodec_close(m_codecCtx);
240
241         if(m_byteiocontext)
242         {
243                 av_close_input_stream(m_formatCtx);
244                 av_free(m_byteiocontext);
245         }
246         else
247                 av_close_input_file(m_formatCtx);
248 }
249
250 int AUD_FFMPEGReader::read_packet(void* opaque, uint8_t* buf, int buf_size)
251 {
252         AUD_FFMPEGReader* reader = reinterpret_cast<AUD_FFMPEGReader*>(opaque);
253
254         int size = AUD_MIN(buf_size, reader->m_membuffer.get()->getSize() - reader->m_membufferpos);
255
256         if(size < 0)
257                 return -1;
258
259         memcpy(buf, ((data_t*)reader->m_membuffer.get()->getBuffer()) + reader->m_membufferpos, size);
260         reader->m_membufferpos += size;
261
262         return size;
263 }
264
265 int64_t AUD_FFMPEGReader::seek_packet(void* opaque, int64_t offset, int whence)
266 {
267         AUD_FFMPEGReader* reader = reinterpret_cast<AUD_FFMPEGReader*>(opaque);
268
269         switch(whence)
270         {
271         case SEEK_SET:
272                 reader->m_membufferpos = 0;
273                 break;
274         case SEEK_END:
275                 reader->m_membufferpos = reader->m_membuffer.get()->getSize();
276                 break;
277         case AVSEEK_SIZE:
278                 return reader->m_membuffer.get()->getSize();
279         }
280
281         return (reader->m_membufferpos += offset);
282 }
283
284 bool AUD_FFMPEGReader::isSeekable() const
285 {
286         return true;
287 }
288
289 void AUD_FFMPEGReader::seek(int position)
290 {
291         if(position >= 0)
292         {
293                 uint64_t st_time = m_formatCtx->start_time;
294                 uint64_t seek_pos = ((uint64_t)position) * ((uint64_t)AV_TIME_BASE) / ((uint64_t)m_specs.rate);
295
296                 if (seek_pos < 0) {
297                         seek_pos = 0;
298                 }
299
300                 if (st_time != AV_NOPTS_VALUE) {
301                         seek_pos += st_time;
302                 }
303
304                 double pts_time_base = 
305                         av_q2d(m_formatCtx->streams[m_stream]->time_base);
306                 uint64_t pts_st_time =
307                         ((st_time != AV_NOPTS_VALUE) ? st_time : 0)
308                         / pts_time_base / (uint64_t) AV_TIME_BASE;
309
310                 // a value < 0 tells us that seeking failed
311                 if(av_seek_frame(m_formatCtx, -1, seek_pos,
312                                  AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY) >= 0)
313                 {
314                         avcodec_flush_buffers(m_codecCtx);
315                         m_position = position;
316
317                         AVPacket packet;
318                         bool search = true;
319
320                         while(search && av_read_frame(m_formatCtx, &packet) >= 0)
321                         {
322                                 // is it a frame from the audio stream?
323                                 if(packet.stream_index == m_stream)
324                                 {
325                                         // decode the package
326                                         m_pkgbuf_left = decode(&packet, m_pkgbuf);
327                                         search = false;
328
329                                         // check position
330                                         if(packet.pts != AV_NOPTS_VALUE)
331                                         {
332                                                 // calculate real position, and read to frame!
333                                                 m_position = (packet.pts - 
334                                                         pts_st_time) * pts_time_base * m_specs.rate;
335
336                                                 if(m_position < position)
337                                                 {
338                                                         // read until we're at the right position
339                                                         int length = AUD_DEFAULT_BUFFER_SIZE;
340                                                         sample_t* buffer;
341                                                         for(int len = position - m_position;
342                                                                 length == AUD_DEFAULT_BUFFER_SIZE;
343                                                                 len -= AUD_DEFAULT_BUFFER_SIZE)
344                                                         {
345                                                                 if(len < AUD_DEFAULT_BUFFER_SIZE)
346                                                                         length = len;
347                                                                 read(length, buffer);
348                                                         }
349                                                 }
350                                         }
351                                 }
352                                 av_free_packet(&packet);
353                         }
354                 }
355                 else
356                 {
357                         fprintf(stderr, "seeking failed!\n");
358                         // Seeking failed, do nothing.
359                 }
360         }
361 }
362
363 int AUD_FFMPEGReader::getLength() const
364 {
365         // return approximated remaning size
366         return (int)((m_formatCtx->duration * m_codecCtx->sample_rate)
367                                  / AV_TIME_BASE)-m_position;
368 }
369
370 int AUD_FFMPEGReader::getPosition() const
371 {
372         return m_position;
373 }
374
375 AUD_Specs AUD_FFMPEGReader::getSpecs() const
376 {
377         return m_specs.specs;
378 }
379
380 void AUD_FFMPEGReader::read(int & length, sample_t* & buffer)
381 {
382         // read packages and decode them
383         AVPacket packet;
384         int data_size = 0;
385         int pkgbuf_pos;
386         int left = length;
387         int sample_size = AUD_DEVICE_SAMPLE_SIZE(m_specs);
388
389         // resize output buffer if necessary
390         if(m_buffer.getSize() < length * AUD_SAMPLE_SIZE(m_specs))
391                 m_buffer.resize(length * AUD_SAMPLE_SIZE(m_specs));
392
393         buffer = m_buffer.getBuffer();
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*) buffer, (data_t*) m_pkgbuf.getBuffer(),
402                                   data_size / AUD_FORMAT_SIZE(m_specs.format));
403                 buffer += 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*) buffer, (data_t*) m_pkgbuf.getBuffer(),
419                                           data_size / AUD_FORMAT_SIZE(m_specs.format));
420                         buffer += 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         buffer = m_buffer.getBuffer();
435
436         if(left > 0)
437                 length -= left;
438         m_position += length;
439 }