]> git.sesse.net Git - nageru/blob - mux.h
When doing a cut, do the shutdown in a separate thread.
[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 #include <libavformat/avio.h>
10 }
11
12 #include <mutex>
13 #include <vector>
14
15 class KeyFrameSignalReceiver {
16 public:
17         // Needs to automatically turn the flag off again after actually receiving data.
18         virtual void signal_keyframe() = 0;
19 };
20
21 class Mux {
22 public:
23         enum Codec {
24                 CODEC_H264,
25                 CODEC_NV12,  // Uncompressed 4:2:0.
26         };
27
28         // Takes ownership of avctx. <keyframe_signal_receiver> can be nullptr.
29         Mux(AVFormatContext *avctx, int width, int height, Codec video_codec, const std::string &video_extradata, const AVCodecContext *audio_ctx, int time_base, KeyFrameSignalReceiver *keyframe_signal_receiver);
30         ~Mux();
31         void add_packet(const AVPacket &pkt, int64_t pts, int64_t dts);
32
33         // As long as the mux is plugged, it will not actually write anything to disk,
34         // just queue the packets. Once it is unplugged, the packets are reordered by pts
35         // and written. This is primarily useful if you might have two different encoders
36         // writing to the mux at the same time (because one is shutting down), so that
37         // pts might otherwise come out-of-order.
38         //
39         // You can plug and unplug multiple times; only when the plug count reaches zero,
40         // something will actually happen.
41         void plug();
42         void unplug();
43
44 private:
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         KeyFrameSignalReceiver *keyframe_signal_receiver;
52 };
53
54 #endif  // !defined(_MUX_H)