1 // Kaeru (換える), a simple transcoder intended for use with Nageru.
3 #include "audio_encoder.h"
4 #include "basic_stats.h"
7 #include "ffmpeg_capture.h"
9 #include "shared/mux.h"
10 #include "quittable_sleeper.h"
11 #include "shared/timebase.h"
12 #include "x264_encoder.h"
22 #include <libavcodec/bsf.h>
25 using namespace bmusb;
26 using namespace movit;
28 using namespace std::chrono;
29 using namespace std::placeholders;
31 Mixer *global_mixer = nullptr;
32 X264Encoder *global_x264_encoder = nullptr;
34 BasicStats *global_basic_stats = nullptr;
35 QuittableSleeper should_quit;
36 MuxMetrics stream_mux_metrics;
40 int write_packet(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
42 static bool seen_sync_markers = false;
43 static string stream_mux_header;
44 HTTPD *httpd = (HTTPD *)opaque;
46 if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
47 seen_sync_markers = true;
48 } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
49 // We don't know if this is a keyframe or not (the muxer could
50 // avoid marking it), so we just have to make the best of it.
51 type = AVIO_DATA_MARKER_SYNC_POINT;
54 HTTPD::StreamID stream_id{ HTTPD::MAIN_STREAM, 0 };
55 if (type == AVIO_DATA_MARKER_HEADER) {
56 stream_mux_header.append((char *)buf, buf_size);
57 httpd->set_header(stream_id, stream_mux_header);
59 httpd->add_data(stream_id, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
66 unique_ptr<Mux> create_mux(HTTPD *httpd, const AVOutputFormat *oformat, X264Encoder *x264_encoder, AudioEncoder *audio_encoder)
68 AVFormatContext *avctx = avformat_alloc_context();
69 avctx->oformat = const_cast<decltype(avctx->oformat)>(oformat); // const_cast is a hack to work in FFmpeg both before and after 5.0.
71 uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
72 avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, httpd, nullptr, nullptr, nullptr);
73 avctx->pb->write_data_type = &write_packet;
74 avctx->pb->ignore_boundary_point = 1;
75 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
77 string video_extradata = x264_encoder->get_global_headers();
79 // If audio is disabled (ie., we won't ever see any audio packets),
80 // set nullptr here to also not include the stream in the mux.
81 AVCodecParameters *audio_codecpar =
82 global_flags.enable_audio ? audio_encoder->get_codec_parameters().release() : nullptr;
85 mux.reset(new Mux(avctx, global_flags.width, global_flags.height, Mux::CODEC_H264, video_extradata, audio_codecpar,
86 get_color_space(global_flags.ycbcr_rec709_coefficients), COARSE_TIMEBASE,
87 /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, { &stream_mux_metrics }));
88 stream_mux_metrics.init({{ "destination", "http" }});
92 void video_frame_callback(FFmpegCapture *video, X264Encoder *x264_encoder, AudioEncoder *audio_encoder,
93 int64_t video_pts, AVRational video_timebase,
94 int64_t audio_pts, AVRational audio_timebase,
96 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
97 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
99 if (video_pts >= 0 && video_frame.len > 0) {
100 ReceivedTimestamps ts;
101 ts.ts.push_back(steady_clock::now());
103 video_pts = av_rescale_q(video_pts, video_timebase, AVRational{ 1, TIMEBASE });
104 int64_t frame_duration = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
105 x264_encoder->add_frame(video_pts, frame_duration, video->get_current_frame_ycbcr_format().luma_coefficients, video_frame.data + video_offset, ts);
106 global_basic_stats->update(frame_num++, /*dropped_frames=*/0);
108 if (audio_frame.len > 0) {
109 // FFmpegCapture takes care of this for us.
110 assert(audio_format.num_channels == 2);
111 assert(audio_format.sample_rate == OUTPUT_FREQUENCY);
113 // TODO: Reduce some duplication against AudioMixer here.
114 size_t num_samples = audio_frame.len / (audio_format.bits_per_sample / 8);
115 vector<float> float_samples;
116 float_samples.resize(num_samples);
118 if (audio_format.bits_per_sample == 16) {
119 const int16_t *src = (const int16_t *)audio_frame.data;
120 float *dst = &float_samples[0];
121 for (size_t i = 0; i < num_samples; ++i) {
122 *dst++ = int16_t(le16toh(*src++)) * (1.0f / 32768.0f);
124 } else if (audio_format.bits_per_sample == 32) {
125 const int32_t *src = (const int32_t *)audio_frame.data;
126 float *dst = &float_samples[0];
127 for (size_t i = 0; i < num_samples; ++i) {
128 *dst++ = int32_t(le32toh(*src++)) * (1.0f / 2147483648.0f);
133 audio_pts = av_rescale_q(audio_pts, audio_timebase, AVRational{ 1, TIMEBASE });
134 audio_encoder->encode_audio(float_samples, audio_pts);
137 if (video_frame.owner) {
138 video_frame.owner->release_frame(video_frame);
140 if (audio_frame.owner) {
141 audio_frame.owner->release_frame(audio_frame);
145 void raw_packet_callback(Mux *mux, int stream_index, const AVPacket *pkt, AVRational timebase)
147 mux->add_packet(*pkt, pkt->pts, pkt->dts == AV_NOPTS_VALUE ? pkt->pts : pkt->dts, timebase, stream_index);
150 void filter_packet_callback(Mux *mux, int stream_index, AVBSFContext *bsfctx, const AVPacket *pkt, AVRational timebase)
152 if (pkt->size <= 2 || pkt->data[0] != 0xff || (pkt->data[1] & 0xf0) != 0xf0) {
153 // Not ADTS data, so just pass it through.
154 mux->add_packet(*pkt, pkt->pts, pkt->dts == AV_NOPTS_VALUE ? pkt->pts : pkt->dts, timebase, stream_index);
158 AVPacket *in_pkt = av_packet_clone(pkt);
159 unique_ptr<AVPacket, decltype(av_packet_unref) *> in_pkt_cleanup(in_pkt, av_packet_unref);
160 int err = av_bsf_send_packet(bsfctx, in_pkt);
162 fprintf(stderr, "av_bsf_send_packet() failed with %d, ignoring\n", err);
166 unique_ptr<AVPacket, decltype(av_packet_unref) *> pkt_cleanup(&out_pkt, av_packet_unref);
167 av_init_packet(&out_pkt);
168 err = av_bsf_receive_packet(bsfctx, &out_pkt);
169 if (err == AVERROR(EAGAIN)) {
173 fprintf(stderr, "av_bsf_receive_packet() failed with %d, ignoring\n", err);
176 mux->add_packet(out_pkt, out_pkt.pts, out_pkt.dts == AV_NOPTS_VALUE ? out_pkt.pts : out_pkt.dts, timebase, stream_index);
180 void adjust_bitrate(int signal)
182 int new_bitrate = global_flags.x264_bitrate;
183 if (signal == SIGUSR1) {
185 if (new_bitrate > 100000) {
186 fprintf(stderr, "Ignoring SIGUSR1, can't increase bitrate below 100000 kbit/sec (currently at %d kbit/sec)\n",
187 global_flags.x264_bitrate);
189 fprintf(stderr, "Increasing bitrate to %d kbit/sec due to SIGUSR1.\n", new_bitrate);
190 global_flags.x264_bitrate = new_bitrate;
191 global_x264_encoder->change_bitrate(new_bitrate);
193 } else if (signal == SIGUSR2) {
195 if (new_bitrate < 100) {
196 fprintf(stderr, "Ignoring SIGUSR2, can't decrease bitrate below 100 kbit/sec (currently at %d kbit/sec)\n",
197 global_flags.x264_bitrate);
199 fprintf(stderr, "Decreasing bitrate to %d kbit/sec due to SIGUSR2.\n", new_bitrate);
200 global_flags.x264_bitrate = new_bitrate;
201 global_x264_encoder->change_bitrate(new_bitrate);
206 void request_quit(int signal)
211 int main(int argc, char *argv[])
213 parse_flags(PROGRAM_KAERU, argc, argv);
214 if (optind + 1 != argc) {
215 usage(PROGRAM_KAERU);
218 global_flags.max_num_cards = 1; // For latency metrics.
220 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(58, 9, 100)
223 avformat_network_init();
227 const AVOutputFormat *oformat = av_guess_format(global_flags.stream_mux_name.c_str(), nullptr, nullptr);
228 assert(oformat != nullptr);
230 unique_ptr<AudioEncoder> audio_encoder;
231 if (global_flags.stream_audio_codec_name.empty()) {
232 audio_encoder.reset(new AudioEncoder(AUDIO_OUTPUT_CODEC_NAME, DEFAULT_AUDIO_OUTPUT_BIT_RATE, oformat));
234 audio_encoder.reset(new AudioEncoder(global_flags.stream_audio_codec_name, global_flags.stream_audio_codec_bitrate, oformat));
237 unique_ptr<X264Encoder> x264_encoder(new X264Encoder(oformat, /*use_separate_disk_params=*/false));
238 unique_ptr<Mux> http_mux = create_mux(&httpd, oformat, x264_encoder.get(), audio_encoder.get());
239 if (global_flags.transcode_audio) {
240 audio_encoder->add_mux(http_mux.get());
242 if (global_flags.transcode_video) {
243 x264_encoder->add_mux(http_mux.get());
245 global_x264_encoder = x264_encoder.get();
247 FFmpegCapture video(argv[optind], global_flags.width, global_flags.height);
248 video.set_pixel_format(FFmpegCapture::PixelFormat_NV12);
249 if (global_flags.transcode_video) {
250 video.set_frame_callback(bind(video_frame_callback, &video, x264_encoder.get(), audio_encoder.get(), _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11));
252 video.set_video_callback(bind(raw_packet_callback, http_mux.get(), /*stream_index=*/0, _1, _2));
254 if (!global_flags.transcode_audio && global_flags.enable_audio) {
255 AVBSFContext *bsfctx = nullptr;
256 if (strcmp(oformat->name, "mp4") == 0 && strcmp(audio_encoder->get_codec()->name, "aac") == 0) {
257 // We need to insert the aac_adtstoasc filter, seemingly (or we will get warnings to do so).
258 const AVBitStreamFilter *filter = av_bsf_get_by_name("aac_adtstoasc");
259 int err = av_bsf_alloc(filter, &bsfctx);
261 fprintf(stderr, "av_bsf_alloc() failed with %d\n", err);
265 if (bsfctx == nullptr) {
266 video.set_audio_callback(bind(raw_packet_callback, http_mux.get(), /*stream_index=*/1, _1, _2));
268 video.set_audio_callback(bind(filter_packet_callback, http_mux.get(), /*stream_index=*/1, bsfctx, _1, _2));
271 video.configure_card();
272 video.start_bm_capture();
273 video.change_rate(10.0); // Play as fast as possible.
275 BasicStats basic_stats(/*verbose=*/false, /*use_opengl=*/false);
276 global_basic_stats = &basic_stats;
277 httpd.start(global_flags.http_port);
279 signal(SIGUSR1, adjust_bitrate);
280 signal(SIGUSR2, adjust_bitrate);
281 signal(SIGINT, request_quit);
283 while (!should_quit.should_quit()) {
284 should_quit.sleep_for(hours(1000));
287 video.stop_dequeue_thread();
288 // Stop the x264 encoder before killing the mux it's writing to.
289 global_x264_encoder = nullptr;
290 x264_encoder.reset();