]> git.sesse.net Git - nageru/blob - main.cpp
Throw up some widgets.
[nageru] / main.cpp
1 #include <assert.h>
2 #include <stdio.h>
3 #include <stdint.h>
4
5 #include <chrono>
6 #include <memory>
7 #include <mutex>
8 #include <string>
9 #include <thread>
10 #include <vector>
11
12 extern "C" {
13 #include <libavformat/avformat.h>
14 }
15
16 #include <QApplication>
17
18 #include "mainwindow.h"
19 #include "ffmpeg_raii.h"
20
21 #define MAX_STREAMS 16
22
23 using namespace std;
24 using namespace std::chrono;
25
26 string filename_for_frame(unsigned stream_idx, int64_t pts)
27 {
28         char filename[256];
29         snprintf(filename, sizeof(filename), "frames/cam%d-pts%09ld.jpeg", stream_idx, pts);
30         return filename;
31 }
32
33 mutex frame_mu;
34 vector<int64_t> frames[MAX_STREAMS];
35
36 int thread_func();
37
38 int main(int argc, char **argv)
39 {
40         av_register_all();
41         avformat_network_init();
42
43         QApplication app(argc, argv);
44         MainWindow mainWindow;
45         mainWindow.show();
46
47         thread(thread_func).detach();
48
49         return app.exec();
50 }
51
52 int thread_func()
53 {
54         auto format_ctx = avformat_open_input_unique("example.mp4", nullptr, nullptr);
55         if (format_ctx == nullptr) {
56                 fprintf(stderr, "%s: Error opening file\n", "example.mp4");
57                 return 1;
58         }
59
60         for ( ;; ) {
61                 AVPacket pkt;
62                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
63                         &pkt, av_packet_unref);
64                 av_init_packet(&pkt);
65                 pkt.data = nullptr;
66                 pkt.size = 0;
67                 if (av_read_frame(format_ctx.get(), &pkt) != 0) {
68                         break;
69                 }
70                 fprintf(stderr, "Got a frame from camera %d, pts = %ld, size = %d\n",
71                         pkt.stream_index, pkt.pts, pkt.size);
72                 string filename = filename_for_frame(pkt.stream_index, pkt.pts);
73                 FILE *fp = fopen(filename.c_str(), "wb");
74                 if (fp == nullptr) {
75                         perror(filename.c_str());
76                         exit(1);
77                 }
78                 fwrite(pkt.data, pkt.size, 1, fp);
79                 fclose(fp);
80
81                 assert(pkt.stream_index < MAX_STREAMS);
82                 frames[pkt.stream_index].push_back(pkt.pts);
83
84                 this_thread::sleep_for(milliseconds(1000) / 120);
85         }
86
87         return 0;
88 }