houxiao
2016-12-28 4ef430e946e717d72e923c4708a9120f94d55dbd
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//
//  FFmpegH264Encoder.cpp
//  FFmpegRTSPServer
//
//  Created by Mina Saad on 9/22/15.
//  Copyright (c) 2015 Mina Saad. All rights reserved.
//
 
#include "FFmpegH264Encoder.h"
 
namespace MESAI
{
    FFmpegH264Encoder::FFmpegH264Encoder()
    {
        pthread_mutex_init(&inqueue_mutex,NULL);
        pthread_mutex_init(&outqueue_mutex,NULL);
 
    }
    
    FFmpegH264Encoder::~FFmpegH264Encoder()
    {
        pthread_mutex_init(&inqueue_mutex,NULL);
        pthread_mutex_init(&outqueue_mutex,NULL);
 
    }
 
    void FFmpegH264Encoder::setCallbackFunctionFrameIsReady(std::function<void()> func)
    {
        onFrame = func;
    }
 
 
    void FFmpegH264Encoder::SendNewFrame(uint8_t * RGBFrame) {
        pthread_mutex_lock(&inqueue_mutex);
        if(inqueue.size()<30)
        {
            inqueue.push(RGBFrame);
        }
        pthread_mutex_unlock(&inqueue_mutex);
    }
 
    void FFmpegH264Encoder::run()
    {
        while(true)
        {
            if(!inqueue.empty())
            {
                uint8_t * frame;
                pthread_mutex_lock(&inqueue_mutex);
                frame = inqueue.front();
                inqueue.pop();
                pthread_mutex_unlock(&inqueue_mutex);
                if(frame != NULL)
                {
                    WriteFrameRGB(frame);
                }
            }
        }
    }
 
    bool FFmpegH264Encoder::SetupCodec(const char *filename, int codec_id)
    {
        int ret;
        m_sws_flags = SWS_BICUBIC;
        m_frame_count=0;
        
        avcodec_register_all();
        av_register_all();
        
        if (strlen(filename) == 0)
            avformat_alloc_output_context2(&m_oc, NULL, "h264", filename);
        else 
            avformat_alloc_output_context2(&m_oc, NULL, NULL, filename);
        
        if (!m_oc) {
            avformat_alloc_output_context2(&m_oc, NULL, "avi", filename);
        }
 
        if (!m_oc) {
            return false;
        }
 
        m_fmt = m_oc->oformat;
        m_video_st = NULL;
        m_fmt->video_codec = (AVCodecID)codec_id;
        m_fmt->audio_codec = AV_CODEC_ID_NONE;
 
        AVStream *st;
 
        m_video_codec = avcodec_find_encoder(m_fmt->video_codec);
        if (!(m_video_codec)) {
                return false;
        }
 
        st = avformat_new_stream(m_oc, m_video_codec);
 
        if (!st) {
                return false;
        }
 
        st->id = m_oc->nb_streams-1;
 
        m_c = st->codec;
        
        m_c->codec_id = m_fmt->video_codec;
        m_c->bit_rate = m_AVIMOV_BPS;            //Bits Per Second 
        m_c->width    = m_AVIMOV_WIDTH;            //Note Resolution must be a multiple of 2!!
        m_c->height   = m_AVIMOV_HEIGHT;        //Note Resolution must be a multiple of 2!!
        m_c->time_base.den = m_AVIMOV_FPS;        //Frames per second
        m_c->time_base.num = 1;
        m_c->gop_size      = m_AVIMOV_GOB;        // Intra frames per x P frames
        m_c->pix_fmt       = AV_PIX_FMT_YUV420P;//Do not change this, H264 needs YUV format not RGB
    
 
        if (m_oc->oformat->flags & AVFMT_GLOBALHEADER)
            m_c->flags |= CODEC_FLAG_GLOBAL_HEADER;
 
        m_video_st=st;
        
 
        AVCodecContext *c = m_video_st->codec;
 
        ret = avcodec_open2(c, m_video_codec, NULL);
        if (ret < 0) {
            return false;
        }
 
        //ret = avpicture_alloc(&m_dst_picture, c->pix_fmt, c->width, c->height);
        m_dst_picture = av_frame_alloc();
        m_dst_picture->format = c->pix_fmt;
        m_dst_picture->data[0] = NULL;
        m_dst_picture->linesize[0] = -1;
        m_dst_picture->pts = 0;
        m_dst_picture->width = m_c->width;
        m_dst_picture->height = m_c->height;
 
        ret = av_image_alloc(m_dst_picture->data, m_dst_picture->linesize, c->width, c->height, (AVPixelFormat)m_dst_picture->format, 32);
        if (ret < 0) {
            return false;
        }
 
        //ret = avpicture_alloc(&m_src_picture, AV_PIX_FMT_BGR24, c->width, c->height);
        m_src_picture = av_frame_alloc();
        m_src_picture->format = c->pix_fmt;
        ret = av_image_alloc(m_src_picture->data, m_src_picture->linesize, c->width, c->height, AV_PIX_FMT_BGR24, 24);
 
        if (ret < 0) {
            return false;
        }
 
        bufferSize = ret;
        
        av_dump_format(m_oc, 0, filename, 1);
 
        if (!(m_fmt->flags & AVFMT_NOFILE)) {
            ret = avio_open(&m_oc->pb, filename, AVIO_FLAG_WRITE);
            if (ret < 0) {
                return false;
            }
        }
        
        ret = avformat_write_header(m_oc, NULL);
        
        if (ret < 0) {
            return false;
        }
 
        sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_BGR24,
                                 c->width, c->height, AV_PIX_FMT_YUV420P,
                                 SWS_BICUBIC, NULL, NULL, NULL);
        if (!sws_ctx) {
            return false;
        }
        
