]> git.sesse.net Git - nageru/blob - nageru/mjpeg_encoder.h
Use vaCreateImage + vaPutImage instead of vaDeriveImage.
[nageru] / nageru / mjpeg_encoder.h
1 #ifndef _MJPEG_ENCODER_H
2 #define _MJPEG_ENCODER_H 1
3
4 #include "shared/ffmpeg_raii.h"
5 #include "ref_counted_frame.h"
6
7 extern "C" {
8
9 #include <libavformat/avio.h>
10
11 }  // extern "C"
12
13 #include <atomic>
14 #include <bmusb/bmusb.h>
15 #include <condition_variable>
16 #include <list>
17 #include <mutex>
18 #include <queue>
19 #include <stdint.h>
20 #include <string>
21 #include <thread>
22
23 #include <va/va.h>
24
25 class HTTPD;
26 struct jpeg_compress_struct;
27 struct VADisplayWithCleanup;
28 struct VectorDestinationManager;
29
30 #define CHECK_VASTATUS(va_status, func)                                 \
31     if (va_status != VA_STATUS_SUCCESS) {                               \
32         fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
33         exit(1);                                                        \
34     }
35
36 class MJPEGEncoder {
37 public:
38         MJPEGEncoder(HTTPD *httpd, const std::string &va_display);
39         ~MJPEGEncoder();
40         void stop();
41         void upload_frame(int64_t pts, unsigned card_index, RefCountedFrame frame, const bmusb::VideoFormat &video_format, size_t y_offset, size_t cbcr_offset);
42
43         // If the frame was started (data_copy != nullptr) but will not be finished
44         // (MJPEG decoding was turned off in the meantime), you'll need to call finish_frame()
45         // to release any VA-API resources.
46         void finish_frame(RefCountedFrame frame);
47
48         bool using_vaapi() const { return va_dpy != nullptr; }
49
50         // Returns -1 for inactive (ie., don't encode frames for this card right now).
51         int get_mjpeg_stream_for_card(unsigned card_index);
52
53 private:
54         static constexpr int quality = 90;
55
56         struct VAResources {
57                 unsigned width, height;
58                 VASurfaceID surface;
59                 VAContextID context;
60                 VABufferID data_buffer;
61                 VAImage image;
62         };
63
64         // RAII wrapper to release VAResources on return (even on error).
65         class ReleaseVAResources {
66         public:
67                 ReleaseVAResources() : committed(true) {}
68
69                 ReleaseVAResources(MJPEGEncoder *mjpeg, const VAResources &resources)
70                         : mjpeg(mjpeg), resources(resources) {}
71
72                 ReleaseVAResources(ReleaseVAResources &) = delete;
73
74                 ReleaseVAResources(ReleaseVAResources &&other)
75                         : mjpeg(other.mjpeg), resources(other.resources), committed(other.committed) {
76                         other.commit();
77                 }
78
79                 ReleaseVAResources &operator= (ReleaseVAResources &) = delete;
80
81                 ReleaseVAResources &operator= (ReleaseVAResources &&other) {
82                         if (!committed) {
83                                 mjpeg->release_va_resources(resources);
84                         }
85                         mjpeg = other.mjpeg;
86                         resources = std::move(other.resources);
87                         committed = other.committed;
88                         other.commit();
89                         return *this;
90                 }
91
92                 ~ReleaseVAResources()
93                 {
94                         if (!committed) {
95                                 mjpeg->release_va_resources(resources);
96                         }
97                 }
98
99                 void commit() { committed = true; }
100
101         private:
102                 MJPEGEncoder *mjpeg = nullptr;
103                 VAResources resources;
104                 bool committed = false;
105         };
106
107         struct QueuedFrame {
108                 int64_t pts;
109                 unsigned card_index;
110                 RefCountedFrame frame;
111                 bmusb::VideoFormat video_format;
112                 size_t y_offset, cbcr_offset;
113
114                 // Only for frames in the process of being encoded by VA-API.
115                 VAResources resources;
116                 ReleaseVAResources resource_releaser;
117         };
118
119         void encoder_thread_func();
120         void va_receiver_thread_func();
121         void encode_jpeg_va(QueuedFrame &&qf);
122         std::vector<uint8_t> encode_jpeg_libjpeg(const QueuedFrame &qf);
123         void write_mjpeg_packet(int64_t pts, unsigned card_index, const uint8_t *jpeg, size_t jpeg_size);
124         void init_jpeg_422(unsigned width, unsigned height, VectorDestinationManager *dest, jpeg_compress_struct *cinfo);
125         std::vector<uint8_t> get_jpeg_header(unsigned width, unsigned height, jpeg_compress_struct *cinfo);
126
127         static int write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time);
128         int write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time);
129
130         std::thread encoder_thread, va_receiver_thread;
131
132         std::mutex mu;
133         std::queue<QueuedFrame> frames_to_be_encoded;  // Under mu.
134         std::condition_variable any_frames_to_be_encoded;  // Governs changes in both frames_to_be_encoded and frames_under_encoding
135
136         std::queue<QueuedFrame> frames_encoding;  // Under mu. Used for VA-API only.
137         std::condition_variable any_frames_encoding;
138
139         AVFormatContextWithCloser avctx;
140         HTTPD *httpd;
141         std::string mux_header;
142         std::atomic<bool> should_quit{false};
143         bool running = false;
144
145         std::unique_ptr<VADisplayWithCleanup> va_dpy;
146         VAConfigID config_id;
147
148         struct VAData {
149                 std::vector<uint8_t> jpeg_header;
150                 VAEncPictureParameterBufferJPEG pic_param;
151                 VAQMatrixBufferJPEG q;
152                 VAHuffmanTableBufferJPEGBaseline huff;
153                 VAEncSliceParameterBufferJPEG parms;
154         };
155         std::map<std::pair<unsigned, unsigned>, VAData> va_data_for_resolution;
156         VAData get_va_data_for_resolution(unsigned width, unsigned height);
157
158         std::list<VAResources> va_resources_freelist;
159         std::mutex va_resources_mutex;
160         VAResources get_va_resources(unsigned width, unsigned height);
161         void release_va_resources(VAResources resources);
162
163         static std::unique_ptr<VADisplayWithCleanup> try_open_va(const std::string &va_display, std::string *error, VAConfigID *config_id);
164
165         uint8_t *tmp_y, *tmp_cbcr, *tmp_cb, *tmp_cr;  // Private to the encoder thread. Used by the libjpeg backend only.
166
167         std::atomic<int64_t> metric_mjpeg_frames_zero_size_dropped{0};
168         std::atomic<int64_t> metric_mjpeg_frames_interlaced_dropped{0};
169         std::atomic<int64_t> metric_mjpeg_frames_unsupported_pixel_format_dropped{0};
170         std::atomic<int64_t> metric_mjpeg_frames_oversized_dropped{0};
171         std::atomic<int64_t> metric_mjpeg_overrun_dropped{0};
172         std::atomic<int64_t> metric_mjpeg_overrun_submitted{0};
173
174         friend class PBOFrameAllocator;  // FIXME
175 };
176
177 #endif  // !defined(_MJPEG_ENCODER_H)