55040e4db8e3b47c62b8ee3459b04896e892de74
[blender.git] / intern / audaspace / ffmpeg / AUD_FFMPEGWriter.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * Copyright 2009-2011 Jörg Hermann Müller
5  *
6  * This file is part of AudaSpace.
7  *
8  * Audaspace is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * AudaSpace is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Audaspace; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file audaspace/ffmpeg/AUD_FFMPEGWriter.cpp
26  *  \ingroup audffmpeg
27  */
28
29
30 // needed for INT64_C
31 #ifndef __STDC_CONSTANT_MACROS
32 #define __STDC_CONSTANT_MACROS
33 #endif
34
35 #include "AUD_FFMPEGWriter.h"
36
37 extern "C" {
38 #include <libavcodec/avcodec.h>
39 #include <libavformat/avformat.h>
40 #include <libavformat/avio.h>
41 #include "ffmpeg_compat.h"
42 }
43
44 static const char* context_error = "AUD_FFMPEGWriter: Couldn't allocate context.";
45 static const char* codec_error = "AUD_FFMPEGWriter: Invalid codec or codec not found.";
46 static const char* stream_error = "AUD_FFMPEGWriter: Couldn't allocate stream.";
47 static const char* format_error = "AUD_FFMPEGWriter: Unsupported sample format.";
48 static const char* file_error = "AUD_FFMPEGWriter: File couldn't be written.";
49 static const char* write_error = "AUD_FFMPEGWriter: Error writing packet.";
50
51 AUD_FFMPEGWriter::AUD_FFMPEGWriter(std::string filename, AUD_DeviceSpecs specs, AUD_Container format, AUD_Codec codec, unsigned int bitrate) :
52         m_position(0),
53         m_specs(specs),
54         m_input_samples(0)
55 {
56         static const char* formats[] = { NULL, "ac3", "flac", "matroska", "mp2", "mp3", "ogg", "wav" };
57
58         m_formatCtx = avformat_alloc_context();
59         if (!m_formatCtx) AUD_THROW(AUD_ERROR_FFMPEG, context_error);
60
61         strcpy(m_formatCtx->filename, filename.c_str());
62         m_outputFmt = m_formatCtx->oformat = av_guess_format(formats[format], filename.c_str(), NULL);
63         if (!m_outputFmt) {
64                 avformat_free_context(m_formatCtx);
65                 AUD_THROW(AUD_ERROR_FFMPEG, context_error);
66         }
67
68         switch(codec)
69         {
70         case AUD_CODEC_AAC:
71                 m_outputFmt->audio_codec = CODEC_ID_AAC;
72                 break;
73         case AUD_CODEC_AC3:
74                 m_outputFmt->audio_codec = CODEC_ID_AC3;
75                 break;
76         case AUD_CODEC_FLAC:
77                 m_outputFmt->audio_codec = CODEC_ID_FLAC;
78                 break;
79         case AUD_CODEC_MP2:
80                 m_outputFmt->audio_codec = CODEC_ID_MP2;
81                 break;
82         case AUD_CODEC_MP3:
83                 m_outputFmt->audio_codec = CODEC_ID_MP3;
84                 break;
85         case AUD_CODEC_PCM:
86                 switch(specs.format)
87                 {
88                 case AUD_FORMAT_U8:
89                         m_outputFmt->audio_codec = CODEC_ID_PCM_U8;
90                         break;
91                 case AUD_FORMAT_S16:
92                         m_outputFmt->audio_codec = CODEC_ID_PCM_S16LE;
93                         break;
94                 case AUD_FORMAT_S24:
95                         m_outputFmt->audio_codec = CODEC_ID_PCM_S24LE;
96                         break;
97                 case AUD_FORMAT_S32:
98                         m_outputFmt->audio_codec = CODEC_ID_PCM_S32LE;
99                         break;
100                 case AUD_FORMAT_FLOAT32:
101                         m_outputFmt->audio_codec = CODEC_ID_PCM_F32LE;
102                         break;
103                 case AUD_FORMAT_FLOAT64:
104                         m_outputFmt->audio_codec = CODEC_ID_PCM_F64LE;
105                         break;
106                 default:
107                         m_outputFmt->audio_codec = CODEC_ID_NONE;
108                         break;
109                 }
110                 break;
111         case AUD_CODEC_VORBIS:
112                 m_outputFmt->audio_codec = CODEC_ID_VORBIS;
113                 break;
114         default:
115                 m_outputFmt->audio_codec = CODEC_ID_NONE;
116                 break;
117         }
118
119         try
120         {
121                 if(m_outputFmt->audio_codec == CODEC_ID_NONE)
122                         AUD_THROW(AUD_ERROR_SPECS, codec_error);
123
124                 m_stream = avformat_new_stream(m_formatCtx, NULL);
125                 if(!m_stream)
126                         AUD_THROW(AUD_ERROR_FFMPEG, stream_error);
127
128                 m_codecCtx = m_stream->codec;
129                 m_codecCtx->codec_id = m_outputFmt->audio_codec;
130                 m_codecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
131                 m_codecCtx->bit_rate = bitrate;
132                 m_codecCtx->sample_rate = int(m_specs.rate);
133                 m_codecCtx->channels = m_specs.channels;
134                 m_codecCtx->time_base.num = 1;
135                 m_codecCtx->time_base.den = m_codecCtx->sample_rate;
136
137                 switch(m_specs.format)
138                 {
139                 case AUD_FORMAT_U8:
140                         m_convert = AUD_convert_float_u8;
141                         m_codecCtx->sample_fmt = AV_SAMPLE_FMT_U8;
142                         break;
143                 case AUD_FORMAT_S16:
144                         m_convert = AUD_convert_float_s16;
145                         m_codecCtx->sample_fmt = AV_SAMPLE_FMT_S16;
146                         break;
147                 case AUD_FORMAT_S32:
148                         m_convert = AUD_convert_float_s32;
149                         m_codecCtx->sample_fmt = AV_SAMPLE_FMT_S32;
150                         break;
151                 case AUD_FORMAT_FLOAT32:
152                         m_convert = AUD_convert_copy<float>;
153                         m_codecCtx->sample_fmt = AV_SAMPLE_FMT_FLT;
154                         break;
155                 case AUD_FORMAT_FLOAT64:
156                         m_convert = AUD_convert_float_double;
157                         m_codecCtx->sample_fmt = AV_SAMPLE_FMT_DBL;
158                         break;
159                 default:
160                         AUD_THROW(AUD_ERROR_FFMPEG, format_error);
161                 }
162
163                 try
164                 {
165                         if(m_formatCtx->oformat->flags & AVFMT_GLOBALHEADER)
166                                 m_codecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
167
168                         AVCodec* codec = avcodec_find_encoder(m_codecCtx->codec_id);
169                         if(!codec)
170                                 AUD_THROW(AUD_ERROR_FFMPEG, codec_error);
171
172                         if(avcodec_open2(m_codecCtx, codec, NULL))
173                                 AUD_THROW(AUD_ERROR_FFMPEG, codec_error);
174
175                         m_output_buffer.resize(FF_MIN_BUFFER_SIZE);
176                         int samplesize = AUD_MAX(AUD_SAMPLE_SIZE(m_specs), AUD_DEVICE_SAMPLE_SIZE(m_specs));
177
178                         if(m_codecCtx->frame_size <= 1)
179                                 m_input_size = 0;
180                         else
181                         {
182                                 m_input_buffer.resize(m_codecCtx->frame_size * samplesize);
183                                 m_input_size = m_codecCtx->frame_size;
184                         }
185
186                         try
187                         {
188                                 if(avio_open(&m_formatCtx->pb, filename.c_str(), AVIO_FLAG_WRITE))
189                                         AUD_THROW(AUD_ERROR_FILE, file_error);
190
191                                 avformat_write_header(m_formatCtx, NULL);
192                         }
193                         catch(AUD_Exception&)
194                         {
195                                 avcodec_close(m_codecCtx);
196                                 av_freep(&m_formatCtx->streams[0]->codec);
197                                 throw;
198                         }
199                 }
200                 catch(AUD_Exception&)
201                 {
202                         av_freep(&m_formatCtx->streams[0]);
203                         throw;
204                 }
205         }
206         catch(AUD_Exception&)
207         {
208                 av_free(m_formatCtx);
209                 throw;
210         }
211 }
212
213 AUD_FFMPEGWriter::~AUD_FFMPEGWriter()
214 {
215         // writte missing data
216         if(m_input_samples)
217         {
218                 sample_t* buf = m_input_buffer.getBuffer();
219                 memset(buf + m_specs.channels * m_input_samples, 0,
220                            (m_input_size - m_input_samples) * AUD_DEVICE_SAMPLE_SIZE(m_specs));
221
222                 encode(buf);
223         }
224
225         av_write_trailer(m_formatCtx);
226
227         avcodec_close(m_codecCtx);
228
229         av_freep(&m_formatCtx->streams[0]->codec);
230         av_freep(&m_formatCtx->streams[0]);
231
232         avio_close(m_formatCtx->pb);
233         av_free(m_formatCtx);
234 }
235
236 int AUD_FFMPEGWriter::getPosition() const
237 {
238         return m_position;
239 }
240
241 AUD_DeviceSpecs AUD_FFMPEGWriter::getSpecs() const
242 {
243         return m_specs;
244 }
245
246 void AUD_FFMPEGWriter::encode(sample_t* data)
247 {
248         sample_t* outbuf = m_output_buffer.getBuffer();
249
250         // convert first
251         if(m_input_size)
252                 m_convert(reinterpret_cast<data_t*>(data), reinterpret_cast<data_t*>(data), m_input_size * m_specs.channels);
253
254         AVPacket packet;
255         av_init_packet(&packet);
256         packet.size = avcodec_encode_audio(m_codecCtx, reinterpret_cast<uint8_t*>(outbuf), m_output_buffer.getSize(), reinterpret_cast<short*>(data));
257         if(m_codecCtx->coded_frame && m_codecCtx->coded_frame->pts != AV_NOPTS_VALUE)
258                 packet.pts = av_rescale_q(m_codecCtx->coded_frame->pts, m_codecCtx->time_base, m_stream->time_base);
259         packet.flags |= AV_PKT_FLAG_KEY;
260         packet.stream_index = m_stream->index;
261         packet.data = reinterpret_cast<uint8_t*>(outbuf);
262
263         if(av_interleaved_write_frame(m_formatCtx, &packet))
264                 AUD_THROW(AUD_ERROR_FFMPEG, write_error);
265 }
266
267 void AUD_FFMPEGWriter::write(unsigned int length, sample_t* buffer)
268 {
269         unsigned int samplesize = AUD_SAMPLE_SIZE(m_specs);
270
271         if(m_input_size)
272         {
273                 sample_t* inbuf = m_input_buffer.getBuffer();
274
275                 while(length)
276                 {
277                         unsigned int len = AUD_MIN(m_input_size - m_input_samples, length);
278
279                         memcpy(inbuf + m_input_samples * m_specs.channels, buffer, len * samplesize);
280
281                         buffer += len * m_specs.channels;
282                         m_input_samples += len;
283                         m_position += len;
284                         length -= len;
285
286                         if(m_input_samples == m_input_size)
287                         {
288                                 encode(inbuf);
289
290                                 m_input_samples = 0;
291                         }
292                 }
293         }
294         else // PCM data, can write directly!
295         {
296                 int samplesize = AUD_SAMPLE_SIZE(m_specs);
297                 if(m_output_buffer.getSize() != length * m_specs.channels * m_codecCtx->bits_per_coded_sample / 8)
298                         m_output_buffer.resize(length * m_specs.channels * m_codecCtx->bits_per_coded_sample / 8);
299                 m_input_buffer.assureSize(length * AUD_MAX(AUD_DEVICE_SAMPLE_SIZE(m_specs), samplesize));
300
301                 sample_t* buf = m_input_buffer.getBuffer();
302                 m_convert(reinterpret_cast<data_t*>(buf), reinterpret_cast<data_t*>(buffer), length * m_specs.channels);
303
304                 encode(buf);
305
306                 m_position += length;
307         }
308 }