        return true;
    }
 
    bool FFmpegH264Encoder::WriteFrameRGB(uint8_t * RGBFrame )
    {
        memcpy(m_src_picture->data[0], RGBFrame, bufferSize);
 
        sws_scale(sws_ctx,
                    m_src_picture->data, m_src_picture->linesize,
                    0, m_c->height, m_dst_picture->data, m_dst_picture->linesize);
        
 
        AVPacket pkt = { 0 };
        int got_packet;
        av_init_packet(&pkt);
 
        int ret = 0;
 
        ret = avcodec_encode_video2(m_c, &pkt, m_dst_picture, &got_packet);
        
        if (ret < 0) {
            return false;
        }
 
        if (!ret && got_packet && pkt.size) 
        {
            pkt.stream_index = m_video_st->index;
            FrameStructure * frame = new FrameStructure();
            frame->dataPointer = new uint8_t[pkt.size];
            frame->dataSize = pkt.size-4;
            frame->frameID = m_frame_count;
 
            memcpy(frame->dataPointer,pkt.data+4,pkt.size-4);
 
            pthread_mutex_lock(&outqueue_mutex);
 
            if(outqueue.size()<30)
            {
                outqueue.push(frame);
            }
            else
            {
                delete frame;
            }
 
            pthread_mutex_unlock(&outqueue_mutex);
 
        }
 
        av_free_packet(&pkt);
 
        m_frame_count++;
        m_dst_picture->pts += av_rescale_q(1, m_video_st->codec->time_base, m_video_st->time_base);
        
        if (onFrame != nullptr)
            onFrame();
        
        return true;
    }
    
    void copyAVFrame(AVFrame* dest, AVFrame* src)
    {
        int height = dest->height;
        int width = dest->width;
 
        memcpy(dest->data[0], src->data[0], height * width); // Y
        memcpy(dest->data[1], src->data[1], height * width / 4); // U
        memcpy(dest->data[2], src->data[2], height * width / 4); // V
    }
    
    bool FFmpegH264Encoder::WriteFrameYUV420(AVFrame * YUVFrame)
    {
        copyAVFrame(m_dst_picture, YUVFrame);
 
        AVPacket pkt = { 0 };
        int got_packet;
        av_init_packet(&pkt);
 
        int ret = 0;
 
        ret = avcodec_encode_video2(m_c, &pkt, m_dst_picture, &got_packet);
        
        if (ret < 0) {
            return false;
        }
 
        if (!ret && got_packet && pkt.size) 
        {
            pkt.stream_index = m_video_st->index;
            FrameStructure * frame = new FrameStructure();
            frame->dataPointer = new uint8_t[pkt.size];
            frame->dataSize = pkt.size-4;
            frame->frameID = m_frame_count;
 
            memcpy(frame->dataPointer,pkt.data+4,pkt.size-4);
 
            pthread_mutex_lock(&outqueue_mutex);
 
            if(outqueue.size()<30)
            {
                outqueue.push(frame);
            }
            else
            {
                delete frame;
            }
 
            pthread_mutex_unlock(&outqueue_mutex);
 
        }
 
        av_free_packet(&pkt);
 
        m_frame_count++;
        m_dst_picture->pts += av_rescale_q(1, m_video_st->codec->time_base, m_video_st->time_base);
        
        if (onFrame != nullptr)
            onFrame();
        
        return true;
    }
 
    bool FFmpegH264Encoder::SetupVideo(std::string filename, int Width, int Height, int FPS, int GOB, int BitPerSecond)
    {
        m_filename = filename;
        m_AVIMOV_WIDTH=Width;    //Movie width
        m_AVIMOV_HEIGHT=Height;    //Movie height
        m_AVIMOV_FPS=FPS;        //Movie frames per second
        m_AVIMOV_GOB=GOB;        //I frames per no of P frames, see note below!
        m_AVIMOV_BPS=BitPerSecond; //Bits per second, if this is too low then movie will become garbled
        
        return SetupCodec(m_filename.c_str(),AV_CODEC_ID_H264);    
    }
 
    void FFmpegH264Encoder::CloseCodec()
    {
 
        av_write_trailer(m_oc);
        avcodec_close(m_video_st->codec);
 
        av_freep(&(m_dst_picture->data[0]));
        av_frame_unref(m_dst_picture);
        av_free(m_dst_picture);
        av_freep(&(m_src_picture->data[0]));
        av_frame_unref(m_src_picture);
        av_free(m_src_picture);
 
        if (!(m_fmt->flags & AVFMT_NOFILE))
            avio_close(m_oc->pb);
 
        m_oc->pb = NULL;
 
        avformat_free_context(m_oc);
        sws_freeContext(sws_ctx);
 
    }
 
    void FFmpegH264Encoder::CloseVideo()
    {
        CloseCodec();    
    }
 
    char FFmpegH264Encoder::GetFrame(u_int8_t** FrameBuffer, unsigned int *FrameSize)
    {    
        if(!outqueue.empty())
        {    
            FrameStructure * frame;
            frame  = outqueue.front();
            *FrameBuffer = (uint8_t*)frame->dataPointer;
            *FrameSize = frame->dataSize;
            return 1;
        }
        else
        {
            *FrameBuffer = 0;
            *FrameSize = 0;
            return 0;
        }
    }
 
    char FFmpegH264Encoder::ReleaseFrame()
    {
        pthread_mutex_lock(&outqueue_mutex);
        if(!outqueue.empty())
        {
            FrameStructure * frame = outqueue.front();
            outqueue.pop();    
            delete frame;
        }
        pthread_mutex_unlock(&outqueue_mutex);
        return 1;
    }
}