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