859227a500638bcfd3a72386db56fd073d89c62a
[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 = AV_CODEC_ID_AAC;
72                 break;
73         case AUD_CODEC_AC3:
74                 m_outputFmt->audio_codec = AV_CODEC_ID_AC3;
75                 break;
76         case AUD_CODEC_FLAC:
77                 m_outputFmt->audio_codec = AV_CODEC_ID_FLAC;
78                 break;
79         case AUD_CODEC_MP2:
80                 m_outputFmt->audio_codec = AV_CODEC_ID_MP2;
81                 break;
82         case AUD_CODEC_MP3:
83                 m_outputFmt->audio_codec = AV_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 = AV_CODEC_ID_PCM_U8;
90                         break;
91                 case AUD_FORMAT_S16:
92                         m_outputFmt->audio_codec = AV_CODEC_ID_PCM_S16LE;
93                         break;
94                 case AUD_FORMAT_S24:
95                         m_outputFmt->audio_codec = AV_CODEC_ID_PCM_S24LE;
96                         break;
97                 case AUD_FORMAT_S32:
98                         m_outputFmt->audio_codec = AV_CODEC_ID_PCM_S32LE;
99                         break;
100                 case AUD_FORMAT_FLOAT32:
101                         m_outputFmt->audio_codec = AV_CODEC_ID_PCM_F32LE;
102                         break;
103                 case AUD_FORMAT_FLOAT64:
104                         m_outputFmt->audio_codec = AV_CODEC_ID_PCM_F64LE;
105                         break;
106                 default:
107                         m_outputFmt->audio_codec = AV_CODEC_ID_NONE;
108                         break;
109                 }
110                 break;
111         case AUD_CODEC_VORBIS:
112                 m_outputFmt->audio_codec = AV_CODEC_ID_VORBIS;
113                 break;
114         default:
115                 m_outputFmt->audio_codec = AV_CODEC_ID_NONE;
116                 break;
117         }
118
119         try
120         {
121                 if(m_outputFmt->audio_codec == AV_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 #ifdef FFMPEG_HAVE_ENCODE_AUDIO2
187                         m_frame = av_frame_alloc();
188                         if (!m_frame)
189                                 AUD_THROW(AUD_ERROR_FFMPEG, codec_error);
190                         avcodec_get_frame_defaults(m_frame);
191                         m_frame->linesize[0]    = m_input_size * samplesize;
192                         m_frame->format         = m_codecCtx->sample_fmt;
193                         m_frame->nb_samples     = m_codecCtx->frame_size;
194 #  ifdef FFMPEG_HAVE_AVFRAME_SAMPLE_RATE
195                         m_frame->sample_rate    = m_codecCtx->sample_rate;
196 #  endif
197 #  ifdef FFMPEG_HAVE_FRAME_CHANNEL_LAYOUT
198                         m_frame->channel_layout = m_codecCtx->channel_layout;
199 #  endif
200                         m_audio_sample_size = av_get_bytes_per_sample(m_codecCtx->sample_fmt);
201                         m_frame_pts = 0;
202 #endif
203
204                         try
205                         {
206                                 if(avio_open(&m_formatCtx->pb, filename.c_str(), AVIO_FLAG_WRITE))
207                                         AUD_THROW(AUD_ERROR_FILE, file_error);
208
209                                 avformat_write_header(m_formatCtx, NULL);
210                         }
211                         catch(AUD_Exception&)
212                         {
213                                 avcodec_close(m_codecCtx);
214                                 av_freep(&m_formatCtx->streams[0]->codec);
215                                 throw;
216                         }
217                 }
218                 catch(AUD_Exception&)
219                 {
220                         av_freep(&m_formatCtx->streams[0]);
221                         throw;
222                 }
223         }
224         catch(AUD_Exception&)
225         {
226                 av_free(m_formatCtx);
227                 throw;
228         }
229 }
230
231 AUD_FFMPEGWriter::~AUD_FFMPEGWriter()
232 {
233         // writte missing data
234         if(m_input_samples)
235         {
236                 sample_t* buf = m_input_buffer.getBuffer();
237                 memset(buf + m_specs.channels * m_input_samples, 0,
238                            (m_input_size - m_input_samples) * AUD_DEVICE_SAMPLE_SIZE(m_specs));
239
240                 encode(buf);
241         }
242
243         av_write_trailer(m_formatCtx);
244
245         avcodec_close(m_codecCtx);
246
247         av_freep(&m_formatCtx->streams[0]->codec);
248         av_freep(&m_formatCtx->streams[0]);
249
250 #ifdef FFMPEG_HAVE_ENCODE_AUDIO2
251         av_frame_free(&m_frame);
252 #endif
253
254         avio_close(m_formatCtx->pb);
255         av_free(m_formatCtx);
256 }
257
258 int AUD_FFMPEGWriter::getPosition() const
259 {
260         return m_position;
261 }
262
263 AUD_DeviceSpecs AUD_FFMPEGWriter::getSpecs() const
264 {
265         return m_specs;
266 }
267
268 void AUD_FFMPEGWriter::encode(sample_t* data)
269 {
270         // convert first
271         if(m_input_size)
272                 m_convert(reinterpret_cast<data_t*>(data), reinterpret_cast<data_t*>(data), m_input_size * m_specs.channels);
273
274         AVPacket packet = { 0 };
275         av_init_packet(&packet);
276
277 #ifdef FFMPEG_HAVE_ENCODE_AUDIO2
278         int got_output, ret;
279         m_frame->pts = m_frame_pts / av_q2d(m_codecCtx->time_base);
280         m_frame_pts++;
281 #ifdef FFMPEG_HAVE_FRAME_CHANNEL_LAYOUT
282         m_frame->channel_layout = m_codecCtx->channel_layout;
283 #endif
284
285         avcodec_fill_audio_frame(m_frame, m_codecCtx->channels, m_codecCtx->sample_fmt, reinterpret_cast<uint8_t*>(data),
286                                  m_frame->nb_samples * av_get_bytes_per_sample(m_codecCtx->sample_fmt) * m_codecCtx->channels, 1);
287
288         ret = avcodec_encode_audio2(m_codecCtx, &packet, m_frame, &got_output);
289         if(ret < 0)
290                 AUD_THROW(AUD_ERROR_FFMPEG, codec_error);
291
292         if(!got_output)
293                 return;
294 #else
295         sample_t* outbuf = m_output_buffer.getBuffer();
296
297         packet.size = avcodec_encode_audio(m_codecCtx, reinterpret_cast<uint8_t*>(outbuf), m_output_buffer.getSize(), reinterpret_cast<short*>(data));
298         if(m_codecCtx->coded_frame && m_codecCtx->coded_frame->pts != AV_NOPTS_VALUE)
299                 packet.pts = av_rescale_q(m_codecCtx->coded_frame->pts, m_codecCtx->time_base, m_stream->time_base);
300         packet.flags |= AV_PKT_FLAG_KEY;
301         packet.data = reinterpret_cast<uint8_t*>(outbuf);
302 #endif
303
304         if(packet.pts != AV_NOPTS_VALUE)
305                 packet.pts = av_rescale_q(packet.pts, m_codecCtx->time_base, m_stream->time_base);
306         if(packet.dts != AV_NOPTS_VALUE)
307                 packet.dts = av_rescale_q(packet.dts, m_codecCtx->time_base, m_stream->time_base);
308         if(packet.duration > 0)
309                 packet.duration = av_rescale_q(packet.duration, m_codecCtx->time_base, m_stream->time_base);
310
311         packet.stream_index = m_stream->index;
312
313         packet.flags |= AV_PKT_FLAG_KEY;
314
315         if(av_interleaved_write_frame(m_formatCtx, &packet)) {
316                 av_free_packet(&packet);
317                 AUD_THROW(AUD_ERROR_FFMPEG, write_error);
318         }
319
320         av_free_packet(&packet);
321 }
322
323 void AUD_FFMPEGWriter::write(unsigned int length, sample_t* buffer)
324 {
325         unsigned int samplesize = AUD_SAMPLE_SIZE(m_specs);
326
327         if(m_input_size)
328         {
329                 sample_t* inbuf = m_input_buffer.getBuffer();
330
331                 while(length)
332                 {
333                         unsigned int len = AUD_MIN(m_input_size - m_input_samples, length);
334
335                         memcpy(inbuf + m_input_samples * m_specs.channels, buffer, len * samplesize);
336
337                         buffer += len * m_specs.channels;
338                         m_input_samples += len;
339                         m_position += len;
340                         length -= len;
341
342                         if(m_input_samples == m_input_size)
343                         {
344                                 encode(inbuf);
345
346                                 m_input_samples = 0;
347                         }
348                 }
349         }
350         else // PCM data, can write directly!
351         {
352                 int samplesize = AUD_SAMPLE_SIZE(m_specs);
353                 if(m_output_buffer.getSize() != length * m_specs.channels * m_codecCtx->bits_per_coded_sample / 8)
354                         m_output_buffer.resize(length * m_specs.channels * m_codecCtx->bits_per_coded_sample / 8);
355                 m_input_buffer.assureSize(length * AUD_MAX(AUD_DEVICE_SAMPLE_SIZE(m_specs), samplesize));
356
357                 sample_t* buf = m_input_buffer.getBuffer();
358                 m_convert(reinterpret_cast<data_t*>(buf), reinterpret_cast<data_t*>(buffer), length * m_specs.channels);
359
360                 encode(buf);
361
362                 m_position += length;
363         }
364 }