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