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