File size: 22,759 Bytes
ce7fc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/* Copyright (c) 2026 Eoin Jordan
 * SPDX-License-Identifier: Apache-2.0
 *
 * One person's pose from a 96 x 96 picture, on a microcontroller.
 *
 * PoseMicro (train/pose_model.py) turns a 96 x 96 colour picture of one
 * person into the 17 COCO keypoints. They go out on the console, one line a
 * frame:
 *
 *   POSE n=15 52,18,93 55,16,90 49,16,91 ... ms=<milliseconds>
 *
 * n keypoints found (heat at or over the threshold: 0.30 unless you change
 * it), then x,y,heat of all 17 in COCO
 * order (nose, eyes, ears, shoulders, elbows, wrists, hips, knees, ankles;
 * left before right), then the time of the inference. x runs from 0 at the
 * left to 100 at the right of the picture, y from 0 at the top to 100 at
 * the bottom, and heat from 0 to 100.
 *
 * 1. Load the programs embedded in flash: fp32 on the portable kernels and,
 *    unless built with -DAPP_CMSIS_NN=OFF, int8 on the CMSIS-NN kernels.
 * 2. Run each on a picture baked into pose_test_input.h and compare what it
 *    answers at the keypoints with what the export expects.
 * 3. With CONFIG_APP_CAMERA, find the pose in every camera frame, and with
 *    CONFIG_APP_SCREEN show the frame with the skeleton on it.
 *
 * A host can ask for things by sending one character on the console:
 *   c   the next frame as the model gets it, before its POSE line
 *   s   the next screen as it is drawn
 *   i   the start-up report again: sizes, self-tests and timings
 *   t   one frame from the embedded picture, not the camera
 *   +   raise the heat a keypoint needs on camera frames by 0.05
 *   -   lower it by 0.05 (CONFIG_APP_POSE_THRESHOLD_PERCENT is where it starts)
 *
 * The runner is the one of the brick detector in
 * executorch-zephyr-xiao-esp32s3 (firmware/src/lego.cpp); what differs is
 * that the int8 program also answers in int8, so nothing is turned back into
 * floats but the 51 numbers the decoder reads.
 */

#include <executorch/extension/data_loader/buffer_data_loader.h>
#include <executorch/runtime/core/memory_allocator.h>
#include <executorch/runtime/core/span.h>
#include <executorch/runtime/executor/memory_manager.h>
#include <executorch/runtime/executor/method.h>
#include <executorch/runtime/executor/program.h>
#include <executorch/runtime/platform/log.h>
#include <executorch/runtime/platform/runtime.h>

#include <zephyr/device.h>
#include <zephyr/drivers/uart.h>
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
#include <zephyr/version.h>

#ifdef CONFIG_ESP_SPIRAM
#include <zephyr/multi_heap/shared_multi_heap.h>
#endif

#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <vector>

#include "model_pte.h"       /* generated: model_pte[], model_pte_len */
#include "pose_decode.h"
#include "pose_test_input.h" /* generated by train/export_pose.py */

#ifdef APP_CMSIS_NN
#include "model_q_pte.h" /* generated: model_q_pte[], model_q_pte_len */
#endif

#ifdef CONFIG_APP_CAMERA
#include "camera.h"
#endif
#ifdef CONFIG_APP_SCREEN
#include "screen.h"
#endif

using executorch::aten::ScalarType;
using executorch::aten::Tensor;
using executorch::aten::TensorImpl;
using executorch::extension::BufferDataLoader;
using executorch::runtime::Error;
using executorch::runtime::EValue;
using executorch::runtime::HierarchicalAllocator;
using executorch::runtime::MemoryAllocator;
using executorch::runtime::MemoryManager;
using executorch::runtime::Method;
using executorch::runtime::MethodMeta;
using executorch::runtime::Program;
using executorch::runtime::Result;
using executorch::runtime::Span;
using executorch::runtime::TensorInfo;

using pose::kCells;
using pose::kKeypoints;
using pose::kSide;

