video analysis2.0拆分,ffmpeg封装go接口库
zhangmeng
2019-09-29 e878e92811a2dbfb6b4d3f7b2c357435f56e28db
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#include "recorder.hpp"
#include "sole.hpp"
 
#include <thread>
#include <unistd.h>
#include <chrono>
 
extern "C"{
#include <libavcodec/avcodec.h>
}
 
#include "../ffmpeg/format/FormatIn.hpp"
#include "../ffmpeg/format/FormatOut.hpp"
#include "../ffmpeg/data/CodedData.hpp"
#include "../ffmpeg/log/log.hpp"
 
using namespace logif;
using namespace ffwrapper;
 
namespace cffmpeg_wrap{
    namespace buz{
        Recorder::Recorder(FormatIn *in, const std::string &id)
        :in_(in)
        ,out_(NULL)
        ,maxduration(30 * 25)
        ,minduration(10 * 25)
        ,end_frame(minduration)
        ,cur_frame(0)
        ,stop_recorder_(false)
        ,id_(id)
        ,id_frame_(-1)
        ,id_frame_in_file_(-1)
        ,file_path_("")
        ,func_rec_info_(nullptr)
        ,thrd_(nullptr)
        ,error_occured_(false)
        ,audio_(false)
        ,cur_frame_a(0)
        ,fp_(NULL)
        {
            if (in){
                maxduration = 30 * in->getFPS();
                minduration = 10 * in->getFPS();
            }
        }
 
        Recorder::~Recorder(){
            
            try
            {
                if (thrd_){
                    if (!stop_recorder_.load()){
                        stop_recorder_.store(true);
                        cv_.notify_one();
                    }
 
                    thrd_->join();
                    // logIt("REC THREAD JOINED, QUIT!!!, %s", id_.c_str());
                }
            }
            catch(const std::exception& e)
            {
                logIt("RECODER DESTRUCTOR EXCEPTION: ", e.what());
            }
 
            if (fp_) {
                fclose(fp_);
                fp_ = NULL;
            }
            
        }
 
        int Recorder::init_write_h264(const bool audio){
            if (out_) {
                delete out_;
            }
 
            out_ = new FormatOut(in_->getFPS(), "mp4");
            
            int pid = getpid();
            file_path_ = dir_ + "/" + sole::uuid4().base62() + "-" + std::to_string(pid) + ".mp4";
 
            auto v = in_->getStream(AVMEDIA_TYPE_VIDEO);
            if (!v){
                return -2;
            }
            AVStream *a = in_->getStream(AVMEDIA_TYPE_AUDIO);
            if (!audio){
                a = NULL;
            }
            auto ret = out_->JustWriter(v, a, file_path_.c_str());
            if (ret){
                logIt("start record file: %s", file_path_.c_str());
                return 0;
            }
 
            logIt("failed to start record: %s", file_path_.c_str());
 
            return -1;
        }
 
        int Recorder::init_write_hevc(const bool audio){
            if (fp_){
                fclose(fp_);
            }
 
            int pid = getpid();
            file_path_ = dir_ + "/" + sole::uuid4().base62() + "-" + std::to_string(pid) + ".hevc";
 
            fp_ = fopen(file_path_.c_str(), "wb");
            if (!fp_){
                logIt("write hevc open file error: %s", file_path_.c_str());
                return -1;
            }
            logIt("start record file: %s", file_path_.c_str());
 
            return 0;
        }
 
        int Recorder::init_writer(const bool audio){
            if(!in_){
                logIt("init_writer FormatIn not init");
                return -1;
            }
 
            if (in_->IsHEVC()){
                return init_write_hevc(audio);
            }else{
                return init_write_h264(audio);
            }
            return -2;
        }
 
////////////////////////
        int Recorder::write_h264(const CPacket &pkt){
            //reader failed, break stream
            if(pkt.id == -1 && !pkt.data){
                return -1;
            }
 
            if (cur_frame == end_frame){
                return 1;
            }
 
            AVPacket &op = pkt.data->getAVPacket();
            AVPacket np(op);
            av_copy_packet(&np, &op);
            
            int64_t cur = cur_frame;
            if (in_->isVideoPkt(&np)){
 
                if(pkt.id == id_frame_){
                    id_frame_in_file_ = cur_frame;
                }
                cur_frame++;
            }else if (in_->isAudioPkt(&np)) {
                cur = cur_frame_a++;
            }
            
            auto ret = out_->writeFrame(&np, cur);
            av_packet_unref(&np);
            
            if (!ret) return -1;
            
            // logIt("WRITE FRAME ID: %d, RECORD ID: %d", pkt.id, id_frame_);
            return 0;
            
        }
 
