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