OSDN Git Service

[MOVIE_SAVER] Use SIMD to transfer a picture OSD(VM)->MOVIE_SAVER .
[csp-qt/common_source_project-fm7.git] / source / src / qt / avio / movie_saver.cpp
1 /*
2  * Common Source Code Project for Qt : movie saver.
3  * (C) 2016 K.Ohta <whatisthis.sowhat _at_ gmail.com>
4  *  License: GPLv2
5  *  History: May 27, 2016 : Initial. This refer from avidemux 2.5.6 .
6  */
7
8 #include <QDateTime>
9 #include "movie_saver.h"
10 #include "../osd.h"
11 #include "agar_logger.h"
12
13 MOVIE_SAVER::MOVIE_SAVER(int width, int height, int fps, OSD *osd, config_t *cfg) : QThread(0)
14 {
15         buffer_size=8 * 1024 * 224;
16         max_rate=4000 * 1000;
17         min_rate=0;
18         _width = width;
19         _height = height;
20         rec_fps = fps;
21         p_osd = osd;
22         p_config = cfg;
23         
24         recording = false;
25         audio_sample_rate = 48000;
26 #if defined(USE_MOVIE_SAVER)
27         memset(audio_frame_buf, 0x00, sizeof(audio_frame_buf));
28         memset(video_frame_buf, 0x00, sizeof(video_frame_buf));
29         output_context = NULL;
30         stream_format = NULL;
31         audio_codec = video_codec = NULL;
32         raw_options_list = NULL;
33         
34         memset(&video_st, 0x00, sizeof(video_st));
35         memset(&audio_st, 0x00, sizeof(audio_st));
36 #endif
37
38         output_context = NULL;
39         
40         audio_data_queue.clear();
41         video_data_queue.clear();
42         
43         do_reset_encoder_options();
44
45         //video_queue_mutex = new QMutex(QMutex::Recursive);
46         totalSrcFrame = 0;
47         totalDstFrame = 0;
48         totalAudioFrame = 0;
49
50         video_bit_rate = 1500 * 1000;
51         audio_bit_rate = 160 * 1000;
52         video_geometry = QSize(640, 480);
53         video_encode_threads = 4;
54 //      audio_enqueue_count = 0;
55         left_frames = 0;
56         req_close = false;
57         req_stop = false;
58         bRunThread = false;
59         
60 }
61
62 MOVIE_SAVER::~MOVIE_SAVER()
63 {
64         if(recording) do_close_main();
65         //if(video_queue_mutex) delete video_queue_mutex;
66
67 }
68
69 QString MOVIE_SAVER::ts2str(int64_t ts)
70 {
71 #if defined(USE_LIBAV)  
72         char buffer[AV_TS_MAX_STRING_SIZE + 16];
73         memset(buffer, 0x00, sizeof(buffer));
74         return QString::fromLocal8Bit(av_ts_make_string(buffer, ts));
75 #else
76         return QString::fromUtf8("");
77 #endif
78 }                  
79
80 QString MOVIE_SAVER::ts2timestr(int64_t ts, void *timebase)
81 {
82 #if defined(USE_LIBAV)  
83         char buffer[AV_TS_MAX_STRING_SIZE + 16];
84         AVRational *tb = (AVRational *)timebase;
85         memset(buffer, 0x00, sizeof(buffer));
86         return QString::fromLocal8Bit(av_ts_make_time_string(buffer, ts, tb));
87 #else
88         return QString::fromUtf8("");
89 #endif
90 }                  
91
92 QString MOVIE_SAVER::err2str(int errnum)
93 {
94 #if defined(USE_LIBAV)  
95         char buffer[AV_TS_MAX_STRING_SIZE + 16];
96         memset(buffer, 0x00, sizeof(buffer));
97         return QString::fromLocal8Bit(av_make_error_string(buffer, sizeof(buffer), errnum));
98 #else
99         return QString::fromUtf8("");
100 #endif
101 }                  
102
103 //void MOVIE_SAVER::log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
104 void MOVIE_SAVER::log_packet(const void *_fmt_ctx, const void *_pkt)
105 {
106 #if defined(USE_LIBAV)  
107         const AVFormatContext *fmt_ctx = (const AVFormatContext *)_fmt_ctx;
108         const AVPacket *pkt = (const AVPacket *)_pkt;
109         AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
110
111         AGAR_DebugLog(AGAR_LOG_DEBUG, "pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
112                    ts2str(pkt->pts).toLocal8Bit().constData(),
113                    ts2timestr(pkt->pts, (void *)time_base).toLocal8Bit().constData(),
114                    ts2str(pkt->dts).toLocal8Bit().constData(),
115                    ts2timestr(pkt->dts, (void *)time_base).toLocal8Bit().constData(),
116                    ts2str(pkt->duration).toLocal8Bit().constData(),
117                    ts2timestr(pkt->duration, (void *)time_base).toLocal8Bit().constData(),
118                    pkt->stream_index);
119 #endif  
120 }
121
122
123 void MOVIE_SAVER::enqueue_video(int frames, int width, int height, QImage *p)
124 {
125 #if defined(USE_MOVIE_SAVER)
126         if(!recording) return;
127         if(p == NULL) return;
128         if(req_stop) return;
129         uint32_t *pq;
130         VIDEO_DATA *px = new VIDEO_DATA(frames, width, height, p);
131         //AGAR_DebugLog(AGAR_LOG_DEBUG, "Movie: Enqueue video data %dx%d %d bytes %dx%d %d frames", width, height, p->byteCount(), p->width(), p->height(), frames);
132         //video_queue_mutex->lock();
133         video_data_queue.enqueue(px);
134         //video_queue_mutex->unlock();
135 #endif   
136 }
137
138 bool MOVIE_SAVER::dequeue_video(uint32_t *p)
139 {
140         //if(!recording) return false;
141         if(p == NULL) return false;
142
143         VIDEO_DATA *pp = video_data_queue.dequeue();
144 #if defined(USE_MOVIE_SAVER)
145         if(pp == NULL) return false;
146         int y;
147         int x;
148         uint32_t *pq;
149         QImage *pp_i = &(pp->frame_data);
150         left_frames = pp->frames;
151         _width = pp->_width;
152         _height = pp->_height;
153         if((left_frames > 0) && (pp_i != NULL)){ 
154                 for(y = 0; y < _height; y++) {
155                         if(y >= pp_i->height()) break;
156                         pq = (uint32_t *)(pp_i->constScanLine(y));
157                         memcpy(&(p[_width * y]), pq, ((_width * sizeof(uint32_t)) > pp_i->bytesPerLine()) ? pp_i->bytesPerLine() : _width * sizeof(uint32_t));
158                 }
159                 video_size = _width * y;
160                 //AGAR_DebugLog(AGAR_LOG_DEBUG, "Movie: Dequeue video data %d bytes", pp->byteCount());
161         }
162 #else
163         video_size = 0;
164 #endif   
165         if(pp != NULL) delete pp;
166         return true;
167 }
168
169 void MOVIE_SAVER::enqueue_audio(int16_t *p, int size)
170 {
171 #if defined(USE_MOVIE_SAVER)
172         if(!recording) return;
173         if(p == NULL) return;
174         if(req_stop) return;
175         QByteArray *pp = new QByteArray((const char *)p, size);
176         //AGAR_DebugLog(AGAR_LOG_DEBUG, "Movie: Enqueue audio data %d bytes", size);
177         audio_data_queue.enqueue(pp);
178 //      audio_enqueue_count++;
179 #endif   
180 }
181
182 bool MOVIE_SAVER::dequeue_audio(int16_t *p)
183 {
184         //if(!recording) return false;
185         if(audio_data_queue.isEmpty()) return false;
186         if(p == NULL) return false;
187         
188         QByteArray *pp = audio_data_queue.dequeue();
189         int16_t *q = (int16_t *)pp->constData();
190         int32_t tmpd;
191 #if defined(USE_MOVIE_SAVER)
192         if(pp == NULL) return false;
193         audio_size = pp->size();
194         if(audio_size <= 0) return false;
195         // I expect to use SIMD.
196         for(int i = 0; i < audio_size / sizeof(int16_t); i++) {
197                 tmpd = q[i];
198                 tmpd <<= 4;
199                 tmpd = tmpd / 3;
200                 tmpd >>= 3;
201                 p[i] = tmpd;
202         }
203         //memcpy(p, pp->constData(), audio_size);
204         audio_count++;
205         //AGAR_DebugLog(AGAR_LOG_DEBUG, "Movie: Dequeue audio data %d bytes", pp->size());
206 #else
207         audio_size = 0;
208 #endif   
209         if(pp != NULL) delete pp;
210         return true;
211 }
212
213
214 void MOVIE_SAVER::run()
215 {
216         bRunThread = true;
217         //AGAR_DebugLog(AGAR_LOG_DEBUG, "MOVIE THREAD: Start");
218         int ret;
219         int fps_wait = (int)((1000.0 / (double)rec_fps) / 4.0);
220         int tmp_wait = fps_wait;
221         bool need_audio_transcode = false;
222         bool need_video_transcode = false;
223         int i;
224         int64_t total_packets_written = 0;
225         bool a_f, v_f;
226         a_f = v_f = false;
227         volatile bool old_recording = false;
228         audio_remain = 0;
229         video_remain = 0;
230         audio_offset = 0;
231         audio_frame_offset = 0;
232         video_offset = 0;
233         n_encode_audio = 0;
234         n_encode_video = 0;
235         req_close = false;
236         req_stop = false;
237         left_frames = 0;
238         while(bRunThread) {
239                 if(recording) {
240                         if(!bRunThread) break;
241                         if(!old_recording) {
242                                 //n_encode_video = n_encode_audio = 1;
243                                 audio_remain = 0;
244                                 video_remain = 0;
245                                 audio_offset = 0;
246                                 audio_frame_offset = 0;
247                                 video_offset = 0;
248                                 video_count = 0;
249                                 audio_count = 0;
250                                 req_close = false;
251                                 req_stop = false;
252                                 //printf("*\n");
253                                 left_frames = 0;
254                                 if(!do_open_main()) {
255                                         recording = false;
256                                         goto _next_turn;
257                                 }
258                                 AGAR_DebugLog(AGAR_LOG_DEBUG, "MOVIE/Saver: Start to recording.");
259                                 old_recording = true;
260                                 a_f = v_f = false;
261                         }
262                         if(audio_remain <= 0) {
263                                 a_f = audio_data_queue.isEmpty();
264                                 if(a_f) goto _video;
265                                 dequeue_audio(audio_frame_buf);
266                                 audio_remain = audio_size;
267                                 audio_offset = 0;
268                                 need_audio_transcode = true;
269                         }
270                 _video:
271                         {
272                                 v_f = video_data_queue.isEmpty();
273                                 if(v_f)
274                                         goto _write_frame;
275                                 if(left_frames <= 0) dequeue_video(video_frame_buf);
276                                 left_frames--;
277                                 video_remain = video_size;
278                                 video_offset = 0;
279                                 need_video_transcode = true;
280                         }
281                 _write_frame:
282                         if ((n_encode_video == 0) &&
283                                 ((n_encode_audio != 0) || av_compare_ts(video_st.next_pts, video_st.st->codec->time_base,
284                                                                                                                 audio_st.next_pts, audio_st.st->codec->time_base) <= 0)) {
285                                 n_encode_video = write_video_frame();
286                                 if(n_encode_video < 0) {
287                                         AGAR_DebugLog(AGAR_LOG_DEBUG, "MOVIE/Saver: Something wrong with encoding video.");
288                                         goto _final;
289                                 }
290                         } else {
291                                 n_encode_audio = write_audio_frame();
292                                 if(n_encode_audio < 0) {
293                                         AGAR_DebugLog(AGAR_LOG_DEBUG, "MOVIE/Saver: Something wrong with encoding audio.");
294                                         goto _final;
295                                 }
296                         }
297                         if (ret < 0 && ret != AVERROR_EOF) {
298                                 char errbuf[128];
299                                 av_strerror(ret, errbuf, sizeof(errbuf));
300                                 AGAR_DebugLog(AGAR_LOG_INFO, "Error while filtering: %s\n", (const char *)errbuf);
301                                 goto _final;
302                         }
303                         
304                         /* dump report by using the output first video and audio streams */
305                         //print_report(0, timer_start, cur_time);
306                         if(req_close) {
307                                 do_close_main();
308                                 need_video_transcode = need_audio_transcode = false;
309                                 old_recording = false;
310                         }
311                 }
312         _next_turn:
313                 //if(req_stop && a_f && v_f) req_close = true;
314                 //printf("%d\n", req_close);
315                 if(!bRunThread) break;
316                 if(need_video_transcode || need_audio_transcode) {
317                         need_video_transcode = need_audio_transcode = false;
318                         continue;
319                 }
320                 if(fps_wait >= tmp_wait) {
321                         this->msleep(tmp_wait);
322                         tmp_wait = 0;
323                 } else {
324                         this->msleep(fps_wait);
325                         tmp_wait -= fps_wait;
326                 }
327                 if(tmp_wait <= 0) {
328                         fps_wait = (int)((1000.0 / (double)rec_fps) / 4.0);
329                         //fps_wait = 10;
330                         tmp_wait = fps_wait;
331                 }
332                 if(req_close) {
333                         do_close_main();
334                         old_recording = false;
335                 }
336                 continue;
337         _final:
338                 req_close = true;
339                 do_close_main();
340                 old_recording = false;
341         }
342         AGAR_DebugLog(AGAR_LOG_DEBUG, "MOVIE: Exit thread.");
343         if(recording) {
344                 req_close = true;
345                 do_close_main();
346         }
347 }
348
349 bool MOVIE_SAVER::is_recording(void)
350 {
351         return recording;
352 }
353
354
355 void MOVIE_SAVER::do_exit()
356 {
357         bRunThread = false;
358         req_close = true;
359         req_stop = true;
360 }
361
362 void MOVIE_SAVER::do_set_record_fps(int fps)
363 {
364         if((fps > 0) && (fps <= 75)) rec_fps = fps;
365 }
366
367 void MOVIE_SAVER::do_set_width(int width)
368 {
369         //printf("width = %d -> %d\n", _width, width);
370         _width = width;
371 }
372
373 void MOVIE_SAVER::do_set_height(int height)
374 {
375         //printf("height = %d -> %d\n", _height, height);
376         _height = height;
377 }
378
379 void MOVIE_SAVER::do_clear_options_list(void)
380 {
381         encode_opt_keys.clear();
382         encode_options.clear();
383 }
384
385 void MOVIE_SAVER::do_add_option(QString key, QString value)
386 {
387         if(key.isEmpty()) return;
388         encode_opt_keys.append(key);
389         if(value.isEmpty()) {
390                 encode_options.append(QString::fromUtf8(""));
391         } else {
392                 encode_options.append(value);
393         }
394 }               
395
396 void MOVIE_SAVER::do_set_video_bitrate(int kbps)
397 {
398         if(kbps < 10) return;
399         video_bit_rate = kbps * 1000;
400 }
401
402 void MOVIE_SAVER::do_set_audio_bitrate(int kbps)
403 {
404         if(kbps < 8) return;
405         audio_bit_rate = kbps * 1000;
406 }
407
408 void MOVIE_SAVER::do_set_video_geometry(QSize geometry)
409 {
410         if(geometry.width() < 100) return;
411         if(geometry.height() < 80) return;
412         video_geometry = geometry;
413 }
414
415 void MOVIE_SAVER::do_set_video_threads(int threads)
416 {
417         video_encode_threads = threads;
418 }
419
420 void MOVIE_SAVER::do_reset_encoder_options(void)
421 {
422         encode_opt_keys.clear();
423         encode_options.clear();
424
425         do_add_option(QString::fromUtf8("c:v"), QString::fromUtf8("libx264"));
426         do_add_option(QString::fromUtf8("c:a"), QString::fromUtf8("aac"));
427         do_add_option(QString::fromUtf8("preset"), QString::fromUtf8("slow"));
428         do_add_option(QString::fromUtf8("tune"), QString::fromUtf8("grain"));
429         //do_add_option(QString::fromUtf8("crf"), QString::fromUtf8("20"));
430         do_add_option(QString::fromUtf8("qmin"), QString::fromUtf8("16"));
431         do_add_option(QString::fromUtf8("qmax"), QString::fromUtf8("24"));
432         // Dummy
433         do_add_option(QString::fromUtf8("qmax"), QString::fromUtf8("24"));
434 }
435