]> git.sesse.net Git - nageru/blob - mux.h
Write 1.4.0 changelog.
[nageru] / mux.h
1 #ifndef _MUX_H
2 #define _MUX_H 1
3
4 // Wrapper around an AVFormat mux.
5
6 extern "C" {
7 #include <libavcodec/avcodec.h>
8 #include <libavformat/avformat.h>
9 }
10
11 #include <sys/types.h>
12 #include <functional>
13 #include <mutex>
14 #include <string>
15 #include <vector>
16
17 class Mux {
18 public:
19         enum Codec {
20                 CODEC_H264,
21                 CODEC_NV12,  // Uncompressed 4:2:0.
22         };
23
24         // Takes ownership of avctx. <write_callback> will be called every time
25         // a write has been made to the video stream (id 0), with the pts of
26         // the just-written frame. (write_callback can be nullptr.)
27         Mux(AVFormatContext *avctx, int width, int height, Codec video_codec, const std::string &video_extradata, const AVCodecParameters *audio_codecpar, int time_base, std::function<void(int64_t)> write_callback);
28         ~Mux();
29         void add_packet(const AVPacket &pkt, int64_t pts, int64_t dts);
30
31         // As long as the mux is plugged, it will not actually write anything to disk,
32         // just queue the packets. Once it is unplugged, the packets are reordered by pts
33         // and written. This is primarily useful if you might have two different encoders
34         // writing to the mux at the same time (because one is shutting down), so that
35         // pts might otherwise come out-of-order.
36         //
37         // You can plug and unplug multiple times; only when the plug count reaches zero,
38         // something will actually happen.
39         void plug();
40         void unplug();
41
42 private:
43         void write_packet_or_die(const AVPacket &pkt);  // Must be called with <mu> held.
44
45         std::mutex mu;
46         AVFormatContext *avctx;  // Protected by <mu>.
47         int plug_count = 0;  // Protected by <mu>.
48         std::vector<AVPacket *> plugged_packets;  // Protected by <mu>.
49
50         AVStream *avstream_video, *avstream_audio;
51
52         std::function<void(int64_t)> write_callback;
53 };
54
55 #endif  // !defined(_MUX_H)