#ifdef APP_CMSIS_NN
/* The int8 program works in internal RAM. */
alignas(16) static uint8_t q_method_pool[CONFIG_APP_POSE_METHOD_POOL_SIZE];
alignas(16) static uint8_t q_temp_pool[CONFIG_APP_POSE_TEMP_POOL_SIZE];
#endif
alignas(16) static uint8_t temp_pool[CONFIG_APP_POSE_TEMP_POOL_SIZE];

namespace {

struct Found {
	pose::Keypoint k[kKeypoints];
	int n;           /* keypoints with heat at or over the threshold */
	float threshold; /* the threshold n was counted with */
	uint32_t us;
};

/* Memory for things too large for the internal RAM: the PSRAM of the
 * module when it is enabled, the heap otherwise. The fp32 program needs
 * about 300 KB for a 96 x 96 x 3 float picture and its first feature map. */
uint8_t *big_alloc(size_t size)
{
#ifdef CONFIG_ESP_SPIRAM
	return static_cast<uint8_t *>(shared_multi_heap_aligned_alloc(SMH_REG_ATTR_EXTERNAL, 16, size));
#else
	return static_cast<uint8_t *>(k_aligned_alloc(16, size));
#endif
}

/* One loaded program with its memory, ready to run. */
class Runner {
      public:
	Runner(const char *name, const uint8_t *pte, size_t pte_len, uint8_t *method_mem,
	       size_t method_size, uint8_t *temp_mem, size_t temp_size)
		: name(name), pte_len(pte_len), loader_(pte, pte_len),
		  method_allocator_(method_size, method_mem), temp_allocator_(temp_size, temp_mem)
	{
	}

	Error init();
	void info() const;
	/* A 96 x 96 picture in, as RGB bytes or, when rgb888 is null, as RGB565
	 * in host order. The program's answer, still in its own memory and good
	 * until the next run, and the time of execute() out. */
	Error run(const uint8_t *rgb888, const uint16_t *rgb565, pose::Output *out, uint32_t *us);

	const char *const name;
	const size_t pte_len;