        int Recorder::write_hevc(const CPacket &pkt){
            if (!fp_){
                logIt("write hevc packet error, file not open");
                return -1;
            }
            if (cur_frame == end_frame){
                return 1;
            }
            
            AVPacket &op = pkt.data->getAVPacket();
            int64_t cur = cur_frame;
            if (in_->isVideoPkt(&op)){
 
                if(pkt.id == id_frame_){
                    id_frame_in_file_ = cur_frame;
                }
                cur_frame++;
            }
 
            fwrite(op.data, op.size, 1, fp_); 
            return 0;
        }
 
        int Recorder::write_correctly(const CPacket &pkt){
            if (in_->IsHEVC()){
                return write_hevc(pkt);
            }
            return write_h264(pkt);
        }
 
        int Recorder::end_write_h264(){
            if (!out_) return -1;
            out_->endWriter();
            if (out_){
                delete out_;
                out_ = NULL;
            }
            return 0;
        }
 
        int Recorder::end_write_hevc(){
            if (fp_){
                fclose(fp_);
                fp_ = NULL;
            }
 
            std::string hevc_file(file_path_);
            auto pos = file_path_.rfind(".hevc");
            if (pos != std::string::npos){
                file_path_ = file_path_.substr(0, pos) + ".mp4";
                logIt("mux hevc real file : %s", file_path_.c_str());
            }
 
            FILE *fp = fopen(hevc_file.c_str(), "rb");
            if (!fp) return 0;
 
            int ret = mux_hevc(fp, file_path_.c_str());
            fclose(fp);
            if (ret == 0){
                if (remove(hevc_file.c_str()) != 0){
                    logIt("mux hevc remove file %s failed", hevc_file.c_str());
                }
            }else{
                logIt("mux hevc to mp4 error, use raw hevc");
                file_path_ = hevc_file;
            }
 
            return 0;
        }
 
        static int read_buffer(void *opaque, uint8_t *buf, int buf_size){
            FILE *fp_open = (FILE*)opaque;
            if (!fp_open) logIt("mux hevc open file error");
 
            if(!feof(fp_open)){
                int true_size=fread(buf,1,buf_size,fp_open);
                return true_size;
            }else{
                return -1;
            }
        }
 
        int Recorder::mux_hevc(FILE *fp, const char *outfile){
            std::unique_ptr<FormatIn> in(new FormatIn(false));
 
            if (!fp) {
                logIt("mux hevc file handle is null");
                return -1;
            }
 
            int tryTime = 0;
            while (in->openWithCustomIO(fp, read_buffer) < 0) {
                usleep(10000);
                if (tryTime++ < 100){
                    logIt("mux hevc mux: %d failed open custom io %s, try again", tryTime, outfile);
                    continue;
                }
                logIt("mux hevc try %d time to open custom io, failed", tryTime);
                return -2;
            }
            if (in->open(NULL, NULL) < 0){
                logIt("mux hevc open stream error");
                return -3;
            }
            if (!in->findStreamInfo(NULL)) {
                logIt("mux hevc can't find streams");
                return -4;
            }
            
            std::unique_ptr<FormatOut> out(new FormatOut(in_->getFPS(), "mp4"));
            auto v = in->getStream(AVMEDIA_TYPE_VIDEO);
            if (!v){
                logIt("mux hevc file can't find video stream");
                return -5;
            }
            if (out->JustWriter(v, NULL, outfile)){
                logIt("mux hevc  start record file: %s", outfile);
            }
 
            int64_t id = 0;
            while(true){
                AVPacket pkt;
                if (in->readPacket(&pkt) != 0){
                    logIt("mux hevc read packet error, id: %lld", id);
                    break;
                }
                out->writeFrame(&pkt, id);
                // logIt("read frame: %d", id);
                
                av_packet_unref(&pkt);
                id++;
            }
            out->endWriter();
 
            return 0;
        }
 
        void Recorder::end_writer(){
 
            if (in_->IsHEVC()){
                end_write_hevc();
            }else{
                end_write_h264();
            }
 
            logIt("finished record : %s frames: %d", file_path_.c_str(), cur_frame);
            {
                std::lock_guard<std::mutex> l(mutex_pkt_);
                list_pkt_.clear();
            }
            // logIt("INDEX %d, REAL-FRAME-ID %d, FILE %s, CURFrame %d, ENDFrame %d\n",
            //      id_frame_in_file_, id_frame_, file_path_.c_str(), cur_frame, end_frame);
 
            if(func_rec_info_){
                func_rec_info_(id_,id_frame_in_file_, file_path_);
            }
        }
 
