OSDN Git Service

Merge branch 'master' of github.com:Artanejp/common_source_project-fm7
[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 "csp_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         csp_logger->debug_log(CSP_LOG_DEBUG, CSP_LOG_TYPE_MOVIE_SAVER, "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         VIDEO_DATA *px = new VIDEO_DATA(frames, width, height, p);
130         //csp_logger->debug_log(CSP_LOG_DEBUG, CSP_LOG_TYPE_MOVIE_SAVER, "Movie: Enqueue video data %dx%d %d bytes %dx%d %d frames", width, height, p->byteCount(), p->width(), p->height(), frames);
131         //video_queue_mutex->lock();
132         video_data_queue.enqueue(px);
133         //video_queue_mutex->unlock();
134 #endif   
135 }
136
137 bool MOVIE_SAVER::dequeue_video(uint32_t *p)
138 {
139         //if(!recording) return false;
140         if(p == NULL) return false;
141
142         VIDEO_DATA *pp = video_data_queue.dequeue();
143 #if defined(USE_MOVIE_SAVER)
144         if(pp == NULL) return false;
145         int y;
146         uint32_t *pq;
147         QImage *pp_i = &(pp->frame_data);
148         left_frames = pp->frames;
149         _width = pp->_width;
150         _height = pp->_height;
151         if((left_frames > 0) && (pp_i != NULL)){ 
152                 for(y = 0; y < _height; y++) {
153                         if(y >= pp_i->height()) break;
154                         pq = (uint32_t *)(pp_i->constScanLine(y));
155                         memcpy(&(p[_width * y]), pq, (((uint)_width * sizeof(uint32_t)) > pp_i->bytesPerLine()) ? pp_i->bytesPerLine() : _width * sizeof(uint32_t));
156                 }
157                 video_size = _width * y;
158                 //csp_logger->debug_log(CSP_LOG_DEBUG, CSP_LOG_TYPE_MOVIE_SAVER, "Movie: Dequeue video data %d bytes", pp->byteCount());
159         }
160 #else
161         video_size = 0;
162 #endif   
163         if(pp != NULL) delete pp;
164         return true;
165 }
166
167 void MOVIE_SAVER::enqueue_audio(int16_t *p, int size)
168 {
169 #if defined(USE_MOVIE_SAVER)
170         if(!recording) return;
171         if(p == NULL) return;
172         if(req_stop) return;
173         QByteArray *pp = new QByteArray((const char *)p, size);
174         //csp_logger->debug_log(CSP_LOG_DEBUG, CSP_LOG_TYPE_MOVIE_SAVER, "Movie: Enqueue audio data %d bytes", size);
175         audio_data_queue.enqueue(pp);
176 //      audio_enqueue_count++;
177 #endif   
178 }
179
180 bool MOVIE_SAVER::dequeue_audio(int16_t *p)
181 {
182         //if(!recording) return false;
183         if(audio_data_queue.isEmpty()) return false;
184         if(p == NULL) return false;
185         
186         QByteArray *pp = audio_data_queue.dequeue();
187         int16_t *q = (int16_t *)pp->constData();
188         int32_t tmpd;
189 #if defined(USE_MOVIE_SAVER)
190         if(pp == NULL) return false;
191         audio_size = pp->size();
192         if(audio_size <= 0) return false;
193         // I expect to use SIMD.
194         for(int i = 0; i < (int)(audio_size / sizeof(int16_t)); i++) {
195                 tmpd = q[i];
196                 tmpd <<= 4;
197                 tmpd = tmpd / 3;
198                 tmpd >>= 3;
199                 p[i] = tmpd;
200         }
201         //memcpy(p, pp->constData(), audio_size);
202         audio_count++;
203 #else
204         audio_size = 0;
205 #endif   
206         if(pp != NULL) delete pp;
207         return true;
208 }
209
210
211 void MOVIE_SAVER::run()
212 {
213         bRunThread = true;
214         //csp_logger->debug_log(CSP_LOG_DEBUG, CSP_LOG_TYPE_MOVIE_SAVER, "MOVIE THREAD: Start");
215         int ret;
216         int fps_wait = (int)((1000.0 / (double)rec_fps) / 4.0);
217         int tmp_wait = fps_wait;
218         bool need_audio_transcode = false;
219         bool need_video_transcode = false;
220         int i;
221         int64_t total_packets_written = 0;
222         bool a_f, v_f;
223         a_f = v_f = false;
224         volatile bool old_recording = false;
225         audio_remain = 0;
226         video_remain = 0;
227         audio_offset = 0;
228         audio_frame_offset = 0;
229         video_offset = 0;
230         n_encode_audio = 0;
231         n_encode_video = 0;
232         req_close = false;
233         req_stop = false;
234         left_frames = 0;
235         while(bRunThread) {
236                 if(recording) {
237                         if(!bRunThread) break;
238                         if(!old_recording) {
239                                 //n_encode_video = n_encode_audio = 1;
240                                 audio_remain = 0;
241                                 video_remain = 0;
242                                 audio_offset = 0;
243                                 audio_frame_offset = 0;
244                                 video_offset = 0;
245                                 video_count = 0;
246                                 audio_count = 0;
247                                 req_close = false;
248                                 req_stop = false;
249                                 left_frames = 0;
250                                 if(!do_open_main()) {
251                                         recording = false;
252                                         goto _next_turn;
253                                 }
254                                 csp_logger->debug_log(CSP_LOG_DEBUG, CSP_LOG_TYPE_MOVIE_SAVER, "MOVIE/Saver: Start to recording.");
255                                 old_recording = true;
256                                 a_f = v_f = false;
257                         }
258                         if(audio_remain <= 0) {
259                                 a_f = audio_data_queue.isEmpty();
260                                 if(a_f) goto _video;
261                                 dequeue_audio(audio_frame_buf);
262                                 audio_remain = audio_size;
263                                 audio_offset = 0;
264                                 need_audio_transcode = true;
265                         }
266                 _video:
267                         {
268                                 v_f = video_data_queue.isEmpty();
269                                 if(v_f)
270                                         goto _write_frame;
271                                 if(left_frames <= 0) dequeue_video(video_frame_buf);
272                                 left_frames--;
273                                 video_remain = video_size;
274                                 video_offset = 0;
275                                 need_video_transcode = true;
276                         }
277                 _write_frame:
278                         if ((n_encode_video == 0) &&
279                                 ((n_encode_audio != 0) || av_compare_ts(video_st.next_pts, video_st.st->codec->time_base,
280                                                                                                                 audio_st.next_pts, audio_st.st->codec->time_base) <= 0)) {
281                                 n_encode_video = write_video_frame();
282                                 if(n_encode_video < 0) {
283                                         csp_logger->debug_log(CSP_LOG_DEBUG, CSP_LOG_TYPE_MOVIE_SAVER, "MOVIE/Saver: Something wrong with encoding video.");
284                                         goto _final;
285                                 }
286                         } else {
287                                 n_encode_audio = write_audio_frame();
288                                 if(n_encode_audio < 0) {
289                                         csp_logger->debug_log(CSP_LOG_DEBUG, CSP_LOG_TYPE_MOVIE_SAVER, "MOVIE/Saver: Something wrong with encoding audio.");
290                                         goto _final;
291                                 }
292                         }
293                         if (ret < 0 && ret != AVERROR_EOF) {
294                                 char errbuf[128];
295                                 av_strerror(ret, errbuf, sizeof(errbuf));
296                                 csp_logger->debug_log(CSP_LOG_INFO, CSP_LOG_TYPE_MOVIE_SAVER, "Error while filtering: %s\n", (const char *)errbuf);
297                                 goto _final;
298                         }
299                         
300                         /* dump report by using the output first video and audio streams */
301                         //print_report(0, timer_start, cur_time);
302                         if(req_close) {
303                                 do_close_main();
304                                 need_video_transcode = need_audio_transcode = false;
305                                 old_recording = false;
306                         }
307                 }
308         _next_turn:
309                 //if(req_stop && a_f && v_f) req_close = true;
310                 if(!bRunThread) break;
311                 if(need_video_transcode || need_audio_transcode) {
312                         need_video_transcode = need_audio_transcode = false;
313                         continue;
314                 }
315                 if(fps_wait >= tmp_wait) {
316                         this->msleep(tmp_wait);
317                         tmp_wait = 0;
318                 } else {
319                         this->msleep(fps_wait);
320                         tmp_wait -= fps_wait;
321                 }
322                 if(tmp_wait <= 0) {
323                         fps_wait = (int)((1000.0 / (double)rec_fps) / 4.0);
324                         //fps_wait = 10;
325                         tmp_wait = fps_wait;
326                 }
327                 if(req_close) {
328                         do_close_main();
329                         old_recording = false;
330                 }
331                 continue;
332         _final:
333                 req_close = true;
334                 do_close_main();
335                 old_recording = false;
336         }
337         csp_logger->debug_log(CSP_LOG_DEBUG, CSP_LOG_TYPE_MOVIE_SAVER, "MOVIE: Exit thread.");
338         if(recording) {
339                 req_close = true;
340                 do_close_main();
341         }
342 }
343
344 bool MOVIE_SAVER::is_recording(void)
345 {
346         return recording;
347 }
348
349
350 void MOVIE_SAVER::do_exit()
351 {
352         bRunThread = false;
353         req_close = true;
354         req_stop = true;
355 }
356
357 void MOVIE_SAVER::do_set_record_fps(int fps)
358 {
359         if((fps > 0) && (fps <= 75)) rec_fps = fps;
360 }
361
362 void MOVIE_SAVER::do_set_width(int width)
363 {
364         _width = width;
365 }
366
367 void MOVIE_SAVER::do_set_height(int height)
368 {
369         _height = height;
370 }
371
372 void MOVIE_SAVER::do_clear_options_list(void)
373 {
374         encode_opt_keys.clear();
375         encode_options.clear();
376 }
377
378 void MOVIE_SAVER::do_add_option(QString key, QString value)
379 {
380         if(key.isEmpty()) return;
381         encode_opt_keys.append(key);
382         if(value.isEmpty()) {
383                 encode_options.append(QString::fromUtf8(""));
384         } else {
385                 encode_options.append(value);
386         }
387 }               
388
389 void MOVIE_SAVER::do_set_video_bitrate(int kbps)
390 {
391         if(kbps < 10) return;
392         video_bit_rate = kbps * 1000;
393 }
394
395 void MOVIE_SAVER::do_set_audio_bitrate(int kbps)
396 {
397         if(kbps < 8) return;
398         audio_bit_rate = kbps * 1000;
399 }
400
401 void MOVIE_SAVER::do_set_video_geometry(QSize geometry)
402 {
403         if(geometry.width() < 100) return;
404         if(geometry.height() < 80) return;
405         video_geometry = geometry;
406 }
407
408 void MOVIE_SAVER::do_set_video_threads(int threads)
409 {
410         video_encode_threads = threads;
411 }
412
413 void MOVIE_SAVER::do_reset_encoder_options(void)
414 {
415         encode_opt_keys.clear();
416         encode_options.clear();
417
418         do_add_option(QString::fromUtf8("c:v"), QString::fromUtf8("libx264"));
419         do_add_option(QString::fromUtf8("c:a"), QString::fromUtf8("aac"));
420         do_add_option(QString::fromUtf8("preset"), QString::fromUtf8("slow"));
421         do_add_option(QString::fromUtf8("tune"), QString::fromUtf8("grain"));
422         //do_add_option(QString::fromUtf8("crf"), QString::fromUtf8("20"));
423         do_add_option(QString::fromUtf8("qmin"), QString::fromUtf8("16"));
424         do_add_option(QString::fromUtf8("qmax"), QString::fromUtf8("24"));
425         // Dummy
426         do_add_option(QString::fromUtf8("qmax"), QString::fromUtf8("24"));
427 }
428