      private:
	BufferDataLoader loader_;
	MemoryAllocator method_allocator_;
	MemoryAllocator temp_allocator_;
	std::vector<Span<uint8_t>> planned_spans_;
	Program *program_ = nullptr;
	Method *method_ = nullptr;
	Tensor *input_tensor_ = nullptr;
	void *input_ = nullptr;
	size_t planned_ = 0;
	bool input_int8_ = false;
	bool input_nhwc_ = false;
	int8_t lut_[256];
};

/* True when a four-dimensional tensor keeps its data as rows of pixels with
 * the channels together (NHWC) and not as one plane per channel (NCHW). */
template <typename T> bool channels_last(const T &dim_order)
{
	return dim_order.size() == 4 && dim_order[1] == 2 && dim_order[2] == 3 && dim_order[3] == 1;
}

Error Runner::init()
{
	Result<Program> program_res = Program::load(&loader_);
	if (!program_res.ok()) {
		ET_LOG(Error, "%s: Program::load failed: 0x%x", name, (unsigned)program_res.error());
		return program_res.error();
	}
	program_ = new Program(std::move(program_res.get()));

	const char *method_name = program_->get_method_name(0).get();
	Result<MethodMeta> meta = program_->method_meta(method_name);
	if (!meta.ok()) {
		return meta.error();
	}

	size_t planned = 0;
	for (size_t id = 0; id < meta->num_memory_planned_buffers(); ++id) {
		size_t size = static_cast<size_t>(meta->memory_planned_buffer_size(id).get());
		uint8_t *buf = static_cast<uint8_t *>(method_allocator_.allocate(size, 16));
		if (buf == nullptr) {
			ET_LOG(Error, "%s: planned buffer %zu (%zu B) does not fit the method pool",
			       name, id, size);
			return Error::MemoryAllocationFailed;
		}
		planned += size;
		planned_spans_.push_back({buf, size});
	}

	auto *planned_memory =
		new HierarchicalAllocator({planned_spans_.data(), planned_spans_.size()});
	auto *memory_manager =
		new MemoryManager(&method_allocator_, planned_memory, &temp_allocator_);

	Result<Method> method_res = program_->load_method(method_name, memory_manager);
	if (!method_res.ok()) {
		ET_LOG(Error, "%s: load_method(%s) failed: 0x%x", name, method_name,
		       (unsigned)method_res.error());
		return method_res.error();
	}
	method_ = new Method(std::move(method_res.get()));

	/* The fp32 program takes floats, one plane per channel. The int8 one
	 * takes the picture as int8 with the channels together: its quantize
	 * operator was removed at export, so the bytes go in through a table. */
	Result<TensorInfo> in_meta = meta->input_tensor_meta(0);
	if (!in_meta.ok()) {
		return in_meta.error();
	}
	input_int8_ = in_meta->scalar_type() == ScalarType::Char;
	input_nhwc_ = channels_last(in_meta->dim_order());
	const size_t want = kSide * kSide * 3 * (input_int8_ ? 1 : sizeof(float));
	if (in_meta->nbytes() != want ||
	    (!input_int8_ && in_meta->scalar_type() != ScalarType::Float)) {
		ET_LOG(Error, "%s: the input is not a 96 x 96 x 3 picture", name);
		return Error::InvalidProgram;
	}
	/* The picture is written here and copied into the program by
	 * set_input(), so this buffer need not be in fast memory. */
	input_ = big_alloc(in_meta->nbytes());
	if (input_ == nullptr) {
		return Error::MemoryAllocationFailed;
	}
	for (int v = 0; v < 256; ++v) {
		float q = roundf(static_cast<float>(v) / 255.f / POSE_Q_INPUT_SCALE) +
			  POSE_Q_INPUT_ZERO_POINT;
		lut_[v] = static_cast<int8_t>(fminf(fmaxf(q, -128.f), 127.f));
	}
	auto *impl = new TensorImpl(
		in_meta->scalar_type(), in_meta->sizes().size(),
		const_cast<TensorImpl::SizesType *>(in_meta->sizes().data()), input_,
		const_cast<TensorImpl::DimOrderType *>(in_meta->dim_order().data()));
	input_tensor_ = new Tensor(impl);

	planned_ = planned;
	return Error::Ok;
}

void Runner::info() const
{
	printk("%-9s %6u bytes in flash, %6u planned, pool %6u of %6u bytes used, %s %s input\n",
	       name, (unsigned)pte_len, (unsigned)planned_, (unsigned)method_allocator_.used_size(),
	       (unsigned)method_allocator_.size(), input_int8_ ? "int8" : "float",
	       input_nhwc_ ? "NHWC" : "NCHW");
}

Error Runner::run(const uint8_t *rgb888, const uint16_t *rgb565, pose::Output *result, uint32_t *us)
{
	const int plane = kSide * kSide;
	int8_t *in_q = static_cast<int8_t *>(input_);
	float *in_f = static_cast<float *>(input_);

	for (int i = 0; i < plane; ++i) {
		uint8_t px[3];

		if (rgb888 != nullptr) {
			px[0] = rgb888[3 * i];
			px[1] = rgb888[3 * i + 1];
			px[2] = rgb888[3 * i + 2];
		} else {
			/* Fill the low bits, so white is 255 and not 248. */
			const uint16_t v = rgb565[i];
			const uint8_t r = (v >> 11) & 0x1f, g = (v >> 5) & 0x3f, b = v & 0x1f;

			px[0] = static_cast<uint8_t>((r << 3) | (r >> 2));
			px[1] = static_cast<uint8_t>((g << 2) | (g >> 4));
			px[2] = static_cast<uint8_t>((b << 3) | (b >> 2));
		}
		for (int c = 0; c < 3; ++c) {
			const int at = input_nhwc_ ? i * 3 + c : c * plane + i;

			if (input_int8_) {
				in_q[at] = lut_[px[c]];
			} else {
				in_f[at] = static_cast<float>(px[c]) * (1.f / 255.f);
			}
		}
	}
	Error err = method_->set_input(EValue(*input_tensor_), 0);
	if (err != Error::Ok) {
		ET_LOG(Error, "%s: set_input failed: 0x%x", name, (unsigned)err);
		return err;
	}

	uint32_t t0 = k_cycle_get_32();
	err = method_->execute();
	uint32_t t1 = k_cycle_get_32();
	if (err != Error::Ok) {
		ET_LOG(Error, "%s: execute failed: 0x%x", name, (unsigned)err);
		return err;
	}
	*us = k_cyc_to_us_floor32(t1 - t0);

	const EValue &out = method_->get_output(0);
	if (!out.isTensor()) {
		return Error::InvalidState;
	}
	const Tensor &t = out.toTensor();
	const bool is_int8 = t.scalar_type() == ScalarType::Char;
	if (t.numel() != pose::kOutputs || (!is_int8 && t.scalar_type() != ScalarType::Float)) {
		ET_LOG(Error, "%s: the output is not 51 x 12 x 12 int8 or float", name);
		return Error::InvalidState;
	}
	/* Left where it is: the decoder reads 17 x 144 numbers to find the
	 * keypoints and 34 more to place them, whatever the layout and type. */
	result->data = t.const_data_ptr<void>();
	result->is_int8 = is_int8;
	result->channels_last = channels_last(t.dim_order());
	result->scale = POSE_Q_OUTPUT_SCALE;
	result->zero_point = POSE_Q_OUTPUT_ZERO_POINT;
	return Error::Ok;
}

/* Hundredths without the float formatter, held to 0..100. */
int hundredths(float v)
{
	int h = static_cast<int>(v * 100.f + 0.5f);

	return h < 0 ? 0 : (h > 100 ? 100 : h);
}

void print_pose(const Found &res)
{
	printk("POSE n=%d", res.n);
	for (int i = 0; i < kKeypoints; ++i) {
		printk(" %d,%d,%d", hundredths(res.k[i].x), hundredths(res.k[i].y),
		       hundredths(res.k[i].heat));
	}
	printk(" ms=%u\n", (res.us + 500) / 1000);
}

void decode(const pose::Output &out, uint32_t us, float threshold, Found *res)
{
	pose::decode(out, res->k);
	res->n = pose::found(res->k, threshold);
	res->threshold = threshold;
	res->us = us;
}

/* Run the embedded picture, compare with the reference and time it.
 * `cells` says where PyTorch found each keypoint and `expected` what it
 * answered there: heat, offset across, offset down. Returns the average time
 * of an inference in microseconds, 0 on failure. */
/* expected_found below 0: the number of keypoints found is not part of the test. */
uint32_t self_test(Runner &runner, const uint8_t *cells, const float *expected, int expected_found,
		   float tolerance, const char *reference, Found *res)
{
	pose::Output out = {};
	uint32_t us = 0;

	if (runner.run(kPoseTestImage, nullptr, &out, &us) != Error::Ok) {
		printk("%s: FAIL: inference\n", runner.name);
		return 0;
	}
	float max_diff = 0.f;
	for (int k = 0; k < kKeypoints; ++k) {
		for (int part = 0; part < 3; ++part) {
			const float got = pose::value(out, part * kKeypoints + k, cells[k]);

			max_diff = fmaxf(max_diff, fabsf(got - expected[3 * k + part]));
		}
	}
	/* Always the threshold the export counted with, whatever the camera's is. */
	decode(out, us, pose::kThreshold, res);

	printk("\n%s self-test: embedded picture, against %s\n", runner.name, reference);
	printk("  ");
	print_pose(*res);
	if (expected_found >= 0) {
		printk("  found %d keypoints, expected %d\n", res->n, expected_found);
	}
	printk("  max |device - expected| = %.2e (limit %.2e)\n", static_cast<double>(max_diff),
	       static_cast<double>(tolerance));
	const bool pass = (expected_found < 0 || res->n == expected_found) && max_diff <= tolerance;
	printk("%s SELF-TEST %s\n", runner.name, pass ? "PASS" : "FAIL");

	/* The fp32 program takes seconds a run; three are enough to time it. */
	const int reps = us > 1000000 ? 3 : 10;
	uint32_t total = 0;
	for (int i = 0; i < reps; ++i) {
		runner.run(kPoseTestImage, nullptr, &out, &us);
		total += us;
	}
	printk("%s inference: %u us average over %d runs\n", runner.name, total / reps, reps);
	res->us = total / reps;
	return pass ? total / reps : 0;
}

#if defined(CONFIG_APP_CAMERA) || defined(CONFIG_APP_SCREEN)
void rgb888_to_rgb565(const uint8_t *in, uint16_t *out, int count)
{
	for (int i = 0; i < count; ++i) {
		out[i] = static_cast<uint16_t>(((in[3 * i] & 0xF8) << 8) | ((in[3 * i + 1] & 0xFC) << 3) |
					       (in[3 * i + 2] >> 3));
	}
}

#endif

#ifdef CONFIG_APP_CAMERA
/* The picture as text: one line a row, four hex digits a pixel. */
void dump_image(const uint16_t *img)
{
	static const char hex[] = "0123456789abcdef";
	static char line[kSide * 4 + 1];

	printk("IMG %d %d rgb565\n", kSide, kSide);
	for (int y = 0; y < kSide; ++y) {
		for (int x = 0; x < kSide; ++x) {
			const uint16_t c = img[y * kSide + x];

			line[4 * x] = hex[c >> 12];
			line[4 * x + 1] = hex[(c >> 8) & 0xf];
			line[4 * x + 2] = hex[(c >> 4) & 0xf];
			line[4 * x + 3] = hex[c & 0xf];
		}
		line[kSide * 4] = '\0';
		printk("%s\n", line);
	}
	printk("END IMG\n");
}
#endif

#ifdef CONFIG_APP_SCREEN
/* What the screen shows. The picture fills the panel; the round edge cuts
 * its corners. */
struct View {
	const uint16_t *image; /* 96 x 96 RGB565 */
	const Found *res;
	const char *caption;
};

constexpr int kImgX = 24;
constexpr int kImgY = 6;
constexpr int kImgScale = 2;

/* The person's left in blue and right in red, as in the pictures of the
 * model card; the nose in white. */
uint16_t keypoint_color(int k)
{
	return k == 0 ? COLOR_WHITE : ((k & 1) ? RGB565(70, 150, 255) : RGB565(255, 50, 40));
}

int screen_x(float x)
{
	return kImgX + static_cast<int>(x * kSide * kImgScale);
}

int screen_y(float y)
{
	return kImgY + static_cast<int>(y * kSide * kImgScale);
}

/* A limb as a row of dots: the screen has no line, and dots clip for free. */
void draw_limb(const pose::Keypoint &a, const pose::Keypoint &b)
{
	const int x0 = screen_x(a.x), y0 = screen_y(a.y);
	const int dx = screen_x(b.x) - x0, dy = screen_y(b.y) - y0;
	const int longest = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
	const int steps = longest / 3 > 0 ? longest / 3 : 1;

	for (int i = 0; i <= steps; ++i) {
		screen_fill(x0 + dx * i / steps - 1, y0 + dy * i / steps - 1, 2, 2, COLOR_AMBER);
	}
}

void draw_view(void *ctx)
{
	const View *v = static_cast<const View *>(ctx);
	const Found &res = *v->res;
	char text[24];

	screen_rgb565(kImgX, kImgY, v->image, kSide, kSide, kImgScale);
	for (int i = 0; i < pose::kLimbs; ++i) {
		const pose::Keypoint &a = res.k[pose::kSkeleton[i][0]];
		const pose::Keypoint &b = res.k[pose::kSkeleton[i][1]];

		if (a.heat >= res.threshold && b.heat >= res.threshold) {
			draw_limb(a, b);
		}
	}
	for (int k = 0; k < kKeypoints; ++k) {
		if (res.k[k].heat < res.threshold) {
			continue;
		}
		const int cx = screen_x(res.k[k].x), cy = screen_y(res.k[k].y);

		/* A black edge, so the dot shows on any shirt and any wall. */
		screen_fill(cx - 3, cy - 3, 7, 7, COLOR_BLACK);
		screen_fill(cx - 2, cy - 2, 5, 5, keypoint_color(k));
	}

	snprintk(text, sizeof(text), "n=%d %ums", res.n, (res.us + 500) / 1000);
	screen_text(120 - SCREEN_FONT_W * static_cast<int>(strlen(text)), 202, text, 2, COLOR_WHITE);
	screen_text(120 - SCREEN_FONT_W / 2 * static_cast<int>(strlen(v->caption)), 222, v->caption,
		    1, COLOR_GREY);
}
#endif /* CONFIG_APP_SCREEN */

/* The start-up report: sizes, the self-test of each program and its time.
 * Returns the program for the camera loop. A host that opened the port too
 * late to see it can ask for it again with 'i'. */
Runner *report(Runner &fp32, Runner *int8, Found *res)
{
	Runner *live = &fp32;

	printk("\nExecuTorch PoseMicro on %s (Zephyr %s)\n", CONFIG_BOARD_TARGET,
	       KERNEL_VERSION_STRING);
	fp32.info();
	if (int8 != nullptr) {
		int8->info();
	}

	const uint32_t us = self_test(fp32, kPoseTestCell, kPoseTestValues, POSE_TEST_FOUND, 1e-3f,
				      "PyTorch", res);

	if (int8 != nullptr) {
		/* The integer kernels round differently from the quantised
		 * model in PyTorch and the layers add up, so the export runs
		 * this program on a PC, on the same kernels, and stores what
		 * it answered: the board should match that to the step. When
		 * the export could not, the values are PyTorch's, the limit
		 * is loose and the number of keypoints found is not tested. */
		const int steps = CONFIG_APP_POSE_INT8_STEPS > 0 ? CONFIG_APP_POSE_INT8_STEPS
								  : POSE_TEST_Q_STEPS;
		const uint32_t us_q =
			self_test(*int8, kPoseTestCellQ, kPoseTestValuesQ,
				  POSE_TEST_Q_FROM_PROGRAM ? POSE_TEST_FOUND_Q : -1,
				  (steps + 0.5f) * POSE_Q_OUTPUT_SCALE,
				  POSE_TEST_Q_FROM_PROGRAM ? "this program run on a PC"
							   : "the quantised model in PyTorch",
				  res);

		if (us != 0 && us_q != 0) {
			printk("\nint8 on CMSIS-NN is %u.%02ux the speed of fp32 on the portable "
			       "kernels\n",
			       us / us_q, (us % us_q) * 100 / us_q);
		}
		if (!IS_ENABLED(CONFIG_APP_POSE_LIVE_FP32)) {
			live = int8;
		}
	}
	printk("live program: %s\n", live->name);
	return live;
}

} // namespace

