]> git.sesse.net Git - nageru/blob - nageru/kaeru.cpp
Fix a dangling reference (found by GCC 14).
[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 "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"
17
18 #include <assert.h>
19 #include <bmusb/bmusb.h>
20 #include <chrono>
21 #include <endian.h>
22 #include <errno.h>
23 #include <functional>
24 #include <memory>
25 #include <signal.h>
26 #include <stddef.h>
27 #include <stdint.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <string>
32 #include <vector>
33
34 extern "C" {
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>
48 }
49
50 using namespace bmusb;
51 using namespace movit;
52 using namespace std;
53 using namespace std::chrono;
54 using namespace std::placeholders;
55
56 Mixer *global_mixer = nullptr;
57 X264Encoder *global_x264_encoder = nullptr;
58 int frame_num = 0;
59 BasicStats *global_basic_stats = nullptr;
60 QuittableSleeper should_quit;
61 MuxMetrics stream_mux_metrics;
62
63 namespace {
64
65 int write_packet(void *opaque, uint8_t *buf, int buf_size, AVIODataMarkerType type, int64_t time)
66 {
67         static bool seen_sync_markers = false;
68         static string stream_mux_header;
69         HTTPD *httpd = (HTTPD *)opaque;
70
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;
77         }
78
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);
83         } else {
84                 httpd->add_data(stream_id, (char *)buf, buf_size, type == AVIO_DATA_MARKER_SYNC_POINT, time, AVRational{ AV_TIME_BASE, 1 });
85         }
86         return buf_size;
87 }
88
89 }  // namespace
90
91 unique_ptr<Mux> create_mux(HTTPD *httpd, const AVOutputFormat *oformat, X264Encoder *x264_encoder, AudioEncoder *audio_encoder)
92 {
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.
95
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;
101
102         string video_extradata = x264_encoder->get_global_headers();
103
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;
108
109         unique_ptr<Mux> mux;
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" }});
114         return mux;
115 }
116
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,
120                           uint16_t timecode,
121                           FrameAllocator::Frame video_frame, size_t video_offset, VideoFormat video_format,
122                           FrameAllocator::Frame audio_frame, size_t audio_offset, AudioFormat audio_format)
123 {
124         if (video_pts >= 0 && video_frame.len > 0) {
125                 ReceivedTimestamps ts;
126                 ts.ts.push_back(steady_clock::now());
127
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);
132         }
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);
137
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);
142
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);
148                         }
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);
154                         }
155                 } else {
156                         assert(false);
157                 }
158                 audio_pts = av_rescale_q(audio_pts, audio_timebase, AVRational{ 1, TIMEBASE });
159                 audio_encoder->encode_audio(float_samples, audio_pts);
160         }
161
162         if (video_frame.owner) {
163                 video_frame.owner->release_frame(video_frame);
164         }
165         if (audio_frame.owner) {
166                 audio_frame.owner->release_frame(audio_frame);
167         }
168 }
169
170 void raw_packet_callback(Mux *mux, int stream_index, const AVPacket *pkt, AVRational timebase)
171 {
172         mux->add_packet(*pkt, pkt->pts, pkt->dts == AV_NOPTS_VALUE ? pkt->pts : pkt->dts, timebase, stream_index);
173 }
174
175 void filter_packet_callback(Mux *mux, int stream_index, AVBSFContext *bsfctx, const AVPacket *pkt, AVRational timebase)
176 {
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);
180                 return;
181         }
182
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);
186         if (err < 0) {
187                 fprintf(stderr, "av_bsf_send_packet() failed with %d, ignoring\n", err);
188         }
189         for ( ;; ) {
190                 AVPacketWithDeleter out_pkt = av_packet_alloc_unique();
191                 err = av_bsf_receive_packet(bsfctx, out_pkt.get());
192                 if (err == AVERROR(EAGAIN)) {
193                         break;
194                 }
195                 if (err < 0) {
196                         fprintf(stderr, "av_bsf_receive_packet() failed with %d, ignoring\n", err);
197                         return;
198                 }
199                 mux->add_packet(*out_pkt, out_pkt->pts, out_pkt->dts == AV_NOPTS_VALUE ? out_pkt->pts : out_pkt->dts, timebase, stream_index);
200         }
201 }
202
203 void adjust_bitrate(int signal)
204 {
205         int new_bitrate = global_flags.x264_bitrate;
206         if (signal == SIGUSR1) {
207                 new_bitrate += 100;
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);
211                 } else {
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);
215                 }
216         } else if (signal == SIGUSR2) {
217                 new_bitrate -= 100;
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);
221                 } else {
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);
225                 }
226         }
227 }
228
229 void request_quit(int signal)
230 {
231         should_quit.quit();
232 }
233
234 int main(int argc, char *argv[])
235 {
236         parse_flags(PROGRAM_KAERU, argc, argv);
237         if (optind + 1 != argc) {
238                 usage(PROGRAM_KAERU);
239                 abort();
240         }
241         global_flags.max_num_cards = 1;  // For latency metrics.
242
243 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(58, 9, 100)
244         av_register_all();
245 #endif
246         avformat_network_init();
247
248         HTTPD httpd;
249
250         const AVOutputFormat *oformat = av_guess_format(global_flags.stream_mux_name.c_str(), nullptr, nullptr);
251         assert(oformat != nullptr);
252
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));
256         } else {
257                 audio_encoder.reset(new AudioEncoder(global_flags.stream_audio_codec_name, global_flags.stream_audio_codec_bitrate, oformat));
258         }
259
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());
264         }
265         if (global_flags.transcode_video) {
266                 x264_encoder->add_mux(http_mux.get());
267         }
268         global_x264_encoder = x264_encoder.get();
269
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));
274         } else {
275                 video.set_video_callback(bind(raw_packet_callback, http_mux.get(), /*stream_index=*/0, _1, _2));
276         }
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);
283                         if (err < 0) {
284                                 fprintf(stderr, "av_bsf_alloc() failed with %d\n", err);
285                                 exit(1);
286                         }
287                 }
288                 if (bsfctx == nullptr) {
289                         video.set_audio_callback(bind(raw_packet_callback, http_mux.get(), /*stream_index=*/1, _1, _2));
290                 } else {
291                         video.set_audio_callback(bind(filter_packet_callback, http_mux.get(), /*stream_index=*/1, bsfctx, _1, _2));
292                 }
293         }
294         video.configure_card();
295         video.start_bm_capture();
296         video.change_rate(10.0);  // Play as fast as possible.
297
298         BasicStats basic_stats(/*verbose=*/false, /*use_opengl=*/false);
299         global_basic_stats = &basic_stats;
300         httpd.start(global_flags.http_port);
301
302         signal(SIGUSR1, adjust_bitrate);
303         signal(SIGUSR2, adjust_bitrate);
304         signal(SIGINT, request_quit);
305
306         while (!should_quit.should_quit()) {
307                 should_quit.sleep_for(hours(1000));
308         }
309
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();
314         return 0;
315 }