1 // Kaeru (換える), a simple transcoder intended for use with Nageru.
2 // This is experimental code, not yet supported.
4 #include "audio_encoder.h"
7 #include "ffmpeg_capture.h"
11 #include "x264_encoder.h"
19 using namespace bmusb;
20 using namespace movit;
22 using namespace std::placeholders;
24 Mixer *global_mixer = nullptr;
25 X264Encoder *global_x264_encoder = nullptr;
27 int write_packet(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
29 static bool seen_sync_markers = false;
30 static string stream_mux_header;
31 HTTPD *httpd = (HTTPD *)opaque;
33 if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
34 seen_sync_markers = true;
35 } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
36 // We don't know if this is a keyframe or not (the muxer could
37 // avoid marking it), so we just have to make the best of it.
38 type = AVIO_DATA_MARKER_SYNC_POINT;
41 if (type == AVIO_DATA_MARKER_HEADER) {
42 stream_mux_header.append((char *)buf, buf_size);
43 httpd->set_header(stream_mux_header);
45 httpd->add_data((char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT);
50 unique_ptr<Mux> create_mux(HTTPD *httpd, AVOutputFormat *oformat, X264Encoder *x264_encoder, AudioEncoder *audio_encoder)
52 AVFormatContext *avctx = avformat_alloc_context();
53 avctx->oformat = oformat;
55 uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
56 avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, httpd, nullptr, nullptr, nullptr);
57 avctx->pb->write_data_type = &write_packet;
58 avctx->pb->ignore_boundary_point = 1;
60 string video_extradata = x264_encoder->get_global_headers();
63 int time_base = global_flags.stream_coarse_timebase ? COARSE_TIMEBASE : TIMEBASE;
64 mux.reset(new Mux(avctx, global_flags.width, global_flags.height, Mux::CODEC_H264, video_extradata, audio_encoder->get_codec_parameters().get(), time_base,
65 /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, {}));
69 void video_frame_callback(FFmpegCapture *video, X264Encoder *x264_encoder, AudioEncoder *audio_encoder,
70 int64_t video_pts, AVRational video_timebase,
71 int64_t audio_pts, AVRational audio_timebase,
73 FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
74 FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
76 if (video_pts >= 0 && video_frame.len > 0) {
77 video_pts = av_rescale_q(video_pts, video_timebase, AVRational{ 1, TIMEBASE });
78 int64_t frame_duration = TIMEBASE * video_format.frame_rate_nom / video_format.frame_rate_den;
79 x264_encoder->add_frame(video_pts, frame_duration, video->get_current_frame_ycbcr_format().luma_coefficients, video_frame.data + video_offset, ReceivedTimestamps());
81 if (audio_frame.len > 0) {
82 // FFmpegCapture takes care of this for us.
83 assert(audio_format.num_channels == 2);
84 assert(audio_format.sample_rate == OUTPUT_FREQUENCY);
86 // TODO: Reduce some duplication against AudioMixer here.
87 size_t num_samples = audio_frame.len / (audio_format.bits_per_sample / 8);
88 vector<float> float_samples;
89 float_samples.resize(num_samples);
90 if (audio_format.bits_per_sample == 16) {
91 const int16_t *src = (const int16_t *)audio_frame.data;
92 float *dst = &float_samples[0];
93 for (size_t i = 0; i < num_samples; ++i) {
94 *dst++ = le16toh(*src++) * (1.0f / 32768.0f);
96 } else if (audio_format.bits_per_sample == 32) {
97 const int32_t *src = (const int32_t *)audio_frame.data;
98 float *dst = &float_samples[0];
99 for (size_t i = 0; i < num_samples; ++i) {
100 *dst++ = le32toh(*src++) * (1.0f / 2147483648.0f);
105 audio_pts = av_rescale_q(audio_pts, audio_timebase, AVRational{ 1, TIMEBASE });
106 audio_encoder->encode_audio(float_samples, audio_pts);
109 if (video_frame.owner) {
110 video_frame.owner->release_frame(video_frame);
112 if (audio_frame.owner) {
113 audio_frame.owner->release_frame(audio_frame);
117 void audio_frame_callback(Mux *mux, const AVPacket *pkt, AVRational timebase)
119 mux->add_packet(*pkt, pkt->pts, pkt->dts == AV_NOPTS_VALUE ? pkt->pts : pkt->dts, timebase);
122 void adjust_bitrate(int signal)
124 int new_bitrate = global_flags.x264_bitrate;
125 if (signal == SIGUSR1) {
127 if (new_bitrate > 100000) {
128 fprintf(stderr, "Ignoring SIGUSR1, can't increase bitrate below 100000 kbit/sec (currently at %d kbit/sec)\n",
129 global_flags.x264_bitrate);
131 fprintf(stderr, "Increasing bitrate to %d kbit/sec due to SIGUSR1.\n", new_bitrate);
132 global_flags.x264_bitrate = new_bitrate;
133 global_x264_encoder->change_bitrate(new_bitrate);
135 } else if (signal == SIGUSR2) {
137 if (new_bitrate < 100) {
138 fprintf(stderr, "Ignoring SIGUSR1, can't decrease bitrate below 100 kbit/sec (currently at %d kbit/sec)\n",
139 global_flags.x264_bitrate);
141 fprintf(stderr, "Decreasing bitrate to %d kbit/sec due to SIGUSR1.\n", new_bitrate);
142 global_flags.x264_bitrate = new_bitrate;
143 global_x264_encoder->change_bitrate(new_bitrate);
148 int main(int argc, char *argv[])
150 parse_flags(PROGRAM_KAERU, argc, argv);
151 if (optind + 1 != argc) {
152 usage(PROGRAM_KAERU);
157 avformat_network_init();
161 AVOutputFormat *oformat = av_guess_format(global_flags.stream_mux_name.c_str(), nullptr, nullptr);
162 assert(oformat != nullptr);
164 unique_ptr<AudioEncoder> audio_encoder;
165 if (global_flags.transcode_audio) {
166 if (global_flags.stream_audio_codec_name.empty()) {
167 audio_encoder.reset(new AudioEncoder(AUDIO_OUTPUT_CODEC_NAME, DEFAULT_AUDIO_OUTPUT_BIT_RATE, oformat));
169 audio_encoder.reset(new AudioEncoder(global_flags.stream_audio_codec_name, global_flags.stream_audio_codec_bitrate, oformat));
173 X264Encoder x264_encoder(oformat);
174 unique_ptr<Mux> http_mux = create_mux(&httpd, oformat, &x264_encoder, audio_encoder.get());
175 if (global_flags.transcode_audio) {
176 audio_encoder->add_mux(http_mux.get());
178 x264_encoder.add_mux(http_mux.get());
179 global_x264_encoder = &x264_encoder;
181 FFmpegCapture video(argv[optind], global_flags.width, global_flags.height);
182 video.set_pixel_format(FFmpegCapture::PixelFormat_NV12);
183 video.set_frame_callback(bind(video_frame_callback, &video, &x264_encoder, audio_encoder.get(), _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11));
184 if (!global_flags.transcode_audio) {
185 video.set_audio_callback(bind(audio_frame_callback, http_mux.get(), _1, _2));
187 video.configure_card();
188 video.start_bm_capture();
189 video.change_rate(2.0); // Be sure never to really fall behind, but also don't dump huge amounts of stuff onto x264.
193 signal(SIGUSR1, adjust_bitrate);
194 signal(SIGUSR2, adjust_bitrate);