5 #include <condition_variable>
14 #include <sys/types.h>
20 #include <libavformat/avformat.h>
23 #include "clip_list.h"
24 #include "shared/context.h"
26 #include "shared/disk_space_estimator.h"
27 #include "shared/ffmpeg_raii.h"
29 #include "frame_on_disk.h"
31 #include "shared/httpd.h"
32 #include "mainwindow.h"
34 #include "shared/post_to_main_thread.h"
35 #include "shared/ref_counted_gl_sync.h"
36 #include "shared/timebase.h"
37 #include "ui_mainwindow.h"
38 #include "vaapi_jpeg_decoder.h"
40 #include <QApplication>
42 #include <QSurfaceFormat>
43 #include <QProgressDialog>
44 #include <movit/init.h>
45 #include <movit/util.h>
48 using namespace std::chrono;
50 constexpr char frame_magic[] = "Ftbifrm0";
51 constexpr size_t frame_magic_len = 8;
53 mutex RefCountedGLsync::fence_lock;
54 atomic<bool> should_quit{false};
56 int64_t start_pts = -1;
58 // TODO: Replace by some sort of GUI control, I guess.
59 int64_t current_pts = 0;
63 unsigned filename_idx;
64 size_t frames_written_so_far = 0;
66 std::map<int, FrameFile> open_frame_files;
69 vector<FrameOnDisk> frames[MAX_STREAMS]; // Under frame_mu.
70 vector<string> frame_filenames; // Under frame_mu.
74 FrameOnDisk write_frame(int stream_idx, int64_t pts, const uint8_t *data, size_t size, DB *db)
76 if (open_frame_files.count(stream_idx) == 0) {
78 snprintf(filename, sizeof(filename), "%s/frames/cam%d-pts%09ld.frames",
79 global_flags.working_directory.c_str(), stream_idx, pts);
80 FILE *fp = fopen(filename, "wb");
86 lock_guard<mutex> lock(frame_mu);
87 unsigned filename_idx = frame_filenames.size();
88 frame_filenames.push_back(filename);
89 open_frame_files[stream_idx] = FrameFile{ fp, filename_idx, 0 };
92 FrameFile &file = open_frame_files[stream_idx];
93 unsigned filename_idx = file.filename_idx;
96 lock_guard<mutex> lock(frame_mu);
97 filename = frame_filenames[filename_idx];
100 FrameHeaderProto hdr;
101 hdr.set_stream_idx(stream_idx);
103 hdr.set_file_size(size);
106 if (!hdr.SerializeToString(&serialized)) {
107 fprintf(stderr, "Frame header serialization failed.\n");
110 uint32_t len = htonl(serialized.size());
112 if (fwrite(frame_magic, frame_magic_len, 1, file.fp) != 1) {
116 if (fwrite(&len, sizeof(len), 1, file.fp) != 1) {
120 if (fwrite(serialized.data(), serialized.size(), 1, file.fp) != 1) {
124 off_t offset = ftell(file.fp);
125 if (fwrite(data, size, 1, file.fp) != 1) {
129 fflush(file.fp); // No fsync(), though. We can accept losing a few frames.
130 global_disk_space_estimator->report_write(filename, 8 + sizeof(len) + serialized.size() + size, pts);
134 frame.filename_idx = filename_idx;
135 frame.offset = offset;
139 lock_guard<mutex> lock(frame_mu);
140 assert(stream_idx < MAX_STREAMS);
141 frames[stream_idx].push_back(frame);
144 if (++file.frames_written_so_far >= 1000) {
145 size_t size = ftell(file.fp);
147 // Start a new file next time.
148 if (fclose(file.fp) != 0) {
152 open_frame_files.erase(stream_idx);
154 // Write information about all frames in the finished file to SQLite.
155 // (If we crash before getting to do this, we'll be scanning through
156 // the file on next startup, and adding it to the database then.)
157 // NOTE: Since we don't fsync(), we could in theory get broken data
158 // but with the right size, but it would seem unlikely.
159 vector<DB::FrameOnDiskAndStreamIdx> frames_this_file;
161 lock_guard<mutex> lock(frame_mu);
162 for (size_t stream_idx = 0; stream_idx < MAX_STREAMS; ++stream_idx) {
163 for (const FrameOnDisk &frame : frames[stream_idx]) {
164 if (frame.filename_idx == filename_idx) {
165 frames_this_file.emplace_back(DB::FrameOnDiskAndStreamIdx{ frame, unsigned(stream_idx) });
171 const char *basename = filename.c_str();
172 while (strchr(basename, '/') != nullptr) {
173 basename = strchr(basename, '/') + 1;
175 db->store_frame_file(basename, size, frames_this_file);
185 void load_existing_frames();
186 int record_thread_func();
188 int main(int argc, char **argv)
190 parse_flags(argc, argv);
191 if (optind == argc) {
192 global_flags.stream_source = "multiangle.mp4";
193 global_flags.slow_down_input = true;
194 } else if (optind + 1 == argc) {
195 global_flags.stream_source = argv[optind];
201 string frame_dir = global_flags.working_directory + "/frames";
204 if (stat(frame_dir.c_str(), &st) == -1) {
205 fprintf(stderr, "%s does not exist, creating it.\n", frame_dir.c_str());
206 if (mkdir(frame_dir.c_str(), 0777) == -1) {
207 perror(global_flags.working_directory.c_str());
212 avformat_network_init();
213 global_httpd = new HTTPD;
215 QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
218 fmt.setDepthBufferSize(0);
219 fmt.setStencilBufferSize(0);
220 fmt.setProfile(QSurfaceFormat::CoreProfile);
221 fmt.setMajorVersion(4);
222 fmt.setMinorVersion(5);
224 // Turn off vsync, since Qt generally gives us at most frame rate
225 // (display frequency) / (number of QGLWidgets active).
226 fmt.setSwapInterval(0);
228 QSurfaceFormat::setDefaultFormat(fmt);
230 QGLFormat::setDefaultFormat(QGLFormat::fromSurfaceFormat(fmt));
232 QApplication app(argc, argv);
233 global_share_widget = new QGLWidget();
234 if (!global_share_widget->isValid()) {
235 fprintf(stderr, "Failed to initialize OpenGL. Futatabi needs at least OpenGL 4.5 to function properly.\n");
241 QSurface *surface = create_surface();
242 QOpenGLContext *context = create_context(surface);
243 make_current(context, surface);
244 CHECK(movit::init_movit(MOVIT_SHADER_DIR, movit::MOVIT_DEBUG_OFF));
245 delete_context(context);
246 // TODO: Delete the surface, too.
249 load_existing_frames();
251 MainWindow main_window;
254 global_httpd->add_endpoint("/queue_status", bind(&MainWindow::get_queue_status, &main_window), HTTPD::NO_CORS_POLICY);
255 global_httpd->start(global_flags.http_port);
259 thread record_thread(record_thread_func);
261 int ret = app.exec();
264 record_thread.join();
265 JPEGFrameView::shutdown();
270 void load_frame_file(const char *filename, const string &basename, unsigned filename_idx, DB *db)
273 if (stat(filename, &st) == -1) {
278 vector<DB::FrameOnDiskAndStreamIdx> all_frames = db->load_frame_file(basename, st.st_size, filename_idx);
279 if (!all_frames.empty()) {
280 // We already had this cached in the database, so no need to look in the file.
281 for (const DB::FrameOnDiskAndStreamIdx &frame : all_frames) {
282 if (frame.stream_idx >= 0 && frame.stream_idx < MAX_STREAMS) {
283 frames[frame.stream_idx].push_back(frame.frame);
284 start_pts = max(start_pts, frame.frame.pts);
290 FILE *fp = fopen(filename, "rb");
296 size_t magic_offset = 0;
297 size_t skipped_bytes = 0;
298 while (!feof(fp) && !ferror(fp)) {
303 if (ch != frame_magic[magic_offset++]) {
304 skipped_bytes += magic_offset;
308 if (magic_offset < frame_magic_len) {
309 // Still reading the magic (hopefully).
313 // OK, found the magic. Try to parse the frame header.
316 if (skipped_bytes > 0) {
317 fprintf(stderr, "WARNING: %s: Skipped %zu garbage bytes in the middle.\n",
318 filename, skipped_bytes);
323 if (fread(&len, sizeof(len), 1, fp) != 1) {
324 fprintf(stderr, "WARNING: %s: Short read when getting length.\n", filename);
329 serialized.resize(ntohl(len));
330 if (fread(&serialized[0], serialized.size(), 1, fp) != 1) {
331 fprintf(stderr, "WARNING: %s: Short read when reading frame header (%zu bytes).\n", filename, serialized.size());
335 FrameHeaderProto hdr;
336 if (!hdr.ParseFromString(serialized)) {
337 fprintf(stderr, "WARNING: %s: Corrupted frame header.\n", filename);
342 frame.pts = hdr.pts();
343 frame.offset = ftell(fp);
344 frame.filename_idx = filename_idx;
345 frame.size = hdr.file_size();
347 if (fseek(fp, frame.offset + frame.size, SEEK_SET) == -1) {
348 fprintf(stderr, "WARNING: %s: Could not seek past frame (probably truncated).\n", filename);
352 if (hdr.stream_idx() >= 0 && hdr.stream_idx() < MAX_STREAMS) {
353 frames[hdr.stream_idx()].push_back(frame);
354 start_pts = max(start_pts, hdr.pts());
356 all_frames.emplace_back(DB::FrameOnDiskAndStreamIdx{ frame, unsigned(hdr.stream_idx()) });
359 if (skipped_bytes > 0) {
360 fprintf(stderr, "WARNING: %s: Skipped %zu garbage bytes at the end.\n",
361 filename, skipped_bytes);
364 size_t size = ftell(fp);
367 db->store_frame_file(basename, size, all_frames);
370 void load_existing_frames()
372 QProgressDialog progress("Scanning frame directory...", "Abort", 0, 1);
373 progress.setWindowTitle("Futatabi");
374 progress.setWindowModality(Qt::WindowModal);
375 progress.setMinimumDuration(1000);
376 progress.setMaximum(1);
377 progress.setValue(0);
379 string frame_dir = global_flags.working_directory + "/frames";
380 DIR *dir = opendir(frame_dir.c_str());
381 if (dir == nullptr) {
387 vector<string> frame_basenames;
390 dirent *de = readdir(dir);
399 if (de->d_type == DT_REG || de->d_type == DT_LNK) {
400 string filename = frame_dir + "/" + de->d_name;
401 frame_filenames.push_back(filename);
402 frame_basenames.push_back(de->d_name);
405 if (progress.wasCanceled()) {
411 progress.setMaximum(frame_filenames.size() + 2);
412 progress.setValue(1);
414 progress.setLabelText("Opening database...");
415 DB db(global_flags.working_directory + "/futatabi.db");
417 progress.setLabelText("Reading frame files...");
418 progress.setValue(2);
420 for (size_t i = 0; i < frame_filenames.size(); ++i) {
421 load_frame_file(frame_filenames[i].c_str(), frame_basenames[i], i, &db);
422 progress.setValue(i + 3);
423 if (progress.wasCanceled()) {
428 if (start_pts == -1) {
431 // Add a gap of one second from the old frames to the new ones.
432 start_pts += TIMEBASE;
434 current_pts = start_pts;
436 for (int stream_idx = 0; stream_idx < MAX_STREAMS; ++stream_idx) {
437 sort(frames[stream_idx].begin(), frames[stream_idx].end(),
438 [](const auto &a, const auto &b) { return a.pts < b.pts; });
441 db.clean_unused_frame_files(frame_basenames);
444 int record_thread_func()
446 pthread_setname_np(pthread_self(), "ReceiveFrames");
449 DB db(global_flags.working_directory + "/futatabi.db");
451 while (!should_quit.load()) {
452 auto format_ctx = avformat_open_input_unique(global_flags.stream_source.c_str(), nullptr, nullptr);
453 if (format_ctx == nullptr) {
454 fprintf(stderr, "%s: Error opening file. Waiting one second and trying again...\n", global_flags.stream_source.c_str());
459 int64_t last_pts = -1;
461 while (!should_quit.load()) {
463 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
464 &pkt, av_packet_unref);
465 av_init_packet(&pkt);
469 // TODO: Make it possible to abort av_read_frame() (use an interrupt callback);
470 // right now, should_quit will be ignored if it's hung on I/O.
471 if (av_read_frame(format_ctx.get(), &pkt) != 0) {
475 // Convert pts to our own timebase.
476 AVRational stream_timebase = format_ctx->streams[pkt.stream_index]->time_base;
477 int64_t pts = av_rescale_q(pkt.pts, stream_timebase, AVRational{ 1, TIMEBASE });
479 // Translate offset into our stream.
480 if (last_pts == -1) {
481 pts_offset = start_pts - pts;
483 pts = std::max(pts + pts_offset, start_pts);
485 //fprintf(stderr, "Got a frame from camera %d, pts = %ld, size = %d\n",
486 // pkt.stream_index, pts, pkt.size);
487 FrameOnDisk frame = write_frame(pkt.stream_index, pts, pkt.data, pkt.size, &db);
489 post_to_main_thread([pkt, frame] {
490 global_mainwindow->display_frame(pkt.stream_index, frame);
493 if (last_pts != -1 && global_flags.slow_down_input) {
494 this_thread::sleep_for(microseconds((pts - last_pts) * 1000000 / TIMEBASE));
500 fprintf(stderr, "%s: Hit EOF. Waiting one second and trying again...\n", global_flags.stream_source.c_str());
503 start_pts = last_pts + TIMEBASE;