summaryrefslogtreecommitdiff
path: root/src/player/VideoWriterThread.cpp
blob: 5ebb654708803d79d848f29173e1752f47eda256 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//
//  libavg - Media Playback Engine. 
//  Copyright (C) 2003-2014 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "VideoWriterThread.h"

#include "../base/ProfilingZoneID.h"
#include "../base/ScopeTimer.h"
#include "../base/StringHelper.h"

#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55, 18, 102)
    typedef CodecID AVCodecID;
#endif

using namespace std;

namespace avg {

const unsigned int VIDEO_BUFFER_SIZE = 400000;
const AVPixelFormat STREAM_PIXEL_FORMAT = ::PIX_FMT_YUVJ420P;

VideoWriterThread::VideoWriterThread(CQueue& cmdQueue, const string& sFilename,
        IntPoint size, int frameRate, int qMin, int qMax)
    : WorkerThread<VideoWriterThread>(sFilename, cmdQueue, Logger::category::PROFILE),
      m_sFilename(sFilename),
      m_Size(size),
      m_FrameRate(frameRate),
      m_QMin(qMin),
      m_QMax(qMax),
      m_pOutputFormatContext()
{
}

VideoWriterThread::~VideoWriterThread()
{
}

static ProfilingZoneID ProfilingZoneEncodeFrame("Encode frame", true);

void VideoWriterThread::encodeYUVFrame(BitmapPtr pBmp)
{
    ScopeTimer timer(ProfilingZoneEncodeFrame);
    convertYUVImage(pBmp);
    writeFrame(m_pConvertedFrame);
    ThreadProfiler::get()->reset();
}

void VideoWriterThread::encodeFrame(BitmapPtr pBmp)
{
    ScopeTimer timer(ProfilingZoneEncodeFrame);
    convertRGBImage(pBmp);
    writeFrame(m_pConvertedFrame);
    ThreadProfiler::get()->reset();
}

void VideoWriterThread::close()
{
    if (m_pOutputFormatContext) {
        av_write_trailer(m_pOutputFormatContext);
        avcodec_close(m_pVideoStream->codec);

        for (unsigned int i=0; i<m_pOutputFormatContext->nb_streams; i++) {
            AVStream* pStream = m_pOutputFormatContext->streams[i];

            pStream->discard = AVDISCARD_ALL;
            av_freep(&m_pOutputFormatContext->streams[i]->codec);
            av_freep(&m_pOutputFormatContext->streams[i]);
        }

        if (!(m_pOutputFormat->flags & AVFMT_NOFILE)) {
#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(53, 8, 0)
            avio_close(m_pOutputFormatContext->pb);
#else            
            url_fclose(m_pOutputFormatContext->pb);
#endif
        }

        av_free(m_pOutputFormatContext);
        av_free(m_pVideoBuffer);
        av_free(m_pConvertedFrame);
        av_free(m_pPictureBuffer);
        sws_freeContext(m_pFrameConversionContext);
        m_pOutputFormatContext = 0;
    }
}

bool VideoWriterThread::init()
{
    open();
    return true;
}

bool VideoWriterThread::work()
{
    waitForCommand();
    return true;
}

void VideoWriterThread::deinit()
{
    close();
}

void VideoWriterThread::open()
{
    av_register_all(); // TODO: make sure this is only done once. 
//    av_log_set_level(AV_LOG_DEBUG);
#if LIBAVFORMAT_VERSION_MAJOR > 52
    m_pOutputFormat = av_guess_format(0, m_sFilename.c_str(), 0);
#else
    m_pOutputFormat = guess_format(0, m_sFilename.c_str(), 0);
#endif
    m_pOutputFormat->video_codec = AV_CODEC_ID_MJPEG;

#if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(52, 24, 0)
    m_pOutputFormatContext = avformat_alloc_context();
#else
    m_pOutputFormatContext = av_alloc_format_context();
#endif
    m_pOutputFormatContext->oformat = m_pOutputFormat;

    strncpy(m_pOutputFormatContext->filename, m_sFilename.c_str(),
            sizeof(m_pOutputFormatContext->filename));

    if (m_pOutputFormat->video_codec != AV_CODEC_ID_NONE) {
        setupVideoStream();
    }
#if LIBAVFORMAT_VERSION_MAJOR < 52
    av_set_parameters(m_pOutputFormatContext, NULL);
#endif

    float muxMaxDelay = 0.7;
    m_pOutputFormatContext->max_delay = int(muxMaxDelay * AV_TIME_BASE);

//    av_dump_format(m_pOutputFormatContext, 0, m_sFilename.c_str(), 1);

    openVideoCodec();

    m_pVideoBuffer = NULL;
    if (!(m_pOutputFormatContext->oformat->flags & AVFMT_RAWPICTURE)) {
        m_pVideoBuffer = (unsigned char*)(av_malloc(VIDEO_BUFFER_SIZE));
    }

    if (!(m_pOutputFormat->flags & AVFMT_NOFILE)) {
#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(53, 8, 0)
        int retVal = avio_open(&m_pOutputFormatContext->pb, m_sFilename.c_str(),
                URL_WRONLY);
#else
        int retVal = url_fopen(&m_pOutputFormatContext->pb, m_sFilename.c_str(),
                URL_WRONLY);
#endif
        if (retVal < 0) {
            throw Exception(AVG_ERR_VIDEO_INIT_FAILED, 
                    string("Could not open output file: '") + m_sFilename + "'");
        }
    }

    m_pFrameConversionContext = sws_getContext(m_Size.x, m_Size.y, 
            ::PIX_FMT_RGB32, m_Size.x, m_Size.y, STREAM_PIXEL_FORMAT, 
            SWS_BILINEAR, NULL, NULL, NULL);

    m_pConvertedFrame = createFrame(STREAM_PIXEL_FORMAT, m_Size);

#if LIBAVFORMAT_VERSION_MAJOR > 52
    avformat_write_header(m_pOutputFormatContext, 0);
#else
    av_write_header(m_pOutputFormatContext);
#endif
}

void VideoWriterThread::setupVideoStream()
{
#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(53, 21, 0)
    m_pVideoStream = avformat_new_stream(m_pOutputFormatContext, 0);
#else
    m_pVideoStream = av_new_stream(m_pOutputFormatContext, 0);
#endif

    AVCodecContext* pCodecContext = m_pVideoStream->codec;
    pCodecContext->codec_id = static_cast<AVCodecID>(m_pOutputFormat->video_codec);
    pCodecContext->codec_type = AVMEDIA_TYPE_VIDEO;

    /* put sample parameters */
    pCodecContext->bit_rate = 400000;
    /* resolution must be a multiple of two */
    pCodecContext->width = m_Size.x;
    pCodecContext->height = m_Size.y;
    /* time base: this is the fundamental unit of time (in seconds) in terms
       of which frame timestamps are represented. for fixed-fps content,
       timebase should be 1/framerate and timestamp increments should be
       identically 1. */
    pCodecContext->time_base.den = m_FrameRate;
    pCodecContext->time_base.num = 1;
//    pCodecContext->gop_size = 12; /* emit one intra frame every twelve frames at most */
    pCodecContext->pix_fmt = STREAM_PIXEL_FORMAT;
    // Quality of quantization
    pCodecContext->qmin = m_QMin;
    pCodecContext->qmax = m_QMax;
    // some formats want stream headers to be separate
    if (m_pOutputFormatContext->oformat->flags & AVFMT_GLOBALHEADER) {
        pCodecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }
    m_FramesWritten = 0;
}

void VideoWriterThread::openVideoCodec()
{
    AVCodec* videoCodec = avcodec_find_encoder(m_pVideoStream->codec->codec_id);
    AVG_ASSERT(videoCodec);

    int rc = avcodec_open2(m_pVideoStream->codec, videoCodec, 0);
    AVG_ASSERT(rc == 0);
}

AVFrame* VideoWriterThread::createFrame(AVPixelFormat pixelFormat, IntPoint size)
{
    AVFrame* pPicture;

    pPicture = avcodec_alloc_frame();

    int memNeeded = avpicture_get_size(pixelFormat, size.x, size.y);
    m_pPictureBuffer = static_cast<unsigned char*>(av_malloc(memNeeded));
    avpicture_fill(reinterpret_cast<AVPicture*>(pPicture),
            m_pPictureBuffer, pixelFormat, size.x, size.y);

    return pPicture;
}

static ProfilingZoneID ProfilingZoneConvertImage(" Convert image", true);

void VideoWriterThread::convertRGBImage(BitmapPtr pSrcBmp)
{
    ScopeTimer timer(ProfilingZoneConvertImage);
    unsigned char* rgbData[3] = {pSrcBmp->getPixels(), NULL, NULL};
    int rgbStride[3] = {pSrcBmp->getLineLen(), 0, 0};

    sws_scale(m_pFrameConversionContext, rgbData, rgbStride,
              0, m_Size.y, m_pConvertedFrame->data, m_pConvertedFrame->linesize);
}

void VideoWriterThread::convertYUVImage(BitmapPtr pSrcBmp)
{
    ScopeTimer timer(ProfilingZoneConvertImage);
    IntPoint size = pSrcBmp->getSize();
    BitmapPtr pYBmp(new Bitmap(size, I8, m_pConvertedFrame->data[0], 
            m_pConvertedFrame->linesize[0], false));
    BitmapPtr pUBmp(new Bitmap(size/2, I8, m_pConvertedFrame->data[1], 
            m_pConvertedFrame->linesize[1], false));
    BitmapPtr pVBmp(new Bitmap(size/2, I8, m_pConvertedFrame->data[2], 
            m_pConvertedFrame->linesize[2], false));
    for (int y=0; y<size.y/2; ++y) {
        int srcStride = pSrcBmp->getStride();
        const unsigned char * pSrc = pSrcBmp->getPixels() + y*srcStride*2;
        int yStride = pYBmp->getStride();
        unsigned char * pYDest = pYBmp->getPixels() + y*yStride*2;
        unsigned char * pUDest = pUBmp->getPixels() + y*pUBmp->getStride();
        unsigned char * pVDest = pVBmp->getPixels() + y*pVBmp->getStride();
        for (int x=0; x<size.x/2; ++x) {
            *pYDest = *pSrc;
            *(pYDest+1) = *(pSrc+4);
            *(pYDest+yStride) = *(pSrc+srcStride);
            *(pYDest+yStride+1) = *(pSrc+srcStride+4);

            *pUDest = ((int)*(pSrc+1) + *(pSrc+5) + 
                       *(pSrc+srcStride+1) + *(pSrc+srcStride+5) + 2)/4; 

            *pVDest = ((int)*(pSrc+2) + *(pSrc+6) + 
                       *(pSrc+srcStride+2) + *(pSrc+srcStride+6) + 2)/4; 

            pSrc += 8;
            pYDest += 2;
            pUDest += 1;
            pVDest += 1;
        }
    }
//    pSrcBmp->save("src"+toString(m_FramesWritten)+".png");
//    pUBmp->save("foo"+toString(m_FramesWritten)+".png");
}

static ProfilingZoneID ProfilingZoneWriteFrame(" Write frame", true);

void VideoWriterThread::writeFrame(AVFrame* pFrame)
{
    ScopeTimer timer(ProfilingZoneWriteFrame);
    m_FramesWritten++;
    AVCodecContext* pCodecContext = m_pVideoStream->codec;
    AVPacket packet = { 0 };
    int ret, out_size = 0;

    #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(54, 0, 0)
        int got_output = 0;
        ret = avcodec_encode_video2(pCodecContext, &packet, pFrame, &got_output);
        if(ret < 0) {
            av_free_packet(&packet);
            AVG_ASSERT(false);
        }
        out_size = packet.size;
    #else
        out_size = avcodec_encode_video(pCodecContext, m_pVideoBuffer,
                VIDEO_BUFFER_SIZE, pFrame);
        if(out_size > 0) {
            av_init_packet(&packet);

            if ((pCodecContext->coded_frame->pts) != (long long)AV_NOPTS_VALUE) {
                packet.pts = av_rescale_q(pCodecContext->coded_frame->pts,
                        pCodecContext->time_base, m_pVideoStream->time_base);
            }

            if (pCodecContext->coded_frame->key_frame) {
                packet.flags |= AV_PKT_FLAG_KEY;
            }
            packet.stream_index = m_pVideoStream->index;
            packet.data = m_pVideoBuffer;
            packet.size = out_size;
        }
    #endif

    ///* if zero size, it means the image was buffered */
    if (out_size > 0) {
        /* write the compressed frame in the media file */
        ret = av_interleaved_write_frame(m_pOutputFormatContext, &packet);
        av_free_packet(&packet);
        AVG_ASSERT(ret == 0);
    }

}

}