1 #ifndef _MJPEG_ENCODER_H
2 #define _MJPEG_ENCODER_H 1
4 #include "shared/ffmpeg_raii.h"
5 #include "ref_counted_frame.h"
9 #include <libavformat/avio.h>
14 #include <bmusb/bmusb.h>
15 #include <condition_variable>
26 struct jpeg_compress_struct;
27 struct VADisplayWithCleanup;
28 struct VectorDestinationManager;
32 MJPEGEncoder(HTTPD *httpd, const std::string &va_display);
35 void upload_frame(int64_t pts, unsigned card_index, RefCountedFrame frame, const bmusb::VideoFormat &video_format, size_t y_offset, size_t cbcr_offset);
38 static constexpr int quality = 90;
43 RefCountedFrame frame;
44 bmusb::VideoFormat video_format;
45 size_t y_offset, cbcr_offset;
48 void encoder_thread_func();
49 std::vector<uint8_t> encode_jpeg(const QueuedFrame &qf);
50 std::vector<uint8_t> encode_jpeg_va(const QueuedFrame &qf);
51 std::vector<uint8_t> encode_jpeg_libjpeg(const QueuedFrame &qf);
52 void init_jpeg_422(unsigned width, unsigned height, VectorDestinationManager *dest, jpeg_compress_struct *cinfo);
53 std::vector<uint8_t> get_jpeg_header(unsigned width, unsigned height, jpeg_compress_struct *cinfo);
55 static int write_packet2_thunk(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time);
56 int write_packet2(uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time);
58 std::thread encoder_thread;
61 std::queue<QueuedFrame> frames_to_be_encoded; // Under mu.
62 std::condition_variable any_frames_to_be_encoded;
64 std::queue<QueuedFrame> frames_encoding; // Under mu.
65 std::condition_variable any_frames_encoding;
67 AVFormatContextWithCloser avctx;
69 std::string mux_header;
70 std::atomic<bool> should_quit{false};
73 std::unique_ptr<VADisplayWithCleanup> va_dpy;
77 std::vector<uint8_t> jpeg_header;
78 VAEncPictureParameterBufferJPEG pic_param;
79 VAQMatrixBufferJPEG q;
80 VAHuffmanTableBufferJPEGBaseline huff;
81 VAEncSliceParameterBufferJPEG parms;
83 std::map<std::pair<unsigned, unsigned>, VAData> va_data_for_resolution;
84 VAData get_va_data_for_resolution(unsigned width, unsigned height);
87 unsigned width, height;
90 VABufferID data_buffer;
92 std::list<VAResources> va_resources_freelist;
93 std::mutex va_resources_mutex;
94 VAResources get_va_resources(unsigned width, unsigned height);
95 void release_va_resources(VAResources resources);
97 // RAII wrapper to release VAResources on return (even on error).
98 class ReleaseVAResources {
100 ReleaseVAResources(MJPEGEncoder *mjpeg, const VAResources &resources)
101 : mjpeg(mjpeg), resources(resources) {}
102 ~ReleaseVAResources()
105 mjpeg->release_va_resources(resources);
109 void commit() { committed = true; }
112 MJPEGEncoder * const mjpeg;
113 const VAResources &resources;
114 bool committed = false;
117 static std::unique_ptr<VADisplayWithCleanup> try_open_va(const std::string &va_display, std::string *error, VAConfigID *config_id);
119 uint8_t *tmp_y, *tmp_cbcr, *tmp_cb, *tmp_cr; // Private to the encoder thread.
122 #endif // !defined(_MJPEG_ENCODER_H)