]> git.sesse.net Git - nageru/blob - main.cpp
Make it possible to change the working directory.
[nageru] / main.cpp
1 #include <assert.h>
2 #include <atomic>
3 #include <chrono>
4 #include <condition_variable>
5 #include <dirent.h>
6 #include <getopt.h>
7 #include <memory>
8 #include <mutex>
9 #include <stdint.h>
10 #include <stdio.h>
11 #include <string>
12 #include <sys/types.h>
13 #include <thread>
14 #include <vector>
15
16 extern "C" {
17 #include <libavformat/avformat.h>
18 }
19
20 #include "clip_list.h"
21 #include "context.h"
22 #include "defs.h"
23 #include "disk_space_estimator.h"
24 #include "ffmpeg_raii.h"
25 #include "flags.h"
26 #include "httpd.h"
27 #include "mainwindow.h"
28 #include "player.h"
29 #include "post_to_main_thread.h"
30 #include "ref_counted_gl_sync.h"
31 #include "timebase.h"
32 #include "ui_mainwindow.h"
33 #include "vaapi_jpeg_decoder.h"
34
35 #include <QApplication>
36 #include <movit/init.h>
37 #include <movit/util.h>
38
39 using namespace std;
40 using namespace std::chrono;
41
42 mutex RefCountedGLsync::fence_lock;
43 atomic<bool> should_quit{false};
44
45 int64_t start_pts = -1;
46
47 // TODO: Replace by some sort of GUI control, I guess.
48 int64_t current_pts = 0;
49
50 string filename_for_frame(unsigned stream_idx, int64_t pts)
51 {
52         char filename[256];
53         snprintf(filename, sizeof(filename), "%s/frames/cam%d-pts%09ld.jpeg",
54                 global_flags.working_directory.c_str(), stream_idx, pts);
55         return filename;
56 }
57
58 mutex frame_mu;
59 vector<int64_t> frames[MAX_STREAMS];
60 HTTPD *global_httpd;
61
62 void load_existing_frames();
63 int record_thread_func();
64
65 int main(int argc, char **argv)
66 {
67         parse_flags(argc, argv);
68         if (optind == argc) {
69                 global_flags.stream_source = "multiangle.mp4";
70                 global_flags.slow_down_input = true;
71         } else if (optind + 1 == argc) {
72                 global_flags.stream_source = argv[optind];
73         } else {
74                 usage();
75                 exit(1);
76         }
77
78         avformat_network_init();
79         global_httpd = new HTTPD;
80
81         QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
82
83         QSurfaceFormat fmt;
84         fmt.setDepthBufferSize(0);
85         fmt.setStencilBufferSize(0);
86         fmt.setProfile(QSurfaceFormat::CoreProfile);
87         fmt.setMajorVersion(4);
88         fmt.setMinorVersion(5);
89
90         // Turn off vsync, since Qt generally gives us at most frame rate
91         // (display frequency) / (number of QGLWidgets active).
92         fmt.setSwapInterval(0);
93
94         QSurfaceFormat::setDefaultFormat(fmt);
95
96         QGLFormat::setDefaultFormat(QGLFormat::fromSurfaceFormat(fmt));
97
98         QApplication app(argc, argv);
99         global_share_widget = new QGLWidget();
100         if (!global_share_widget->isValid()) {
101                 fprintf(stderr, "Failed to initialize OpenGL. Futatabi needs at least OpenGL 4.5 to function properly.\n");
102                 exit(1);
103         }
104
105         // Initialize Movit.
106         {
107                 QSurface *surface = create_surface();
108                 QOpenGLContext *context = create_context(surface);
109                 make_current(context, surface);
110                 CHECK(movit::init_movit(MOVIT_SHADER_DIR, movit::MOVIT_DEBUG_OFF));
111                 delete_context(context);
112                 // TODO: Delete the surface, too.
113         }
114
115         MainWindow main_window;
116         main_window.show();
117
118         global_httpd->add_endpoint("/queue_status", bind(&MainWindow::get_queue_status, &main_window), HTTPD::NO_CORS_POLICY);
119         global_httpd->start(DEFAULT_HTTPD_PORT);
120
121         init_jpeg_vaapi();
122
123         load_existing_frames();
124         thread record_thread(record_thread_func);
125
126         int ret = app.exec();
127
128         should_quit = true;
129         record_thread.join();
130         JPEGFrameView::shutdown();
131
132         return ret;
133 }
134
135 void load_existing_frames()
136 {
137         DIR *dir = opendir("frames/");
138         if (dir == nullptr) {
139                 perror("frames/");
140                 start_pts = 0;
141                 return;
142         }
143
144         for ( ;; ) {
145                 errno = 0;
146                 dirent *de = readdir(dir);
147                 if (de == nullptr) {
148                         if (errno != 0) {
149                                 perror("readdir");
150                                 exit(1);
151                         }
152                         break;
153                 }
154
155                 int stream_idx;
156                 int64_t pts;
157                 if (sscanf(de->d_name, "cam%d-pts%ld.jpeg", &stream_idx, &pts) == 2 &&
158                     stream_idx >= 0 && stream_idx < MAX_STREAMS) {
159                         frames[stream_idx].push_back(pts);
160                         start_pts = max(start_pts, pts);
161                 }
162         }
163
164         closedir(dir);
165
166         if (start_pts == -1) {
167                 start_pts = 0;
168         } else {
169                 // Add a gap of one second from the old frames to the new ones.
170                 start_pts += TIMEBASE;
171         }
172
173         for (int stream_idx = 0; stream_idx < MAX_STREAMS; ++stream_idx) {
174                 sort(frames[stream_idx].begin(), frames[stream_idx].end());
175         }
176 }
177
178 int record_thread_func()
179 {
180         auto format_ctx = avformat_open_input_unique(global_flags.stream_source.c_str(), nullptr, nullptr);
181         if (format_ctx == nullptr) {
182                 fprintf(stderr, "%s: Error opening file\n", global_flags.stream_source.c_str());
183                 return 1;
184         }
185
186         int64_t last_pts = -1;
187         int64_t pts_offset;
188
189         while (!should_quit.load()) {
190                 AVPacket pkt;
191                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
192                         &pkt, av_packet_unref);
193                 av_init_packet(&pkt);
194                 pkt.data = nullptr;
195                 pkt.size = 0;
196
197                 // TODO: Make it possible to abort av_read_frame() (use an interrupt callback);
198                 // right now, should_quit will be ignored if it's hung on I/O.
199                 if (av_read_frame(format_ctx.get(), &pkt) != 0) {
200                         break;
201                 }
202
203                 // Convert pts to our own timebase.
204                 AVRational stream_timebase = format_ctx->streams[pkt.stream_index]->time_base;
205                 int64_t pts = av_rescale_q(pkt.pts, stream_timebase, AVRational{ 1, TIMEBASE });
206
207                 // Translate offset into our stream.
208                 if (last_pts == -1) {
209                         pts_offset = start_pts - pts;
210                 }
211                 pts = std::max(pts + pts_offset, start_pts);
212
213                 //fprintf(stderr, "Got a frame from camera %d, pts = %ld, size = %d\n",
214                 //      pkt.stream_index, pts, pkt.size);
215                 string filename = filename_for_frame(pkt.stream_index, pts);
216                 FILE *fp = fopen(filename.c_str(), "wb");
217                 if (fp == nullptr) {
218                         perror(filename.c_str());
219                         exit(1);
220                 }
221                 fwrite(pkt.data, pkt.size, 1, fp);
222                 fclose(fp);
223
224                 global_disk_space_estimator->report_write(filename, pts);
225
226                 post_to_main_thread([pkt, pts] {
227                         if (pkt.stream_index == 0) {
228                                 global_mainwindow->ui->input1_display->setFrame(pkt.stream_index, pts, /*interpolated=*/false);
229                         } else if (pkt.stream_index == 1) {
230                                 global_mainwindow->ui->input2_display->setFrame(pkt.stream_index, pts, /*interpolated=*/false);
231                         } else if (pkt.stream_index == 2) {
232                                 global_mainwindow->ui->input3_display->setFrame(pkt.stream_index, pts, /*interpolated=*/false);
233                         } else if (pkt.stream_index == 3) {
234                                 global_mainwindow->ui->input4_display->setFrame(pkt.stream_index, pts, /*interpolated=*/false);
235                         }
236                 });
237
238                 assert(pkt.stream_index < MAX_STREAMS);
239                 frames[pkt.stream_index].push_back(pts);
240
241                 if (last_pts != -1 && global_flags.slow_down_input) {
242                         this_thread::sleep_for(microseconds((pts - last_pts) * 1000000 / TIMEBASE));
243                 }
244                 last_pts = pts;
245                 current_pts = pts;
246         }
247
248         return 0;
249 }