]> git.sesse.net Git - nageru/blob - nageru/kaeru.cpp
843bd81b4293cbdc28f15c6387e9457aa550c049
[nageru] / nageru / kaeru.cpp
1 // Kaeru (換える), a simple transcoder intended for use with Nageru.
2
3 #include "audio_encoder.h"
4 #include "basic_stats.h"
5 #include "defs.h"
6 #include "flags.h"
7 #include "ffmpeg_capture.h"
8 #include "mixer.h"
9 #include "shared/mux.h"
10 #include "quittable_sleeper.h"
11 #include "shared/timebase.h"
12 #include "x264_encoder.h"
13
14 #include <assert.h>
15 #include <fcntl.h>
16 #include <signal.h>
17 #include <unistd.h>
18 #include <chrono>
19 #include <string>
20
21 using namespace bmusb;
22 using namespace movit;
23 using namespace std;
24 using namespace std::chrono;
25 using namespace std::placeholders;
26
27 Mixer *global_mixer = nullptr;
28 X264Encoder *global_x264_encoder = nullptr;
29 int frame_num = 0;
30 BasicStats *global_basic_stats = nullptr;
31 QuittableSleeper should_quit;
32 MuxMetrics stream_mux_metrics;
33
34 namespace {
35
36 int write_packet(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
37 {
38         static bool seen_sync_markers = false;
39         static string stream_mux_header;
40         HTTPD *httpd = (HTTPD *)opaque;
41
42         if (type == AVIO_DATA_MARKER_SYNC_POINT || type == AVIO_DATA_MARKER_BOUNDARY_POINT) {
43                 seen_sync_markers = true;
44         } else if (type == AVIO_DATA_MARKER_UNKNOWN && !seen_sync_markers) {
45                 // We don't know if this is a keyframe or not (the muxer could
46                 // avoid marking it), so we just have to make the best of it.
47                 type = AVIO_DATA_MARKER_SYNC_POINT;
48         }
49
50         if (type == AVIO_DATA_MARKER_HEADER) {
51                 stream_mux_header.append((char *)buf, buf_size);
52                 httpd->set_header(HTTPD::MAIN_STREAM, stream_mux_header);
53         } else {
54                 httpd->add_data(HTTPD::MAIN_STREAM, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
55         }
56         return buf_size;
57 }
58
59 }  // namespace
60
61 unique_ptr<Mux> create_mux(HTTPD *httpd, AVOutputFormat *oformat, X264Encoder *x264_encoder, AudioEncoder *audio_encoder)
62 {
63         AVFormatContext *avctx = avformat_alloc_context();
64         avctx->oformat = oformat;
65
66         uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
67         avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, httpd, nullptr, nullptr, nullptr);
68         avctx->pb->write_data_type = &write_packet;
69         avctx->pb->ignore_boundary_point = 1;
70         avctx->flags = AVFMT_FLAG_CUSTOM_IO;
71
72         string video_extradata = x264_encoder->get_global_headers();
73
74         unique_ptr<Mux> mux;
75         mux.reset(new Mux(avctx, global_flags.width, global_flags.height, Mux::CODEC_H264, video_extradata, audio_encoder->get_codec_parameters().get(),
76                 get_color_space(global_flags.ycbcr_rec709_coefficients), COARSE_TIMEBASE,
77                 /*write_callback=*/nullptr, Mux::WRITE_FOREGROUND, { &stream_mux_metrics }));
78         stream_mux_metrics.init({{ "destination", "http" }});
79         return mux;
80 }
81
82 void video_frame_callback(FFmpegCapture *video, X264Encoder *x264_encoder, AudioEncoder *audio_encoder,
83                           int64_t video_pts, AVRational video_timebase,
84                           int64_t audio_pts, AVRational audio_timebase,
85                           uint16_t timecode,
86                           FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
87                           FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
88 {
89         if (video_pts >= 0 && video_frame.len > 0) {
90                 ReceivedTimestamps ts;
91                 ts.ts.push_back(steady_clock::now());
92
93                 video_pts = av_rescale_q(video_pts, video_timebase, AVRational{ 1, TIMEBASE });
94                 int64_t frame_duration = int64_t(TIMEBASE) * video_format.frame_rate_den / video_format.frame_rate_nom;
95                 x264_encoder->add_frame(video_pts, frame_duration, video->get_current_frame_ycbcr_format().luma_coefficients, video_frame.data + video_offset, ts);
96                 global_basic_stats->update(frame_num++, /*dropped_frames=*/0);
97         }
98         if (audio_frame.len > 0) {
99                 // FFmpegCapture takes care of this for us.
100                 assert(audio_format.num_channels == 2);
101                 assert(audio_format.sample_rate == OUTPUT_FREQUENCY);
102
103                 // TODO: Reduce some duplication against AudioMixer here.
104                 size_t num_samples = audio_frame.len / (audio_format.bits_per_sample / 8);
105                 vector<float> float_samples;
106                 float_samples.resize(num_samples);
107                 if (audio_format.bits_per_sample == 16) {
108                         const int16_t *src = (const int16_t *)audio_frame.data;
109                         float *dst = &float_samples[0];
110                         for (size_t i = 0; i < num_samples; ++i) {
111                                 *dst++ = le16toh(*src++) * (1.0f / 32768.0f);
112                         }
113                 } else if (audio_format.bits_per_sample == 32) {
114                         const int32_t *src = (const int32_t *)audio_frame.data;
115                         float *dst = &float_samples[0];
116                         for (size_t i = 0; i < num_samples; ++i) {
117                                 *dst++ = le32toh(*src++) * (1.0f / 2147483648.0f);
118                         }
119                 } else {
120                         assert(false);
121                 }
122                 audio_pts = av_rescale_q(audio_pts, audio_timebase, AVRational{ 1, TIMEBASE });
123                 audio_encoder->encode_audio(float_samples, audio_pts);
124         }
125
126         if (video_frame.owner) {
127                 video_frame.owner->release_frame(video_frame);
128         }
129         if (audio_frame.owner) {
130                 audio_frame.owner->release_frame(audio_frame);
131         }
132 }
133
134 void audio_frame_callback(Mux *mux, const AVPacket *pkt, AVRational timebase)
135 {
136         mux->add_packet(*pkt, pkt->pts, pkt->dts == AV_NOPTS_VALUE ? pkt->pts : pkt->dts, timebase, /*stream_index=*/1);
137 }
138
139 void adjust_bitrate(int signal)
140 {
141         int new_bitrate = global_flags.x264_bitrate;
142         if (signal == SIGUSR1) {
143                 new_bitrate += 100;
144                 if (new_bitrate > 100000) {
145                         fprintf(stderr, "Ignoring SIGUSR1, can't increase bitrate below 100000 kbit/sec (currently at %d kbit/sec)\n",
146                                 global_flags.x264_bitrate);
147                 } else {
148                         fprintf(stderr, "Increasing bitrate to %d kbit/sec due to SIGUSR1.\n", new_bitrate);
149                         global_flags.x264_bitrate = new_bitrate;
150                         global_x264_encoder->change_bitrate(new_bitrate);
151                 }
152         } else if (signal == SIGUSR2) {
153                 new_bitrate -= 100;
154                 if (new_bitrate < 100) {
155                         fprintf(stderr, "Ignoring SIGUSR2, can't decrease bitrate below 100 kbit/sec (currently at %d kbit/sec)\n",
156                                 global_flags.x264_bitrate);
157                 } else {
158                         fprintf(stderr, "Decreasing bitrate to %d kbit/sec due to SIGUSR2.\n", new_bitrate);
159                         global_flags.x264_bitrate = new_bitrate;
160                         global_x264_encoder->change_bitrate(new_bitrate);
161                 }
162         }
163 }
164
165 void request_quit(int signal)
166 {
167         should_quit.quit();
168 }
169
170 int main(int argc, char *argv[])
171 {
172         parse_flags(PROGRAM_KAERU, argc, argv);
173         if (optind + 1 != argc) {
174                 usage(PROGRAM_KAERU);
175                 exit(1);
176         }
177         global_flags.num_cards = 1;  // For latency metrics.
178
179 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(58, 9, 100)
180         av_register_all();
181 #endif
182         avformat_network_init();
183
184         HTTPD httpd;
185
186         AVOutputFormat *oformat = av_guess_format(global_flags.stream_mux_name.c_str(), nullptr, nullptr);
187         assert(oformat != nullptr);
188
189         unique_ptr<AudioEncoder> audio_encoder;
190         if (global_flags.stream_audio_codec_name.empty()) {
191                 audio_encoder.reset(new AudioEncoder(AUDIO_OUTPUT_CODEC_NAME, DEFAULT_AUDIO_OUTPUT_BIT_RATE, oformat));
192         } else {
193                 audio_encoder.reset(new AudioEncoder(global_flags.stream_audio_codec_name, global_flags.stream_audio_codec_bitrate, oformat));
194         }
195
196         unique_ptr<X264Encoder> x264_encoder(new X264Encoder(oformat));
197         unique_ptr<Mux> http_mux = create_mux(&httpd, oformat, x264_encoder.get(), audio_encoder.get());
198         if (global_flags.transcode_audio) {
199                 audio_encoder->add_mux(http_mux.get());
200         }
201         x264_encoder->add_mux(http_mux.get());
202         global_x264_encoder = x264_encoder.get();
203
204         FFmpegCapture video(argv[optind], global_flags.width, global_flags.height);
205         video.set_pixel_format(FFmpegCapture::PixelFormat_NV12);
206         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));
207         if (!global_flags.transcode_audio) {
208                 video.set_audio_callback(bind(audio_frame_callback, http_mux.get(), _1, _2));
209         }
210         video.configure_card();
211         video.start_bm_capture();
212         video.change_rate(10.0);  // Play as fast as possible.
213
214         BasicStats basic_stats(/*verbose=*/false, /*use_opengl=*/false);
215         global_basic_stats = &basic_stats;
216         httpd.start(global_flags.http_port);
217
218         signal(SIGUSR1, adjust_bitrate);
219         signal(SIGUSR2, adjust_bitrate);
220         signal(SIGINT, request_quit);
221
222         while (!should_quit.should_quit()) {
223                 should_quit.sleep_for(hours(1000));
224         }
225
226         video.stop_dequeue_thread();
227         // Stop the x264 encoder before killing the mux it's writing to.
228         global_x264_encoder = nullptr;
229         x264_encoder.reset();
230         return 0;
231 }