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 "print_latency.h"
10 #include "shared/ffmpeg_raii.h"
11 #include "shared/httpd.h"
12 #include "shared/mux.h"
13 #include "quittable_sleeper.h"
14 #include "shared/shared_defs.h"
15 #include "shared/timebase.h"
16 #include "x264_encoder.h"
19 #include <bmusb/bmusb.h>
35 #include <libavcodec/bsf.h>
36 #include <libavcodec/codec_par.h>
37 #include <libavcodec/packet.h>
38 #include <libavformat/avformat.h>
39 #include <libavformat/avio.h>
40 #include <libavformat/version.h>
41 #include <libavutil/avutil.h>
42 #include <libavutil/common.h>
43 #include <libavutil/error.h>
44 #include <libavutil/mathematics.h>
45 #include <libavutil/mem.h>
46 #include <libavutil/rational.h>
47 #include <libavutil/version.h>
50 using namespace bmusb;
51 using namespace movit;
53 using namespace std::chrono;
54 using namespace std::placeholders;
56 Mixer *global_mixer = nullptr;
57 X264Encoder *global_x264_encoder = nullptr;
59 BasicStats *global_basic_stats = nullptr;
60 QuittableSleeper should_quit;
61 MuxMetrics stream_mux_metrics;
65 int write_packet(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
67 static bool seen_sync_markers = false;
68 static string stream_mux_header;
69 HTTPD *httpd = (HTTPD *)opaque;
71 if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
72 seen_sync_markers = true;
73 } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
74 // We don't know if this is a keyframe or not (the muxer could
75 // avoid marking it), so we just have to make the best of it.
76 type = AVIO_DATA_MARKER_SYNC_POINT;
79 HTTPD::StreamID stream_id{ HTTPD::MAIN_STREAM, 0 };
80 if (type == AVIO_DATA_MARKER_HEADER) {
81 stream_mux_header.append((char *)buf, buf_size);
82 httpd->set_header(stream_id, stream_mux_header);
84 httpd->add_data(stream_id, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
91 unique_ptr<Mux> create_mux(HTTPD *httpd, const AVOutputFormat *oformat, X264Encoder *x264_encoder, AudioEncoder *audio_encoder)
93 AVFormatContext *avctx = avformat_alloc_context();
94 avctx->oformat = oformat; // const_cast is a hack to work in FFmpeg both before and after 5.0.
96 uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
97 avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, httpd, nullptr, nullptr, nullptr);
98 avctx->pb->write_data_type = &write_packet;
99 avctx->pb->ignore_boundary_point = 1;
100 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
102 string video_extradata = x264_encoder->get_global_headers();
104 // If audio is disabled (ie., we won't ever see any audio packets),
105 // set nullptr here to also not include the stream in the mux.
106 AVCodecParameters *audio_codecpar =
107 global_flags.enable_audio ? audio_encoder->get_codec_parameters().release() : nullptr;
110 mux.reset(new Mux(avctx, global_flags.width, global_flags.height, Mux::CODEC_H264, video_extradata, audio_codecpar,
111 get_color_space(global_flags.ycbcr_rec709_coefficients), COARSE_TIMEBASE,
112 /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, { &stream_mux_metrics }));
113 stream_mux_metrics.init({{ "destination", "http" }});
117 void video_frame_callback(FFmpegCapture *video, X264Encoder *x264_encoder, AudioEncoder *audio_encoder,
118 int64_t video_pts, AVRational video_timebase,
119 int64_t audio_pts, AVRational audio_timebase,
121 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
122 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
124 if (video_pts >= 0 && video_frame.len > 0) {
125 ReceivedTimestamps ts;
126 ts.ts.push_back(steady_clock::now());
128 video_pts = av_rescale_q(video_pts, video_timebase, AVRational{ 1, TIMEBASE });
129 int64_t frame_duration = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
130 x264_encoder->add_frame(video_pts, frame_duration, video->get_current_frame_ycbcr_format().luma_coefficients, video_frame.data + video_offset, ts);
131 global_basic_stats->update(frame_num++, /*dropped_frames=*/0);
133 if (audio_frame.len > 0) {
134 // FFmpegCapture takes care of this for us.
135 assert(audio_format.num_channels == 2);
136 assert(audio_format.sample_rate == OUTPUT_FREQUENCY);
138 // TODO: Reduce some duplication against AudioMixer here.
139 size_t num_samples = audio_frame.len / (audio_format.bits_per_sample / 8);
140 vector<float> float_samples;
141 float_samples.resize(num_samples);
143 if (audio_format.bits_per_sample == 16) {
144 const int16_t *src = (const int16_t *)audio_frame.data;
145 float *dst = &float_samples[0];
146 for (size_t i = 0; i < num_samples; ++i) {
147 *dst++ = int16_t(le16toh(*src++)) * (1.0f / 32768.0f);
149 } else if (audio_format.bits_per_sample == 32) {
150 const int32_t *src = (const int32_t *)audio_frame.data;
151 float *dst = &float_samples[0];
152 for (size_t i = 0; i < num_samples; ++i) {
153 *dst++ = int32_t(le32toh(*src++)) * (1.0f / 2147483648.0f);
158 audio_pts = av_rescale_q(audio_pts, audio_timebase, AVRational{ 1, TIMEBASE });
159 audio_encoder->encode_audio(float_samples, audio_pts);
162 if (video_frame.owner) {
163 video_frame.owner->release_frame(video_frame);
165 if (audio_frame.owner) {
166 audio_frame.owner->release_frame(audio_frame);
170 void raw_packet_callback(Mux *mux, int stream_index, const AVPacket *pkt, AVRational timebase)
172 mux->add_packet(*pkt, pkt->pts, pkt->dts == AV_NOPTS_VALUE ? pkt->pts : pkt->dts, timebase, stream_index);
175 void filter_packet_callback(Mux *mux, int stream_index, AVBSFContext *bsfctx, const AVPacket *pkt, AVRational timebase)
177 if (pkt->size <= 2 || pkt->data[0] != 0xff || (pkt->data[1] & 0xf0) != 0xf0) {
178 // Not ADTS data, so just pass it through.
179 mux->add_packet(*pkt, pkt->pts, pkt->dts == AV_NOPTS_VALUE ? pkt->pts : pkt->dts, timebase, stream_index);
183 AVPacket *in_pkt = av_packet_clone(pkt);
184 unique_ptr<AVPacket, decltype(av_packet_unref) *> in_pkt_cleanup(in_pkt, av_packet_unref);
185 int err = av_bsf_send_packet(bsfctx, in_pkt);
187 fprintf(stderr, "av_bsf_send_packet() failed with %d, ignoring\n", err);
190 AVPacketWithDeleter out_pkt = av_packet_alloc_unique();
191 err = av_bsf_receive_packet(bsfctx, out_pkt.get());
192 if (err == AVERROR(EAGAIN)) {
196 fprintf(stderr, "av_bsf_receive_packet() failed with %d, ignoring\n", err);
199 mux->add_packet(*out_pkt, out_pkt->pts, out_pkt->dts == AV_NOPTS_VALUE ? out_pkt->pts : out_pkt->dts, timebase, stream_index);
203 void adjust_bitrate(int signal)
205 int new_bitrate = global_flags.x264_bitrate;
206 if (signal == SIGUSR1) {
208 if (new_bitrate > 100000) {
209 fprintf(stderr, "Ignoring SIGUSR1, can't increase bitrate below 100000 kbit/sec (currently at %d kbit/sec)\n",
210 global_flags.x264_bitrate);
212 fprintf(stderr, "Increasing bitrate to %d kbit/sec due to SIGUSR1.\n", new_bitrate);
213 global_flags.x264_bitrate = new_bitrate;
214 global_x264_encoder->change_bitrate(new_bitrate);
216 } else if (signal == SIGUSR2) {
218 if (new_bitrate < 100) {
219 fprintf(stderr, "Ignoring SIGUSR2, can't decrease bitrate below 100 kbit/sec (currently at %d kbit/sec)\n",
220 global_flags.x264_bitrate);
222 fprintf(stderr, "Decreasing bitrate to %d kbit/sec due to SIGUSR2.\n", new_bitrate);
223 global_flags.x264_bitrate = new_bitrate;
224 global_x264_encoder->change_bitrate(new_bitrate);
229 void request_quit(int signal)
234 int main(int argc, char *argv[])
236 parse_flags(PROGRAM_KAERU, argc, argv);
237 if (optind + 1 != argc) {
238 usage(PROGRAM_KAERU);
241 global_flags.max_num_cards = 1; // For latency metrics.
243 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(58, 9, 100)
246 avformat_network_init();
250 const AVOutputFormat *oformat = av_guess_format(global_flags.stream_mux_name.c_str(), nullptr, nullptr);
251 assert(oformat != nullptr);
253 unique_ptr<AudioEncoder> audio_encoder;
254 if (global_flags.stream_audio_codec_name.empty()) {
255 audio_encoder.reset(new AudioEncoder(AUDIO_OUTPUT_CODEC_NAME, DEFAULT_AUDIO_OUTPUT_BIT_RATE, oformat));
257 audio_encoder.reset(new AudioEncoder(global_flags.stream_audio_codec_name, global_flags.stream_audio_codec_bitrate, oformat));
260 unique_ptr<X264Encoder> x264_encoder(new X264Encoder(oformat, /*use_separate_disk_params=*/false));
261 unique_ptr<Mux> http_mux = create_mux(&httpd, oformat, x264_encoder.get(), audio_encoder.get());
262 if (global_flags.transcode_audio) {
263 audio_encoder->add_mux(http_mux.get());
265 if (global_flags.transcode_video) {
266 x264_encoder->add_mux(http_mux.get());
268 global_x264_encoder = x264_encoder.get();
270 FFmpegCapture video(argv[optind], global_flags.width, global_flags.height);
271 video.set_pixel_format(FFmpegCapture::PixelFormat_NV12);
272 if (global_flags.transcode_video) {
273 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));
275 video.set_video_callback(bind(raw_packet_callback, http_mux.get(), /*stream_index=*/0, _1, _2));
277 if (!global_flags.transcode_audio && global_flags.enable_audio) {
278 AVBSFContext *bsfctx = nullptr;
279 if (strcmp(oformat->name, "mp4") == 0 && strcmp(audio_encoder->get_codec()->name, "aac") == 0) {
280 // We need to insert the aac_adtstoasc filter, seemingly (or we will get warnings to do so).
281 const AVBitStreamFilter *filter = av_bsf_get_by_name("aac_adtstoasc");
282 int err = av_bsf_alloc(filter, &bsfctx);
284 fprintf(stderr, "av_bsf_alloc() failed with %d\n", err);
288 if (bsfctx == nullptr) {
289 video.set_audio_callback(bind(raw_packet_callback, http_mux.get(), /*stream_index=*/1, _1, _2));
291 video.set_audio_callback(bind(filter_packet_callback, http_mux.get(), /*stream_index=*/1, bsfctx, _1, _2));
294 video.configure_card();
295 video.start_bm_capture();
296 video.change_rate(10.0); // Play as fast as possible.
298 BasicStats basic_stats(/*verbose=*/false, /*use_opengl=*/false);
299 global_basic_stats = &basic_stats;
300 httpd.start(global_flags.http_port);
302 signal(SIGUSR1, adjust_bitrate);
303 signal(SIGUSR2, adjust_bitrate);
304 signal(SIGINT, request_quit);
306 while (!should_quit.should_quit()) {
307 should_quit.sleep_for(hours(1000));
310 video.stop_dequeue_thread();
311 // Stop the x264 encoder before killing the mux it's writing to.
312 global_x264_encoder = nullptr;
313 x264_encoder.reset();