3D Audio GSoC:
[blender.git] / intern / audaspace / ffmpeg / AUD_FFMPEGWriter.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_FFMPEGWriter.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_FFMPEGWriter.h"
38
39 extern "C" {
40 #include <libavcodec/avcodec.h>
41 #include <libavformat/avformat.h>
42 #include <libavformat/avio.h>
43 }
44
45 static const char* context_error = "AUD_FFMPEGWriter: Couldn't allocate context.";
46 static const char* codec_error = "AUD_FFMPEGWriter: Invalid codec or codec not found.";
47 static const char* stream_error = "AUD_FFMPEGWriter: Couldn't allocate stream.";
48 static const char* format_error = "AUD_FFMPEGWriter: Unsupported sample format.";
49 static const char* file_error = "AUD_FFMPEGWriter: File couldn't be written.";
50 static const char* write_error = "AUD_FFMPEGWriter: Error writing packet.";
51
52 AUD_FFMPEGWriter::AUD_FFMPEGWriter(std::string filename, AUD_DeviceSpecs specs, AUD_Container format, AUD_Codec codec, unsigned int bitrate) :
53         m_position(0),
54         m_specs(specs),
55         m_input_samples(0)
56 {
57         static const char* formats[] = { NULL, "ac3", "flac", "matroska", "mp2", "mp3", "ogg", "wav" };
58
59         if(avformat_alloc_output_context2(&m_formatCtx, NULL, formats[format], filename.c_str()))
60                 AUD_THROW(AUD_ERROR_FFMPEG, context_error);
61
62         m_outputFmt = m_formatCtx->oformat;
63
64         switch(codec)
65         {
66         case AUD_CODEC_AAC:
67                 m_outputFmt->audio_codec = CODEC_ID_AAC;
68                 break;
69         case AUD_CODEC_AC3:
70                 m_outputFmt->audio_codec = CODEC_ID_AC3;
71                 break;
72         case AUD_CODEC_FLAC:
73                 m_outputFmt->audio_codec = CODEC_ID_FLAC;
74                 break;
75         case AUD_CODEC_MP2:
76                 m_outputFmt->audio_codec = CODEC_ID_MP2;
77                 break;
78         case AUD_CODEC_MP3:
79                 m_outputFmt->audio_codec = CODEC_ID_MP3;
80                 break;
81         case AUD_CODEC_PCM:
82                 switch(specs.format)
83                 {
84                 case AUD_FORMAT_U8:
85                         m_outputFmt->audio_codec = CODEC_ID_PCM_U8;
86                         break;
87                 case AUD_FORMAT_S16:
88                         m_outputFmt->audio_codec = CODEC_ID_PCM_S16LE;
89                         break;
90                 case AUD_FORMAT_S24:
91                         m_outputFmt->audio_codec = CODEC_ID_PCM_S24LE;
92                         break;
93                 case AUD_FORMAT_S32:
94                         m_outputFmt->audio_codec = CODEC_ID_PCM_S32LE;
95                         break;
96                 case AUD_FORMAT_FLOAT32:
97                         m_outputFmt->audio_codec = CODEC_ID_PCM_F32LE;
98                         break;
99                 case AUD_FORMAT_FLOAT64:
100                         m_outputFmt->audio_codec = CODEC_ID_PCM_F64LE;
101                         break;
102                 default:
103                         m_outputFmt->audio_codec = CODEC_ID_NONE;
104                         break;
105                 }
106                 break;
107         case AUD_CODEC_VORBIS:
108                 m_outputFmt->audio_codec = CODEC_ID_VORBIS;
109                 break;
110         default:
111                 m_outputFmt->audio_codec = CODEC_ID_NONE;
112                 break;
113         }
114
115         try
116         {
117                 if(m_outputFmt->audio_codec == CODEC_ID_NONE)
118                         AUD_THROW(AUD_ERROR_SPECS, codec_error);
119
120                 m_stream = av_new_stream(m_formatCtx, 0);
121                 if(!m_stream)
122                         AUD_THROW(AUD_ERROR_FFMPEG, stream_error);
123
124                 m_codecCtx = m_stream->codec;
125                 m_codecCtx->codec_id = m_outputFmt->audio_codec;
126                 m_codecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
127                 m_codecCtx->bit_rate = bitrate;
128                 m_codecCtx->sample_rate = int(m_specs.rate);
129                 m_codecCtx->channels = m_specs.channels;
130                 m_codecCtx->time_base = (AVRational){1, m_codecCtx->sample_rate};
131
132                 switch(m_specs.format)
133                 {
134                 case AUD_FORMAT_U8:
135                         m_convert = AUD_convert_float_u8;
136                         m_codecCtx->sample_fmt = SAMPLE_FMT_U8;
137                         break;
138                 case AUD_FORMAT_S16:
139                         m_convert = AUD_convert_float_s16;
140                         m_codecCtx->sample_fmt = SAMPLE_FMT_S16;
141                         break;
142                 case AUD_FORMAT_S32:
143                         m_convert = AUD_convert_float_s32;
144                         m_codecCtx->sample_fmt = SAMPLE_FMT_S32;
145                         break;
146                 case AUD_FORMAT_FLOAT32:
147                         m_convert = AUD_convert_copy<float>;
148                         m_codecCtx->sample_fmt = SAMPLE_FMT_FLT;
149                         break;
150                 case AUD_FORMAT_FLOAT64:
151                         m_convert = AUD_convert_float_double;
152                         m_codecCtx->sample_fmt = SAMPLE_FMT_DBL;
153                         break;
154                 default:
155                         AUD_THROW(AUD_ERROR_FFMPEG, format_error);
156                 }
157
158                 try
159                 {
160                         if(m_formatCtx->oformat->flags & AVFMT_GLOBALHEADER)
161                                 m_codecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
162
163                         AVCodec* codec = avcodec_find_encoder(m_codecCtx->codec_id);
164                         if(!codec)
165                                 AUD_THROW(AUD_ERROR_FFMPEG, codec_error);
166
167                         if(avcodec_open(m_codecCtx, codec))
168                                 AUD_THROW(AUD_ERROR_FFMPEG, codec_error);
169
170                         m_output_buffer.resize(FF_MIN_BUFFER_SIZE);
171                         int samplesize = AUD_MAX(AUD_SAMPLE_SIZE(m_specs), AUD_DEVICE_SAMPLE_SIZE(m_specs));
172
173                         if(m_codecCtx->frame_size <= 1)
174                                 m_input_size = 0;
175                         else
176                         {
177                                 m_input_buffer.resize(m_codecCtx->frame_size * samplesize);
178                                 m_input_size = m_codecCtx->frame_size;
179                         }
180
181                         try
182                         {
183                                 if(avio_open(&m_formatCtx->pb, filename.c_str(), AVIO_WRONLY))
184                                         AUD_THROW(AUD_ERROR_FILE, file_error);
185
186                                 avformat_write_header(m_formatCtx, NULL);
187                         }
188                         catch(AUD_Exception&)
189                         {
190                                 avcodec_close(m_codecCtx);
191                                 av_freep(&m_formatCtx->streams[0]->codec);
192                                 throw;
193                         }
194                 }
195                 catch(AUD_Exception&)
196                 {
197                         av_freep(&m_formatCtx->streams[0]);
198                         throw;
199                 }
200         }
201         catch(AUD_Exception&)
202         {
203                 av_free(m_formatCtx);
204                 throw;
205         }
206 }
207
208 AUD_FFMPEGWriter::~AUD_FFMPEGWriter()
209 {
210         // writte missing data
211         if(m_input_samples)
212         {
213                 sample_t* buf = m_input_buffer.getBuffer();
214                 memset(buf + m_specs.channels * m_input_samples, 0,
215                            (m_input_size - m_input_samples) * AUD_DEVICE_SAMPLE_SIZE(m_specs));
216
217                 encode(buf);
218         }
219
220         av_write_trailer(m_formatCtx);
221
222         avcodec_close(m_codecCtx);
223
224         av_freep(&m_formatCtx->streams[0]->codec);
225         av_freep(&m_formatCtx->streams[0]);
226
227         avio_close(m_formatCtx->pb);
228         av_free(m_formatCtx);
229 }
230
231 int AUD_FFMPEGWriter::getPosition() const
232 {
233         return m_position;
234 }
235
236 AUD_DeviceSpecs AUD_FFMPEGWriter::getSpecs() const
237 {
238         return m_specs;
239 }
240
241 void AUD_FFMPEGWriter::encode(sample_t* data)
242 {
243         sample_t* outbuf = m_output_buffer.getBuffer();
244
245         // convert first
246         if(m_input_size)
247                 m_convert(reinterpret_cast<data_t*>(data), reinterpret_cast<data_t*>(data), m_input_size * m_specs.channels);
248
249         AVPacket packet;
250         av_init_packet(&packet);
251         packet.size = avcodec_encode_audio(m_codecCtx, reinterpret_cast<uint8_t*>(outbuf), m_output_buffer.getSize(), reinterpret_cast<short*>(data));
252         if(m_codecCtx->coded_frame && m_codecCtx->coded_frame->pts != AV_NOPTS_VALUE)
253                 packet.pts = av_rescale_q(m_codecCtx->coded_frame->pts, m_codecCtx->time_base, m_stream->time_base);
254         packet.flags |= AV_PKT_FLAG_KEY;
255         packet.stream_index = m_stream->index;
256         packet.data = reinterpret_cast<uint8_t*>(outbuf);
257
258         if(av_interleaved_write_frame(m_formatCtx, &packet))
259                 AUD_THROW(AUD_ERROR_FFMPEG, write_error);
260 }
261
262 void AUD_FFMPEGWriter::write(unsigned int length, sample_t* buffer)
263 {
264         unsigned int samplesize = AUD_SAMPLE_SIZE(m_specs);
265
266         if(m_input_size)
267         {
268                 sample_t* inbuf = m_input_buffer.getBuffer();
269
270                 while(length)
271                 {
272                         unsigned int len = AUD_MIN(m_input_size - m_input_samples, length);
273
274                         memcpy(inbuf + m_input_samples * m_specs.channels, buffer, len * samplesize);
275
276                         buffer += len * m_specs.channels;
277                         m_input_samples += len;
278                         m_position += len;
279                         length -= len;
280
281                         if(m_input_samples == m_input_size)
282                         {
283                                 encode(inbuf);
284
285                                 m_input_samples = 0;
286                         }
287                 }
288         }
289         else // PCM data, can write directly!
290         {
291                 int samplesize = AUD_SAMPLE_SIZE(m_specs);
292                 if(m_output_buffer.getSize() != length * m_specs.channels * m_codecCtx->bits_per_coded_sample / 8)
293                         m_output_buffer.resize(length * m_specs.channels * m_codecCtx->bits_per_coded_sample / 8);
294                 m_input_buffer.assureSize(length * AUD_MAX(AUD_DEVICE_SAMPLE_SIZE(m_specs), samplesize));
295
296                 sample_t* buf = m_input_buffer.getBuffer();
297                 m_convert(reinterpret_cast<data_t*>(buf), reinterpret_cast<data_t*>(buffer), length * m_specs.channels);
298
299                 encode(buf);
300
301                 m_position += length;
302         }
303 }