        void Recorder::run_thread(){
 
            while(!stop_recorder_.load()){
 
                std::list<CPacket> pkts;
                {
                    std::unique_lock<std::mutex> locker(mutex_pkt_);
                    auto status = cv_.wait_for(locker, std::chrono::seconds(3), [&]{
                        return !list_pkt_.empty() || stop_recorder_.load();
                    });
 
                    if (!status || stop_recorder_.load()){
                        error_occured_ = !status;
                        break;
                    }
                    list_pkt_.swap(pkts);
                }
                
                int ret = 0;
                for(auto &i : pkts){
                    ret = write_correctly(i);
                    if (ret != 0){
                        break;
                    }
                }
 
                if (ret != 0){
                    break;
                }
            }
 
            stop_recorder_.store(true);
            end_writer();
        }
 
        int Recorder::Run(const char* output, const int mind, const int maxd, const bool audio){
 
            bool a = audio;
            if (in_->IsHEVC()) a = false;
 
            dir_ = output;
            int ret = init_writer(a);
            if(ret != 0){
                logIt("recorder init writer error");
                return -1;
            }
 
            double fps = in_->getFPS();    
            if(fps > 1.0){
                maxduration = fps * maxd;
                minduration = fps * mind;
                end_frame = minduration;
            }
 
            audio_ = a;
 
            logIt("minduration %d maxduration %d curduration %d", minduration, maxduration, end_frame);    
 
            thrd_.reset(new std::thread([&]{
                run_thread();
            }));
            //.detach();
 
            return 0;
        }
 
        int Recorder::FireRecorder(const int64_t &id){
            if (stop_recorder_.load()) return -1;
 
            if(id_frame_ == -1){
                id_frame_ = id;
 
                std::lock_guard<std::mutex> locker(mutex_pkt_);
                if (list_pkt_.size() > end_frame){
                    end_frame = list_pkt_.size() + minduration/2;
                    if (end_frame > maxduration)
                        end_frame = maxduration;
                }
 
                // logIt("FIRST FIRE RECORD ID: %lld, cur_frame: %d, end_frame: %d", id, cur_frame, end_frame);
 
            }else if(cur_frame > minduration/2 && end_frame < maxduration){
                end_frame = end_frame + minduration / 2;
                if(end_frame > maxduration){
                    end_frame = maxduration;
                }
                // logIt("PROLONG REC, cur_frame: %d, end_frame: %d", cur_frame, end_frame);
            }
            // logIt("FIRE REC FRAME ID: %lld", id);
            return 0;
        }
 
        int Recorder::PushPacket(const CPacket &pkt){
            if (stop_recorder_.load()) return 0;
 
            std::lock_guard<std::mutex> locker(mutex_pkt_);
 
            if(id_frame_ == -1){
                //wait I 
                if (!audio_ && in_->isAudioPkt(&pkt.data->getAVPacket())){
                    return 0;
                }
 
                maybe_dump_gop();
 
                list_pkt_.push_back(pkt);
                // cv_.notify_one();
 
            }else{
                list_pkt_.push_back(pkt);
                cv_.notify_one();
            }
 
            return list_pkt_.size();
        }
 
        int Recorder::PushPackets(std::list<CPacket> &lst){
            
            if (stop_recorder_.load()) return 0;
 
            std::lock_guard<std::mutex> locker(mutex_pkt_);
            bool i = false;
            for (auto &p : lst){
                if (!audio_ && in_->isAudioPkt(&p.data->getAVPacket())){
                    continue;
                }
                
                list_pkt_.push_back(p);
            }
            maybe_dump_gop();
            cv_.notify_one();
 
            // logIt("CACHE PACKET : %d", list_pkt_.size());
            return list_pkt_.size();
        }
 
        void Recorder::maybe_dump_gop(){
            //超过min/2,丢弃gop
            while (list_pkt_.size() > minduration) {
                list_pkt_.pop_front();
                while(!list_pkt_.empty()){
                    auto &i = list_pkt_.front();
                    if (!(i.data->getAVPacket().flags & AV_PKT_FLAG_KEY)){
                        list_pkt_.pop_front();
                    }else{
                        break;
                    }
                }
            }
        }
    }
}