-
- AVCodec *codec_audio = avcodec_find_encoder(AUDIO_OUTPUT_CODEC);
- avstream_audio = avformat_new_stream(avctx, codec_audio);
- if (avstream_audio == nullptr) {
- fprintf(stderr, "avformat_new_stream() failed\n");
- exit(1);
- }
- avstream_audio->time_base = AVRational{1, TIMEBASE};
- avstream_audio->codec->bit_rate = AUDIO_OUTPUT_BIT_RATE;
- avstream_audio->codec->sample_rate = OUTPUT_FREQUENCY;
- avstream_audio->codec->sample_fmt = AUDIO_OUTPUT_SAMPLE_FMT;
- avstream_audio->codec->channels = 2;
- avstream_audio->codec->channel_layout = AV_CH_LAYOUT_STEREO;
- avstream_audio->codec->time_base = AVRational{1, TIMEBASE};
- if (avctx->oformat->flags & AVFMT_GLOBALHEADER) {
- avstream_audio->codec->flags = AV_CODEC_FLAG_GLOBAL_HEADER;
- }
-
- AVDictionary *options = NULL;
- vector<pair<string, string>> opts = MUX_OPTS;
- for (pair<string, string> opt : opts) {
- av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
- }
- if (avformat_write_header(avctx, &options) < 0) {
- fprintf(stderr, "avformat_write_header() failed\n");
- exit(1);
- }
-}
-
-HTTPD::Mux::~Mux()
-{
- av_write_trailer(avctx);
- avformat_free_context(avctx);
-}
-
-void HTTPD::Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
-{
- if (!seen_keyframe && !(pkt.stream_index == 0 && (pkt.flags & AV_PKT_FLAG_KEY))) {
- // Wait until we see the first (video) key frame.
- return;
- }
- seen_keyframe = true;
-
- AVPacket pkt_copy;
- av_copy_packet(&pkt_copy, &pkt);
- if (pkt.stream_index == 0) {
- pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_video->time_base);
- pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_video->time_base);
- } else if (pkt.stream_index == 1) {
- pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
- pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
- } else {
- assert(false);
- }
-
- if (av_interleaved_write_frame(avctx, &pkt_copy) < 0) {
- fprintf(stderr, "av_interleaved_write_frame() failed\n");
- exit(1);
- }
-}
-
-HTTPD::Stream::Stream(AVOutputFormat *oformat, int width, int height)
-{
- AVFormatContext *avctx = avformat_alloc_context();
- avctx->oformat = oformat;
- uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
- avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, &HTTPD::Stream::write_packet_thunk, nullptr);
- avctx->flags = AVFMT_FLAG_CUSTOM_IO;
-
- mux.reset(new Mux(avctx, width, height));