]> git.sesse.net Git - nageru/blob - futatabi/main.cpp
Add a Futatabi metric for number of received frames.
[nageru] / futatabi / main.cpp
1 #include <assert.h>
2 #include <arpa/inet.h>
3 #include <atomic>
4 #include <chrono>
5 #include <condition_variable>
6 #include <dirent.h>
7 #include <getopt.h>
8 #include <memory>
9 #include <mutex>
10 #include <stdint.h>
11 #include <stdio.h>
12 #include <string>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <thread>
16 #include <unistd.h>
17 #include <vector>
18
19 extern "C" {
20 #include <libavformat/avformat.h>
21 }
22
23 #include "clip_list.h"
24 #include "shared/context.h"
25 #include "defs.h"
26 #include "shared/disk_space_estimator.h"
27 #include "shared/ffmpeg_raii.h"
28 #include "flags.h"
29 #include "frame_on_disk.h"
30 #include "frame.pb.h"
31 #include "shared/httpd.h"
32 #include "mainwindow.h"
33 #include "player.h"
34 #include "shared/post_to_main_thread.h"
35 #include "shared/ref_counted_gl_sync.h"
36 #include "shared/timebase.h"
37 #include "shared/metrics.h"
38 #include "ui_mainwindow.h"
39 #include "vaapi_jpeg_decoder.h"
40
41 #include <QApplication>
42 #include <QGLFormat>
43 #include <QSurfaceFormat>
44 #include <QProgressDialog>
45 #include <movit/init.h>
46 #include <movit/util.h>
47
48 using namespace std;
49 using namespace std::chrono;
50
51 constexpr char frame_magic[] = "Ftbifrm0";
52 constexpr size_t frame_magic_len = 8;
53
54 mutex RefCountedGLsync::fence_lock;
55 atomic<bool> should_quit{false};
56
57 int64_t start_pts = -1;
58
59 // TODO: Replace by some sort of GUI control, I guess.
60 int64_t current_pts = 0;
61
62 struct FrameFile {
63         FILE *fp = nullptr;
64         unsigned filename_idx;
65         size_t frames_written_so_far = 0;
66 };
67 std::map<int, FrameFile> open_frame_files;
68
69 mutex frame_mu;
70 vector<FrameOnDisk> frames[MAX_STREAMS];  // Under frame_mu.
71 vector<string> frame_filenames;  // Under frame_mu.
72
73 atomic<int64_t> metric_received_frames[MAX_STREAMS]{{0}};
74
75 namespace {
76
77 FrameOnDisk write_frame(int stream_idx, int64_t pts, const uint8_t *data, size_t size, DB *db)
78 {
79         if (open_frame_files.count(stream_idx) == 0) {
80                 char filename[256];
81                 snprintf(filename, sizeof(filename), "%s/frames/cam%d-pts%09ld.frames",
82                         global_flags.working_directory.c_str(), stream_idx, pts);
83                 FILE *fp = fopen(filename, "wb");
84                 if (fp == nullptr) {
85                         perror(filename);
86                         exit(1);
87                 }
88
89                 lock_guard<mutex> lock(frame_mu);
90                 unsigned filename_idx = frame_filenames.size();
91                 frame_filenames.push_back(filename);
92                 open_frame_files[stream_idx] = FrameFile{ fp, filename_idx, 0 };
93         }
94
95         FrameFile &file = open_frame_files[stream_idx];
96         unsigned filename_idx = file.filename_idx;
97         string filename;
98         {
99                 lock_guard<mutex> lock(frame_mu);
100                 filename = frame_filenames[filename_idx];
101         }
102
103         FrameHeaderProto hdr;
104         hdr.set_stream_idx(stream_idx);
105         hdr.set_pts(pts);
106         hdr.set_file_size(size);
107
108         string serialized;
109         if (!hdr.SerializeToString(&serialized)) {
110                 fprintf(stderr, "Frame header serialization failed.\n");
111                 exit(1);
112         }
113         uint32_t len = htonl(serialized.size());
114
115         if (fwrite(frame_magic, frame_magic_len, 1, file.fp) != 1) {
116                 perror("fwrite");
117                 exit(1);
118         }
119         if (fwrite(&len, sizeof(len), 1, file.fp) != 1) {
120                 perror("fwrite");
121                 exit(1);
122         }
123         if (fwrite(serialized.data(), serialized.size(), 1, file.fp) != 1) {
124                 perror("fwrite");
125                 exit(1);
126         }
127         off_t offset = ftell(file.fp);
128         if (fwrite(data, size, 1, file.fp) != 1) {
129                 perror("fwrite");
130                 exit(1);
131         }
132         fflush(file.fp);  // No fsync(), though. We can accept losing a few frames.
133         global_disk_space_estimator->report_write(filename, 8 + sizeof(len) + serialized.size() + size, pts);
134
135         FrameOnDisk frame;
136         frame.pts = pts;
137         frame.filename_idx = filename_idx;
138         frame.offset = offset;
139         frame.size = size;
140
141         {
142                 lock_guard<mutex> lock(frame_mu);
143                 assert(stream_idx < MAX_STREAMS);
144                 frames[stream_idx].push_back(frame);
145         }
146
147         if (++file.frames_written_so_far >= 1000) {
148                 size_t size = ftell(file.fp);
149
150                 // Start a new file next time.
151                 if (fclose(file.fp) != 0) {
152                         perror("fclose");
153                         exit(1);
154                 }
155                 open_frame_files.erase(stream_idx);
156
157                 // Write information about all frames in the finished file to SQLite.
158                 // (If we crash before getting to do this, we'll be scanning through
159                 // the file on next startup, and adding it to the database then.)
160                 // NOTE: Since we don't fsync(), we could in theory get broken data
161                 // but with the right size, but it would seem unlikely.
162                 vector<DB::FrameOnDiskAndStreamIdx> frames_this_file;
163                 {
164                         lock_guard<mutex> lock(frame_mu);
165                         for (size_t stream_idx = 0; stream_idx < MAX_STREAMS; ++stream_idx) {
166                                 for (const FrameOnDisk &frame : frames[stream_idx]) {
167                                         if (frame.filename_idx == filename_idx) {
168                                                 frames_this_file.emplace_back(DB::FrameOnDiskAndStreamIdx{ frame, unsigned(stream_idx) });
169                                         }
170                                 }
171                         }
172                 }
173
174                 const char *basename = filename.c_str();
175                 while (strchr(basename, '/') != nullptr) {
176                         basename = strchr(basename, '/') + 1;
177                 }
178                 db->store_frame_file(basename, size, frames_this_file);
179         }
180
181         return frame;
182 }
183
184 } // namespace
185
186 HTTPD *global_httpd;
187
188 void load_existing_frames();
189 void record_thread_func();
190
191 int main(int argc, char **argv)
192 {
193         parse_flags(argc, argv);
194         if (optind == argc) {
195                 global_flags.stream_source = "multiangle.mp4";
196                 global_flags.slow_down_input = true;
197         } else if (optind + 1 == argc) {
198                 global_flags.stream_source = argv[optind];
199         } else {
200                 usage();
201                 exit(1);
202         }
203
204         string frame_dir = global_flags.working_directory + "/frames";
205
206         if (mkdir(frame_dir.c_str(), 0777) == 0) {
207                 fprintf(stderr, "%s does not exist, creating it.\n", frame_dir.c_str());
208         } else if (errno != EEXIST) {
209                 perror(global_flags.working_directory.c_str());
210                 exit(1);
211         }
212
213         avformat_network_init();
214         global_httpd = new HTTPD;
215
216         QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
217
218         QSurfaceFormat fmt;
219         fmt.setDepthBufferSize(0);
220         fmt.setStencilBufferSize(0);
221         fmt.setProfile(QSurfaceFormat::CoreProfile);
222         fmt.setMajorVersion(4);
223         fmt.setMinorVersion(5);
224
225         // Turn off vsync, since Qt generally gives us at most frame rate
226         // (display frequency) / (number of QGLWidgets active).
227         fmt.setSwapInterval(0);
228
229         QSurfaceFormat::setDefaultFormat(fmt);
230
231         QGLFormat::setDefaultFormat(QGLFormat::fromSurfaceFormat(fmt));
232
233         QApplication app(argc, argv);
234         global_share_widget = new QGLWidget();
235         if (!global_share_widget->isValid()) {
236                 fprintf(stderr, "Failed to initialize OpenGL. Futatabi needs at least OpenGL 4.5 to function properly.\n");
237                 exit(1);
238         }
239
240         // Initialize Movit.
241         {
242                 QSurface *surface = create_surface();
243                 QOpenGLContext *context = create_context(surface);
244                 if (!make_current(context, surface)) {
245                         printf("oops\n");
246                         exit(1);
247                 }
248                 CHECK(movit::init_movit(MOVIT_SHADER_DIR, movit::MOVIT_DEBUG_OFF));
249                 delete_context(context);
250                 // TODO: Delete the surface, too.
251         }
252
253         load_existing_frames();
254
255         MainWindow main_window;
256         main_window.show();
257
258         global_httpd->add_endpoint("/queue_status", bind(&MainWindow::get_queue_status, &main_window), HTTPD::NO_CORS_POLICY);
259         global_httpd->start(global_flags.http_port);
260
261         init_jpeg_vaapi();
262
263         thread record_thread(record_thread_func);
264
265         int ret = app.exec();
266
267         should_quit = true;
268         record_thread.join();
269         JPEGFrameView::shutdown();
270
271         return ret;
272 }
273
274 void load_frame_file(const char *filename, const string &basename, unsigned filename_idx, DB *db)
275 {
276         struct stat st;
277         if (stat(filename, &st) == -1) {
278                 perror(filename);
279                 exit(1);
280         }
281
282         vector<DB::FrameOnDiskAndStreamIdx> all_frames = db->load_frame_file(basename, st.st_size, filename_idx);
283         if (!all_frames.empty()) {
284                 // We already had this cached in the database, so no need to look in the file.
285                 for (const DB::FrameOnDiskAndStreamIdx &frame : all_frames) {
286                         if (frame.stream_idx < MAX_STREAMS) {
287                                 frames[frame.stream_idx].push_back(frame.frame);
288                                 start_pts = max(start_pts, frame.frame.pts);
289                         }
290                 }
291                 return;
292         }
293
294         FILE *fp = fopen(filename, "rb");
295         if (fp == nullptr) {
296                 perror(filename);
297                 exit(1);
298         }
299
300         size_t magic_offset = 0;
301         size_t skipped_bytes = 0;
302         while (!feof(fp) && !ferror(fp)) {
303                 int ch = getc(fp);
304                 if (ch == -1) {
305                         break;
306                 }
307                 if (ch != frame_magic[magic_offset++]) {
308                         skipped_bytes += magic_offset;
309                         magic_offset = 0;
310                         continue;
311                 }
312                 if (magic_offset < frame_magic_len) {
313                         // Still reading the magic (hopefully).
314                         continue;
315                 }
316
317                 // OK, found the magic. Try to parse the frame header.
318                 magic_offset = 0;
319
320                 if (skipped_bytes > 0)  {
321                         fprintf(stderr, "WARNING: %s: Skipped %zu garbage bytes in the middle.\n",
322                                 filename, skipped_bytes);
323                         skipped_bytes = 0;
324                 }
325
326                 uint32_t len;
327                 if (fread(&len, sizeof(len), 1, fp) != 1) {
328                         fprintf(stderr, "WARNING: %s: Short read when getting length.\n", filename);
329                         break;
330                 }
331
332                 string serialized;
333                 serialized.resize(ntohl(len));
334                 if (fread(&serialized[0], serialized.size(), 1, fp) != 1) {
335                         fprintf(stderr, "WARNING: %s: Short read when reading frame header (%zu bytes).\n", filename, serialized.size());
336                         break;
337                 }
338
339                 FrameHeaderProto hdr;
340                 if (!hdr.ParseFromString(serialized)) {
341                         fprintf(stderr, "WARNING: %s: Corrupted frame header.\n", filename);
342                         continue;
343                 }
344
345                 FrameOnDisk frame;
346                 frame.pts = hdr.pts();
347                 frame.offset = ftell(fp);
348                 if (frame.offset == -1) {
349                         fprintf(stderr, "WARNING: %s: ftell() failed (%s).\n", filename, strerror(errno));
350                         break;
351                 }
352                 frame.filename_idx = filename_idx;
353                 frame.size = hdr.file_size();
354
355                 if (fseek(fp, frame.offset + frame.size, SEEK_SET) == -1) {
356                         fprintf(stderr, "WARNING: %s: Could not seek past frame (probably truncated).\n", filename);
357                         continue;
358                 }
359
360                 if (hdr.stream_idx() >= 0 && hdr.stream_idx() < MAX_STREAMS) {
361                         frames[hdr.stream_idx()].push_back(frame);
362                         start_pts = max(start_pts, hdr.pts());
363                 }
364                 all_frames.emplace_back(DB::FrameOnDiskAndStreamIdx{ frame, unsigned(hdr.stream_idx()) });
365         }
366
367         if (skipped_bytes > 0) {
368                 fprintf(stderr, "WARNING: %s: Skipped %zu garbage bytes at the end.\n",
369                         filename, skipped_bytes);
370         }
371
372         off_t size = ftell(fp);
373         fclose(fp);
374
375         if (size == -1) {
376                 fprintf(stderr, "WARNING: %s: ftell() failed (%s).\n", filename, strerror(errno));
377                 return;
378         }
379
380         db->store_frame_file(basename, size, all_frames);
381 }
382
383 void load_existing_frames()
384 {
385         QProgressDialog progress("Scanning frame directory...", "Abort", 0, 1);
386         progress.setWindowTitle("Futatabi");
387         progress.setWindowModality(Qt::WindowModal);
388         progress.setMinimumDuration(1000);
389         progress.setMaximum(1);
390         progress.setValue(0);
391
392         string frame_dir = global_flags.working_directory + "/frames";
393         DIR *dir = opendir(frame_dir.c_str());
394         if (dir == nullptr) {
395                 perror("frames/");
396                 start_pts = 0;
397                 return;
398         }
399
400         vector<string> frame_basenames;
401         for ( ;; ) {
402                 errno = 0;
403                 dirent *de = readdir(dir);
404                 if (de == nullptr) {
405                         if (errno != 0) {
406                                 perror("readdir");
407                                 exit(1);
408                         }
409                         break;
410                 }
411
412                 if (de->d_type == DT_REG || de->d_type == DT_LNK) {
413                         string filename = frame_dir + "/" + de->d_name;
414                         frame_filenames.push_back(filename);
415                         frame_basenames.push_back(de->d_name);
416                 }
417
418                 if (progress.wasCanceled()) {
419                         exit(1);
420                 }
421         }
422         closedir(dir);
423
424         progress.setMaximum(frame_filenames.size() + 2);
425         progress.setValue(1);
426
427         progress.setLabelText("Opening database...");
428         DB db(global_flags.working_directory + "/futatabi.db");
429
430         progress.setLabelText("Reading frame files...");
431         progress.setValue(2);
432
433         for (size_t i = 0; i < frame_filenames.size(); ++i) {
434                 load_frame_file(frame_filenames[i].c_str(), frame_basenames[i], i, &db);
435                 progress.setValue(i + 3);
436                 if (progress.wasCanceled()) {
437                         exit(1);
438                 }
439         }
440
441         if (start_pts == -1) {
442                 start_pts = 0;
443         } else {
444                 // Add a gap of one second from the old frames to the new ones.
445                 start_pts += TIMEBASE;
446         }
447         current_pts = start_pts;
448
449         for (int stream_idx = 0; stream_idx < MAX_STREAMS; ++stream_idx) {
450                 sort(frames[stream_idx].begin(), frames[stream_idx].end(),
451                         [](const auto &a, const auto &b) { return a.pts < b.pts; });
452         }
453
454         db.clean_unused_frame_files(frame_basenames);
455 }
456
457 void record_thread_func()
458 {
459         for (unsigned i = 0; i < MAX_STREAMS; ++i) {
460                 global_metrics.add("received_frames", {{ "stream", to_string(i) }}, &metric_received_frames[i]);
461         }
462
463         if (global_flags.stream_source.empty() || global_flags.stream_source == "/dev/null") {
464                 // Save the user from some repetitive messages.
465                 return;
466         }
467
468         pthread_setname_np(pthread_self(), "ReceiveFrames");
469
470         int64_t pts_offset = 0;  // Needs to be initialized due to a spurious GCC warning.
471         DB db(global_flags.working_directory + "/futatabi.db");
472
473         while (!should_quit.load()) {
474                 auto format_ctx = avformat_open_input_unique(global_flags.stream_source.c_str(), nullptr, nullptr);
475                 if (format_ctx == nullptr) {
476                         fprintf(stderr, "%s: Error opening file. Waiting one second and trying again...\n", global_flags.stream_source.c_str());
477                         sleep(1);
478                         continue;
479                 }
480
481                 int64_t last_pts = -1;
482
483                 while (!should_quit.load()) {
484                         AVPacket pkt;
485                         unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
486                                 &pkt, av_packet_unref);
487                         av_init_packet(&pkt);
488                         pkt.data = nullptr;
489                         pkt.size = 0;
490
491                         // TODO: Make it possible to abort av_read_frame() (use an interrupt callback);
492                         // right now, should_quit will be ignored if it's hung on I/O.
493                         if (av_read_frame(format_ctx.get(), &pkt) != 0) {
494                                 break;
495                         }
496                         if (pkt.stream_index >= MAX_STREAMS) {
497                                 continue;
498                         }
499
500                         ++metric_received_frames[pkt.stream_index];
501
502                         // Convert pts to our own timebase.
503                         AVRational stream_timebase = format_ctx->streams[pkt.stream_index]->time_base;
504                         int64_t pts = av_rescale_q(pkt.pts, stream_timebase, AVRational{ 1, TIMEBASE });
505
506                         // Translate offset into our stream.
507                         if (last_pts == -1) {
508                                 pts_offset = start_pts - pts;
509                         }
510                         pts = std::max(pts + pts_offset, start_pts);
511
512                         //fprintf(stderr, "Got a frame from camera %d, pts = %ld, size = %d\n",
513                         //      pkt.stream_index, pts, pkt.size);
514                         FrameOnDisk frame = write_frame(pkt.stream_index, pts, pkt.data, pkt.size, &db);
515
516                         post_to_main_thread([pkt, frame] {
517                                 global_mainwindow->display_frame(pkt.stream_index, frame);
518                         });
519
520                         if (last_pts != -1 && global_flags.slow_down_input) {
521                                 this_thread::sleep_for(microseconds((pts - last_pts) * 1000000 / TIMEBASE));
522                         }
523                         last_pts = pts;
524                         current_pts = pts;
525                 }
526
527                 fprintf(stderr, "%s: Hit EOF. Waiting one second and trying again...\n", global_flags.stream_source.c_str());
528                 sleep(1);
529
530                 start_pts = last_pts + TIMEBASE;
531         }
532 }