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"
10 #include "quittable_sleeper.h"
12 #include "x264_encoder.h"
21 using namespace bmusb;
22 using namespace movit;
24 using namespace std::chrono;
25 using namespace std::placeholders;
27 Mixer *global_mixer = nullptr;
28 X264Encoder *global_x264_encoder = nullptr;
30 BasicStats *global_basic_stats = nullptr;
31 QuittableSleeper should_quit;
32 MuxMetrics stream_mux_metrics;
34 int write_packet(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
36 static bool seen_sync_markers = false;
37 static string stream_mux_header;
38 HTTPD *httpd = (HTTPD *)opaque;
40 if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
41 seen_sync_markers = true;
42 } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
43 // We don't know if this is a keyframe or not (the muxer could
44 // avoid marking it), so we just have to make the best of it.
45 type = AVIO_DATA_MARKER_SYNC_POINT;
48 if (type == AVIO_DATA_MARKER_HEADER) {
49 stream_mux_header.append((char *)buf, buf_size);
50 httpd->set_header(stream_mux_header);
52 httpd->add_data((char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
57 unique_ptr<Mux> create_mux(HTTPD *httpd, AVOutputFormat *oformat, X264Encoder *x264_encoder, AudioEncoder *audio_encoder)
59 AVFormatContext *avctx = avformat_alloc_context();
60 avctx->oformat = oformat;
62 uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
63 avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, httpd, nullptr, nullptr, nullptr);
64 avctx->pb->write_data_type = &write_packet;
65 avctx->pb->ignore_boundary_point = 1;
66 avctx->flags = AVFMT_FLAG_CUSTOM_IO;
68 string video_extradata = x264_encoder->get_global_headers();
71 mux.reset(new Mux(avctx, global_flags.width, global_flags.height, Mux::CODEC_H264, video_extradata, audio_encoder->get_codec_parameters().get(), COARSE_TIMEBASE,
72 /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, { &stream_mux_metrics }));
73 stream_mux_metrics.init({{ "destination", "http" }});
77 void video_frame_callback(FFmpegCapture *video, X264Encoder *x264_encoder, AudioEncoder *audio_encoder,
78 int64_t video_pts, AVRational video_timebase,
79 int64_t audio_pts, AVRational audio_timebase,
81 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
82 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
84 if (video_pts >= 0 && video_frame.len > 0) {
85 ReceivedTimestamps ts;
86 ts.ts.push_back(steady_clock::now());
88 video_pts = av_rescale_q(video_pts, video_timebase, AVRational{ 1, TIMEBASE });
89 int64_t frame_duration = TIMEBASE * video_format.frame_rate_den / video_format.frame_rate_nom;
90 x264_encoder->add_frame(video_pts, frame_duration, video->get_current_frame_ycbcr_format().luma_coefficients, video_frame.data + video_offset, ts);
91 global_basic_stats->update(frame_num++, /*dropped_frames=*/0);
93 if (audio_frame.len > 0) {
94 // FFmpegCapture takes care of this for us.
95 assert(audio_format.num_channels == 2);
96 assert(audio_format.sample_rate == OUTPUT_FREQUENCY);
98 // TODO: Reduce some duplication against AudioMixer here.
99 size_t num_samples = audio_frame.len / (audio_format.bits_per_sample / 8);
100 vector<float> float_samples;
101 float_samples.resize(num_samples);
102 if (audio_format.bits_per_sample == 16) {
103 const int16_t *src = (const int16_t *)audio_frame.data;
104 float *dst = &float_samples[0];
105 for (size_t i = 0; i < num_samples; ++i) {
106 *dst++ = le16toh(*src++) * (1.0f / 32768.0f);
108 } else if (audio_format.bits_per_sample == 32) {
109 const int32_t *src = (const int32_t *)audio_frame.data;
110 float *dst = &float_samples[0];
111 for (size_t i = 0; i < num_samples; ++i) {
112 *dst++ = le32toh(*src++) * (1.0f / 2147483648.0f);
117 audio_pts = av_rescale_q(audio_pts, audio_timebase, AVRational{ 1, TIMEBASE });
118 audio_encoder->encode_audio(float_samples, audio_pts);
121 if (video_frame.owner) {
122 video_frame.owner->release_frame(video_frame);
124 if (audio_frame.owner) {
125 audio_frame.owner->release_frame(audio_frame);
129 void audio_frame_callback(Mux *mux, const AVPacket *pkt, AVRational timebase)
131 mux->add_packet(*pkt, pkt->pts, pkt->dts == AV_NOPTS_VALUE ? pkt->pts : pkt->dts, timebase, /*stream_index=*/1);
134 void adjust_bitrate(int signal)
136 int new_bitrate = global_flags.x264_bitrate;
137 if (signal == SIGUSR1) {
139 if (new_bitrate > 100000) {
140 fprintf(stderr, "Ignoring SIGUSR1, can't increase bitrate below 100000 kbit/sec (currently at %d kbit/sec)\n",
141 global_flags.x264_bitrate);
143 fprintf(stderr, "Increasing bitrate to %d kbit/sec due to SIGUSR1.\n", new_bitrate);
144 global_flags.x264_bitrate = new_bitrate;
145 global_x264_encoder->change_bitrate(new_bitrate);
147 } else if (signal == SIGUSR2) {
149 if (new_bitrate < 100) {
150 fprintf(stderr, "Ignoring SIGUSR2, can't decrease bitrate below 100 kbit/sec (currently at %d kbit/sec)\n",
151 global_flags.x264_bitrate);
153 fprintf(stderr, "Decreasing bitrate to %d kbit/sec due to SIGUSR2.\n", new_bitrate);
154 global_flags.x264_bitrate = new_bitrate;
155 global_x264_encoder->change_bitrate(new_bitrate);
160 void request_quit(int signal)
165 int main(int argc, char *argv[])
167 parse_flags(PROGRAM_KAERU, argc, argv);
168 if (optind + 1 != argc) {
169 usage(PROGRAM_KAERU);
172 global_flags.num_cards = 1; // For latency metrics.
175 avformat_network_init();
179 AVOutputFormat *oformat = av_guess_format(global_flags.stream_mux_name.c_str(), nullptr, nullptr);
180 assert(oformat != nullptr);
182 unique_ptr<AudioEncoder> audio_encoder;
183 if (global_flags.stream_audio_codec_name.empty()) {
184 audio_encoder.reset(new AudioEncoder(AUDIO_OUTPUT_CODEC_NAME, DEFAULT_AUDIO_OUTPUT_BIT_RATE, oformat));
186 audio_encoder.reset(new AudioEncoder(global_flags.stream_audio_codec_name, global_flags.stream_audio_codec_bitrate, oformat));
189 unique_ptr<X264Encoder> x264_encoder(new X264Encoder(oformat));
190 unique_ptr<Mux> http_mux = create_mux(&httpd, oformat, x264_encoder.get(), audio_encoder.get());
191 if (global_flags.transcode_audio) {
192 audio_encoder->add_mux(http_mux.get());
194 x264_encoder->add_mux(http_mux.get());
195 global_x264_encoder = x264_encoder.get();
197 FFmpegCapture video(argv[optind], global_flags.width, global_flags.height);
198 video.set_pixel_format(FFmpegCapture::PixelFormat_NV12);
199 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));
200 if (!global_flags.transcode_audio) {
201 video.set_audio_callback(bind(audio_frame_callback, http_mux.get(), _1, _2));
203 video.configure_card();
204 video.start_bm_capture();
205 video.change_rate(2.0); // Be sure never to really fall behind, but also don't dump huge amounts of stuff onto x264.
207 BasicStats basic_stats(/*verbose=*/false, /*use_opengl=*/false);
208 global_basic_stats = &basic_stats;
209 httpd.start(global_flags.http_port);
211 signal(SIGUSR1, adjust_bitrate);
212 signal(SIGUSR2, adjust_bitrate);
213 signal(SIGINT, request_quit);
215 while (!should_quit.should_quit()) {
216 should_quit.sleep_for(hours(1000));
219 video.stop_dequeue_thread();
220 // Stop the x264 encoder before killing the mux it's writing to.
221 x264_encoder.reset();