]> git.sesse.net Git - bmusb/blob - fake_capture.cpp
Make FakeCapture capable of outputting audio (a simple sine tone).
[bmusb] / fake_capture.cpp
1 // A fake capture device that sends single-color frames at a given rate.
2 // Mostly useful for testing themes without actually hooking up capture devices.
3
4 #include "bmusb/fake_capture.h"
5
6 #include <assert.h>
7 #include <stdint.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <math.h>
12 #include <unistd.h>
13 #if __SSE2__
14 #include <immintrin.h>
15 #endif
16 #include <cstddef>
17
18 #include "bmusb/bmusb.h"
19
20 #define FRAME_SIZE (8 << 20)  // 8 MB.
21
22 // Pure-color inputs: Red, green, blue, white.
23 #define NUM_COLORS 4
24 constexpr uint8_t ys[NUM_COLORS] = { 81, 145, 41, 235 };
25 constexpr uint8_t cbs[NUM_COLORS] = { 90, 54, 240, 128 };
26 constexpr uint8_t crs[NUM_COLORS] = { 240, 34, 110, 128 };
27
28 using namespace std;
29
30 namespace bmusb {
31 namespace {
32
33 // We don't bother with multiversioning for this, because SSE2
34 // is on by default for all 64-bit compiles, which is really
35 // the target user segment here.
36
37 void memset2(uint8_t *s, const uint8_t c[2], size_t n)
38 {
39         size_t i = 0;
40 #if __SSE2__
41         const uint8_t c_expanded[16] = {
42                 c[0], c[1], c[0], c[1], c[0], c[1], c[0], c[1],
43                 c[0], c[1], c[0], c[1], c[0], c[1], c[0], c[1]
44         };
45         __m128i cc = *(__m128i *)c_expanded;
46         __m128i *out = (__m128i *)s;
47
48         for ( ; i < (n & ~15); i += 16) {
49                 _mm_storeu_si128(out++, cc);
50                 _mm_storeu_si128(out++, cc);
51         }
52
53         s = (uint8_t *)out;
54 #endif
55         for ( ; i < n; ++i) {
56                 *s++ = c[0];
57                 *s++ = c[1];
58         }
59 }
60
61 void memset4(uint8_t *s, const uint8_t c[4], size_t n)
62 {
63         size_t i = 0;
64 #if __SSE2__
65         const uint8_t c_expanded[16] = {
66                 c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3],
67                 c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3]
68         };
69         __m128i cc = *(__m128i *)c_expanded;
70         __m128i *out = (__m128i *)s;
71
72         for ( ; i < (n & ~7); i += 8) {
73                 _mm_storeu_si128(out++, cc);
74                 _mm_storeu_si128(out++, cc);
75         }
76
77         s = (uint8_t *)out;
78 #endif
79         for ( ; i < n; ++i) {
80                 *s++ = c[0];
81                 *s++ = c[1];
82                 *s++ = c[2];
83                 *s++ = c[3];
84         }
85 }
86
87 }  // namespace
88
89 FakeCapture::FakeCapture(unsigned width, unsigned height, unsigned fps, unsigned audio_sample_frequency, int card_index, bool has_audio)
90         : width(width), height(height), fps(fps), audio_sample_frequency(audio_sample_frequency)
91 {
92         char buf[256];
93         snprintf(buf, sizeof(buf), "Fake card %d", card_index + 1);
94         description = buf;
95
96         y = ys[card_index % NUM_COLORS];
97         cb = cbs[card_index % NUM_COLORS];
98         cr = crs[card_index % NUM_COLORS];
99
100         if (has_audio) {
101                 audio_ref_level = pow(10.0f, -23.0f / 20.0f) * (1u << 31);  // -23 dBFS (EBU R128 level).
102
103                 float freq = 440.0 * pow(2.0, card_index / 12.0);
104                 sincosf(2 * M_PI * freq / audio_sample_frequency, &audio_sin, &audio_cos);
105                 audio_real = audio_ref_level;
106                 audio_imag = 0.0f;
107         }
108 }
109
110 FakeCapture::~FakeCapture()
111 {
112         if (has_dequeue_callbacks) {
113                 dequeue_cleanup_callback();
114         }
115 }
116
117 void FakeCapture::configure_card()
118 {
119         if (video_frame_allocator == nullptr) {
120                 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
121                 set_video_frame_allocator(owned_video_frame_allocator.get());
122         }
123         if (audio_frame_allocator == nullptr) {
124                 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
125                 set_audio_frame_allocator(owned_audio_frame_allocator.get());
126         }
127 }
128
129 void FakeCapture::start_bm_capture()
130 {
131         producer_thread_should_quit = false;
132         producer_thread = thread(&FakeCapture::producer_thread_func, this);
133 }
134
135 void FakeCapture::stop_dequeue_thread()
136 {
137         producer_thread_should_quit = true;
138         producer_thread.join();
139 }
140         
141 std::map<uint32_t, VideoMode> FakeCapture::get_available_video_modes() const
142 {
143         VideoMode mode;
144
145         char buf[256];
146         snprintf(buf, sizeof(buf), "%ux%u", width, height);
147         mode.name = buf;
148         
149         mode.autodetect = false;
150         mode.width = width;
151         mode.height = height;
152         mode.frame_rate_num = fps;
153         mode.frame_rate_den = 1;
154         mode.interlaced = false;
155
156         return {{ 0, mode }};
157 }
158
159 std::map<uint32_t, std::string> FakeCapture::get_available_video_inputs() const
160 {
161         return {{ 0, "Fake video input (single color)" }};
162 }
163
164 std::map<uint32_t, std::string> FakeCapture::get_available_audio_inputs() const
165 {
166         return {{ 0, "Fake audio input (silence)" }};
167 }
168
169 void FakeCapture::set_video_mode(uint32_t video_mode_id)
170 {
171         assert(video_mode_id == 0);
172 }
173
174 void FakeCapture::set_video_input(uint32_t video_input_id)
175 {
176         assert(video_input_id == 0);
177 }
178
179 void FakeCapture::set_audio_input(uint32_t audio_input_id)
180 {
181         assert(audio_input_id == 0);
182 }
183
184 namespace {
185
186 void add_time(double t, timespec *ts)
187 {
188         ts->tv_nsec += lrint(t * 1e9);
189         ts->tv_sec += ts->tv_nsec / 1000000000;
190         ts->tv_nsec %= 1000000000;
191 }
192
193 bool timespec_less_than(const timespec &a, const timespec &b)
194 {
195         return make_pair(a.tv_sec, a.tv_nsec) < make_pair(b.tv_sec, b.tv_nsec);
196 }
197
198 }  // namespace
199
200 void FakeCapture::producer_thread_func()
201 {
202         uint16_t timecode = 0;
203
204         if (has_dequeue_callbacks) {
205                 dequeue_init_callback();
206         }
207
208         timespec next_frame;
209         clock_gettime(CLOCK_MONOTONIC, &next_frame);
210         add_time(1.0 / fps, &next_frame);
211
212         while (!producer_thread_should_quit) {
213                 timespec now;
214                 clock_gettime(CLOCK_MONOTONIC, &now);
215
216                 if (timespec_less_than(now, next_frame)) {
217                         // Wait until the next frame.
218                         if (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
219                                             &next_frame, nullptr) == -1) {
220                                 if (errno == EINTR) continue;  // Re-check the flag and then sleep again.
221                                 perror("clock_nanosleep");
222                                 exit(1);
223                         }
224                 } else {
225                         // We've seemingly missed a frame. If we're more than one second behind,
226                         // reset the timer; otherwise, just keep going.
227                         timespec limit = next_frame;
228                         ++limit.tv_sec;
229                         if (!timespec_less_than(now, limit)) {
230                                 fprintf(stderr, "More than one second of missed fake frames; resetting clock.\n");
231                                 next_frame = now;
232                         }
233                 }
234
235                 // Figure out when the next frame is to be, then compute the current one.
236                 add_time(1.0 / fps, &next_frame);
237
238                 VideoFormat video_format;
239                 video_format.width = width;
240                 video_format.height = height;
241                 video_format.frame_rate_nom = fps;
242                 video_format.frame_rate_den = 1;
243                 video_format.has_signal = true;
244                 video_format.is_connected = false;
245
246                 FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
247                 if (video_frame.data != nullptr) {
248                         assert(video_frame.size >= width * height * 2);
249                         if (video_frame.interleaved) {
250                                 uint8_t cbcr[] = { cb, cr };
251                                 memset2(video_frame.data, cbcr, width * height / 2);
252                                 memset(video_frame.data2, y, width * height);
253                         } else {
254                                 uint8_t ycbcr[] = { y, cb, y, cr };
255                                 memset4(video_frame.data, ycbcr, width * height / 2);
256                         }
257                         video_frame.len = width * height * 2;
258                 }
259
260                 AudioFormat audio_format;
261                 audio_format.bits_per_sample = 32;
262                 audio_format.num_channels = 2;
263
264                 FrameAllocator::Frame audio_frame = audio_frame_allocator->alloc_frame();
265                 if (audio_frame.data != nullptr) {
266                         const unsigned num_stereo_samples = audio_sample_frequency / fps;
267                         assert(audio_frame.size >= 2 * sizeof(int32_t) * num_stereo_samples);
268                         audio_frame.len = 2 * sizeof(int32_t) * num_stereo_samples;
269
270                         if (audio_sin == 0.0f) {
271                                 // Silence.
272                                 memset(audio_frame.data, 0, audio_frame.len);
273                         } else {
274                                 make_tone((int32_t *)audio_frame.data, num_stereo_samples);
275                         }
276                 }
277
278                 frame_callback(timecode++,
279                                video_frame, 0, video_format,
280                                audio_frame, 0, audio_format);
281         }
282         if (has_dequeue_callbacks) {
283                 dequeue_cleanup_callback();
284         }
285 }
286
287 void FakeCapture::make_tone(int32_t *out, unsigned num_stereo_samples)
288 {
289         int32_t *ptr = out;
290         float r = audio_real, i = audio_imag;
291         for (unsigned sample_num = 0; sample_num < num_stereo_samples; ++sample_num) {
292                 int32_t s = lrintf(r);
293                 *ptr++ = s;
294                 *ptr++ = s;
295
296                 // Rotate the phaser by one sample.
297                 float new_r = r * audio_cos - i * audio_sin;
298                 float new_i = r * audio_sin + i * audio_cos;
299                 r = new_r;
300                 i = new_i;
301         }
302
303         // Periodically renormalize to counteract precision issues.
304         double corr = audio_ref_level / hypot(r, i);
305         audio_real = r * corr;
306         audio_imag = i * corr;
307 }
308
309 }  // namespace bmusb