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