e748235e40e3baa75a376dfc9a39e19343b43c40
[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         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(av_find_stream_info(m_formatCtx)<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         if(avcodec_open(m_codecCtx, aCodec)<0)
137                 AUD_THROW(AUD_ERROR_FFMPEG, codecopen_error);
138
139         // XXX this prints file information to stdout:
140         //dump_format(m_formatCtx, 0, NULL, 0);
141
142         m_specs.channels = (AUD_Channels) m_codecCtx->channels;
143
144         switch(m_codecCtx->sample_fmt)
145         {
146         case SAMPLE_FMT_U8:
147                 m_convert = AUD_convert_u8_float;
148                 m_specs.format = AUD_FORMAT_U8;
149                 break;
150         case SAMPLE_FMT_S16:
151                 m_convert = AUD_convert_s16_float;
152                 m_specs.format = AUD_FORMAT_S16;
153                 break;
154         case SAMPLE_FMT_S32:
155                 m_convert = AUD_convert_s32_float;
156                 m_specs.format = AUD_FORMAT_S32;
157                 break;
158         case SAMPLE_FMT_FLT:
159                 m_convert = AUD_convert_copy<float>;
160                 m_specs.format = AUD_FORMAT_FLOAT32;
161                 break;
162         case SAMPLE_FMT_DBL:
163                 m_convert = AUD_convert_double_float;
164                 m_specs.format = AUD_FORMAT_FLOAT64;
165                 break;
166         default:
167                 AUD_THROW(AUD_ERROR_FFMPEG, format_error);
168         }
169
170         m_specs.rate = (AUD_SampleRate) m_codecCtx->sample_rate;
171 }
172
173 static const char* fileopen_error = "AUD_FFMPEGReader: File couldn't be "
174                                                                         "opened.";
175
176 AUD_FFMPEGReader::AUD_FFMPEGReader(std::string filename) :
177         m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
178         m_byteiocontext(NULL),
179         m_membuf(NULL)
180 {
181         // open file
182         if(av_open_input_file(&m_formatCtx, filename.c_str(), NULL, 0, NULL)!=0)
183                 AUD_THROW(AUD_ERROR_FILE, fileopen_error);
184
185         try
186         {
187                 init();
188         }
189         catch(AUD_Exception&)
190         {
191                 av_close_input_file(m_formatCtx);
192                 throw;
193         }
194 }
195
196 static const char* streamopen_error = "AUD_FFMPEGReader: Stream couldn't be "
197                                                                           "opened.";
198
199 AUD_FFMPEGReader::AUD_FFMPEGReader(AUD_Reference<AUD_Buffer> buffer) :
200                 m_pkgbuf(AVCODEC_MAX_AUDIO_FRAME_SIZE<<1),
201                 m_membuffer(buffer),
202                 m_membufferpos(0)
203 {
204         m_membuf = reinterpret_cast<data_t*>(av_malloc(FF_MIN_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE));
205
206         m_byteiocontext = av_alloc_put_byte(m_membuf, FF_MIN_BUFFER_SIZE, 0, this,
207                                                                                 read_packet, NULL, seek_packet);
208
209         if(!m_byteiocontext)
210         {
211                 av_free(m_byteiocontext);
212                 AUD_THROW(AUD_ERROR_FILE, fileopen_error);
213         }
214
215         AVProbeData probe_data;
216         probe_data.filename = "";
217         probe_data.buf = reinterpret_cast<data_t*>(buffer.get()->getBuffer());
218         probe_data.buf_size = buffer.get()->getSize();
219         AVInputFormat* fmt = av_probe_input_format(&probe_data, 1);
220
221         // open stream
222         if(av_open_input_stream(&m_formatCtx, m_byteiocontext, "", fmt, NULL)!=0)
223         {
224                 av_free(m_byteiocontext);
225                 AUD_THROW(AUD_ERROR_FILE, streamopen_error);
226         }
227
228         try
229         {
230                 init();
231         }
232         catch(AUD_Exception&)
233         {
234                 av_close_input_stream(m_formatCtx);
235                 av_free(m_byteiocontext);
236                 throw;
237         }
238 }
239
240 AUD_FFMPEGReader::~AUD_FFMPEGReader()
241 {
242         avcodec_close(m_codecCtx);
243
244         if(m_byteiocontext)
245         {
246                 av_close_input_stream(m_formatCtx);
247                 av_free(m_byteiocontext);
248         }
249         else
250                 av_close_input_file(m_formatCtx);
251 }
252
253 int AUD_FFMPEGReader::read_packet(void* opaque, uint8_t* buf, int buf_size)
254 {
255         AUD_FFMPEGReader* reader = reinterpret_cast<AUD_FFMPEGReader*>(opaque);
256
257         int size = AUD_MIN(buf_size, reader->m_membuffer.get()->getSize() - reader->m_membufferpos);
258
259         if(size < 0)
260                 return -1;
261
262         memcpy(buf, ((data_t*)reader->m_membuffer.get()->getBuffer()) + reader->m_membufferpos, size);
263         reader->m_membufferpos += size;
264
265         return size;
266 }
267
268 int64_t AUD_FFMPEGReader::seek_packet(void* opaque, int64_t offset, int whence)
269 {
270         AUD_FFMPEGReader* reader = reinterpret_cast<AUD_FFMPEGReader*>(opaque);
271
272         switch(whence)
273         {
274         case SEEK_SET:
275                 reader->m_membufferpos = 0;
276                 break;
277         case SEEK_END:
278                 reader->m_membufferpos = reader->m_membuffer.get()->getSize();
279                 break;
280         case AVSEEK_SIZE:
281                 return reader->m_membuffer.get()->getSize();
282         }
283
284         return (reader->m_membufferpos += offset);
285 }
286
287 bool AUD_FFMPEGReader::isSeekable() const
288 {
289         return true;
290 }
291
292 void AUD_FFMPEGReader::seek(int position)
293 {
294         if(position >= 0)
295         {
296                 uint64_t st_time = m_formatCtx->start_time;
297                 uint64_t seek_pos = ((uint64_t)position) * ((uint64_t)AV_TIME_BASE) / ((uint64_t)m_specs.rate);
298
299                 if (seek_pos < 0) {
300                         seek_pos = 0;
301                 }
302
303                 if (st_time != AV_NOPTS_VALUE) {
304                         seek_pos += st_time;
305                 }
306
307                 double pts_time_base = 
308                         av_q2d(m_formatCtx->streams[m_stream]->time_base);
309                 uint64_t pts_st_time =
310                         ((st_time != AV_NOPTS_VALUE) ? st_time : 0)
311                         / pts_time_base / (uint64_t) AV_TIME_BASE;
312
313                 // a value < 0 tells us that seeking failed
314                 if(av_seek_frame(m_formatCtx, -1, seek_pos,
315                                  AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY) >= 0)
316                 {
317                         avcodec_flush_buffers(m_codecCtx);
318                         m_position = position;
319
320                         AVPacket packet;
321                         bool search = true;
322
323                         while(search && av_read_frame(m_formatCtx, &packet) >= 0)
324                         {
325                                 // is it a frame from the audio stream?
326                                 if(packet.stream_index == m_stream)
327                                 {
328                                         // decode the package
329                                         m_pkgbuf_left = decode(&packet, m_pkgbuf);
330                                         search = false;
331
332                                         // check position
333                                         if(packet.pts != AV_NOPTS_VALUE)
334                                         {
335                                                 // calculate real position, and read to frame!
336                                                 m_position = (packet.pts - 
337                                                         pts_st_time) * pts_time_base * m_specs.rate;
338
339                                                 if(m_position < position)
340                                                 {
341                                                         // read until we're at the right position
342                                                         int length = AUD_DEFAULT_BUFFER_SIZE;
343                                                         sample_t* buffer;
344                                                         for(int len = position - m_position;
345                                                                 length == AUD_DEFAULT_BUFFER_SIZE;
346                                                                 len -= AUD_DEFAULT_BUFFER_SIZE)
347                                                         {
348                                                                 if(len < AUD_DEFAULT_BUFFER_SIZE)
349                                                                         length = len;
350                                                                 read(length, buffer);
351                                                         }
352                                                 }
353                                         }
354                                 }
355                                 av_free_packet(&packet);
356                         }
357                 }
358                 else
359                 {
360                         fprintf(stderr, "seeking failed!\n");
361                         // Seeking failed, do nothing.
362                 }
363         }
364 }
365
366 int AUD_FFMPEGReader::getLength() const
367 {
368         // return approximated remaning size
369         return (int)((m_formatCtx->duration * m_codecCtx->sample_rate)
370                                  / AV_TIME_BASE)-m_position;
371 }
372
373 int AUD_FFMPEGReader::getPosition() const
374 {
375         return m_position;
376 }
377
378 AUD_Specs AUD_FFMPEGReader::getSpecs() const
379 {
380         return m_specs.specs;
381 }
382
383 void AUD_FFMPEGReader::read(int & length, sample_t* & buffer)
384 {
385         // read packages and decode them
386         AVPacket packet;
387         int data_size = 0;
388         int pkgbuf_pos;
389         int left = length;
390         int sample_size = AUD_DEVICE_SAMPLE_SIZE(m_specs);
391
392         // resize output buffer if necessary
393         if(m_buffer.getSize() < length * AUD_SAMPLE_SIZE(m_specs))
394                 m_buffer.resize(length * AUD_SAMPLE_SIZE(m_specs));
395
396         buffer = m_buffer.getBuffer();
397         pkgbuf_pos = m_pkgbuf_left;
398         m_pkgbuf_left = 0;
399
400         // there may still be data in the buffer from the last call
401         if(pkgbuf_pos > 0)
402         {
403                 data_size = AUD_MIN(pkgbuf_pos, left * sample_size);
404                 m_convert((data_t*) buffer, (data_t*) m_pkgbuf.getBuffer(),
405                                   data_size / AUD_FORMAT_SIZE(m_specs.format));
406                 buffer += data_size / AUD_FORMAT_SIZE(m_specs.format);
407                 left -= data_size/sample_size;
408         }
409
410         // for each frame read as long as there isn't enough data already
411         while((left > 0) && (av_read_frame(m_formatCtx, &packet) >= 0))
412         {
413                 // is it a frame from the audio stream?
414                 if(packet.stream_index == m_stream)
415                 {
416                         // decode the package
417                         pkgbuf_pos = decode(&packet, m_pkgbuf);
418
419                         // copy to output buffer
420                         data_size = AUD_MIN(pkgbuf_pos, left * sample_size);
421                         m_convert((data_t*) buffer, (data_t*) m_pkgbuf.getBuffer(),
422                                           data_size / AUD_FORMAT_SIZE(m_specs.format));
423                         buffer += data_size / AUD_FORMAT_SIZE(m_specs.format);
424                         left -= data_size/sample_size;
425                 }
426                 av_free_packet(&packet);
427         }
428         // read more data than necessary?
429         if(pkgbuf_pos > data_size)
430         {
431                 m_pkgbuf_left = pkgbuf_pos-data_size;
432                 memmove(m_pkgbuf.getBuffer(),
433                                 ((data_t*)m_pkgbuf.getBuffer())+data_size,
434                                 pkgbuf_pos-data_size);
435         }
436
437         buffer = m_buffer.getBuffer();
438
439         if(left > 0)
440                 length -= left;
441         m_position += length;
442 }