int main(void)
{
	executorch::runtime::runtime_init();

	static Found res;
	Runner *int8_or_null = nullptr;

	uint8_t *pool = big_alloc(CONFIG_APP_POSE_FP32_POOL_SIZE);
	if (pool == nullptr) {
		printk("FAIL: no %d bytes for the fp32 program (is the PSRAM enabled?)\n",
		       CONFIG_APP_POSE_FP32_POOL_SIZE);
		return 1;
	}
	static Runner fp32("portable", model_pte, model_pte_len, pool, CONFIG_APP_POSE_FP32_POOL_SIZE,
			   temp_pool, sizeof(temp_pool));
	if (fp32.init() != Error::Ok) {
		printk("FAIL: runtime init (portable)\n");
		return 1;
	}
#ifdef APP_CMSIS_NN
	static Runner int8("cmsis-nn", model_q_pte, model_q_pte_len, q_method_pool,
			   sizeof(q_method_pool), q_temp_pool, sizeof(q_temp_pool));
	if (int8.init() != Error::Ok) {
		printk("FAIL: runtime init (cmsis-nn)\n");
		return 1;
	}
	int8_or_null = &int8;
#endif

	/* --- 1. Self-test on the embedded picture ----------------------------- */
	Runner *const live = report(fp32, int8_or_null, &res);

#if defined(CONFIG_APP_CAMERA) || defined(CONFIG_APP_SCREEN)
	static uint16_t frame[kSide * kSide];
#endif

#ifdef CONFIG_APP_SCREEN
	static View view;

	rgb888_to_rgb565(kPoseTestImage, frame, kSide * kSide);
	view.image = frame;
	view.res = &res;
	view.caption = "self-test";
	const bool have_screen = screen_init() == 0;
	if (have_screen) {
		screen_render(draw_view, &view);
	}
#endif

	/* --- 2. Live camera loop --------------------------------------------- */
#ifdef CONFIG_APP_CAMERA
	const struct device *const console = DEVICE_DT_GET(DT_CHOSEN(zephyr_console));

	if (app_camera_init() != 0) {
		printk("camera init failed; stopping after self-test\n");
		return 0;
	}
#ifdef CONFIG_APP_SCREEN
	k_msleep(1500); /* leave the self-test picture up for a moment */
	view.caption = live->name;
#endif

	/* The heat a keypoint needs on camera frames, in percent. A camera's
	 * pictures are not COCO's: '+' and '-' on the console move it while
	 * you watch, and CONFIG_APP_POSE_THRESHOLD_PERCENT keeps what works. */
	int threshold_percent = CONFIG_APP_POSE_THRESHOLD_PERCENT;

	printk("keypoint threshold on camera frames: %d%% ('+' and '-' change it)\n",
	       threshold_percent);

	for (;;) {
		bool want_image = false;
		bool want_test = false;
		unsigned char ch;

		while (device_is_ready(console) && uart_poll_in(console, &ch) == 0) {
			if (ch == 'c') {
				want_image = true;
			}
			if (ch == '+' || ch == '-') {
				threshold_percent += ch == '+' ? 5 : -5;
				threshold_percent = threshold_percent < 5    ? 5
						    : threshold_percent > 95 ? 95
									     : threshold_percent;
				printk("keypoint threshold on camera frames: %d%%\n",
				       threshold_percent);
			}
			if (ch == 'i') {
				report(fp32, int8_or_null, &res);
			}
			if (ch == 't') {
				want_test = true;
			}
#ifdef CONFIG_APP_SCREEN
			if (ch == 's') {
				screen_dump_next();
			}
#endif
		}

		pose::Output out = {};
		uint32_t us = 0;
		Error err;

		if (want_test) {
			/* One frame from the embedded picture instead of the camera. */
			rgb888_to_rgb565(kPoseTestImage, frame, kSide * kSide);
			err = live->run(kPoseTestImage, nullptr, &out, &us);
		} else {
			if (app_camera_capture_rgb565(frame) != 0) {
				k_msleep(CONFIG_APP_CAMERA_INTERVAL_MS);
				continue;
			}
			err = live->run(nullptr, frame, &out, &us);
		}
		if (err != Error::Ok) {
			k_msleep(CONFIG_APP_CAMERA_INTERVAL_MS);
			continue;
		}
		decode(out, us, static_cast<float>(threshold_percent) / 100.f, &res);
#ifdef CONFIG_APP_SCREEN
		view.caption = want_test ? "self-test" : live->name;
#endif

		if (want_image) {
			dump_image(frame);
		}
		print_pose(res);
#ifdef CONFIG_APP_SCREEN
		if (have_screen) {
			screen_render(draw_view, &view);
		}
#endif
		k_msleep(CONFIG_APP_CAMERA_INTERVAL_MS);
	}
#else
	ARG_UNUSED(live);
#endif
	return 0;
}