-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathmain.cpp
More file actions
1817 lines (1601 loc) · 57.3 KB
/
Copy pathmain.cpp
File metadata and controls
1817 lines (1601 loc) · 57.3 KB
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define MODULE_TAG "pixelpilot"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
#include <inttypes.h>
#include <signal.h>
#include <fstream>
#include <atomic>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/mman.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <drm_fourcc.h>
#include <linux/videodev2.h>
#include <rockchip/rk_mpi.h>
#include <nlohmann/json.hpp>
#include <yaml-cpp/yaml.h>
#include "spdlog/spdlog.h"
extern "C" {
#include "main.h"
#include "drm.h"
#include "mavlink/common/mavlink.h"
#include "mavlink.h"
#include "input.h"
}
#include "osd.h"
#include "osd.hpp"
#include "wfbcli.hpp"
#include "dvr.h"
#include "mpp_encoder.h"
#include "frame_processor.h"
#include "gstrtpreceiver.h"
#include "scheduling_helper.hpp"
#include "time_util.h"
#include "os_mon.hpp"
#include "pixelpilot_config.h"
#include <iostream>
#include "WiFiRSSIMonitor.hpp"
#include "gsmenu/gs_system.h"
#include "gsmenu/air_actions.h"
#include "gsmenu/gs_actions.h"
#include "menu.h"
#define READ_BUF_SIZE (1024*1024) // SZ_1M https://github.com/rockchip-linux/mpp/blob/ed377c99a733e2cdbcc457a6aa3f0fcd438a9dff/osal/inc/mpp_common.h#L179
#define MAX_FRAMES 24 // min 16 and 20+ recommended (mpp/readme.txt)
#define CODEC_ALIGN(x, a) (((x)+(a)-1)&~((a)-1))
#define DEFAULT_CONFIG_PATH "/etc/pixelpilot.yaml"
YAML::Node config;
#define MSG_FIFO_NAME "/run/pixelpilot.msg"
struct {
MppCtx ctx;
MppApi *mpi;
struct timespec first_frame_ts;
MppBufferGroup frm_grp;
struct {
int prime_fd;
uint32_t fb_id;
uint32_t handle;
} frame_to_drm[MAX_FRAMES];
} mpi;
struct timespec frame_stats[1000];
struct modeset_output *output_list;
int frm_eos = 0;
int drm_fd = 0;
pthread_mutex_t video_mutex;
pthread_cond_t video_cond;
extern bool osd_update_ready;
extern bool gsmenu_enabled;
int video_zpos = 1;
void set_mpp_decoding_parameters(MppApi * mpi, MppCtx ctx);
static pthread_mutex_t mpp_reinit_mutex = PTHREAD_MUTEX_INITIALIZER;
static std::atomic<bool> mpp_reinit_pending{false};
bool mavlink_dvr_on_arm = false;
bool osd_custom_message = false;
bool disable_vsync = false;
bool disable_gregidr = false;
uint32_t refresh_frequency_ms = 1000;
VideoCodec codec = VideoCodec::H265;
uint16_t listen_port = 5600;
const char* unix_socket = NULL;
char* dvr_template = NULL;
Dvr *dvr_raw = NULL;
Dvr *dvr_reenc_inst = NULL;
MppEncoder *reencoder = NULL;
MppEncoderParams reenc_params;
DvrMode dvr_mode = DVR_MODE_RAW;
bool dvr_osd = false;
static int video_framerate = -1;
static bool dvr_filenames_with_sequence = false;
static int mp4_fragmentation_mode = 0;
static int64_t dvr_max_file_size = 4000000000LL; // 4 GB (decimal), safe margin for VFAT 4 GiB limit
FrameProcessor *frame_proc = nullptr;
// Thread handles for the encoder and pacer — file-scope so live mode toggle can join them.
static pthread_t g_tid_enc = 0;
static pthread_t g_tid_fproc = 0;
static pthread_t g_tid_dvr_raw = 0;
static pthread_t g_tid_dvr_reenc = 0;
// Decoded frame geometry – updated in init_buffer(), used in __FRAME_THREAD__
uint32_t decoded_hor_stride = 0;
uint32_t decoded_ver_stride = 0;
OsSensors os_sensors; // TODO: pass as argument to `main_loop`
MenuAction airactions[MAX_ACTIONS];
size_t airactions_count;
MenuAction gsactions[MAX_ACTIONS];
size_t gsactions_count;
// Add global variables for plane id overrides
uint32_t video_plane_id_override = 0;
uint32_t osd_plane_id_override = 0;
WiFiRSSIMonitor wifi_monitor;
extern enum RXMode RXMODE;
bool enable_live_colortrans = false;
float live_colortrans_offset = -0.15f;
float live_colortrans_gain = 2.5f;
gamma_lut_controller lut_ctrl;
// Helper: get target width/height for the current re-encode resolution setting.
static void reenc_target_dims(uint32_t &w, uint32_t &h) {
if (reenc_params.resolution == EncResolution::Res720p) { w = 1280; h = 720; }
else { w = 1920; h = 1080; }
}
void init_buffer(MppFrame frame) {
output_list->video_frm_width = mpp_frame_get_width(frame);
output_list->video_frm_height = mpp_frame_get_height(frame);
RK_U32 hor_stride = mpp_frame_get_hor_stride(frame);
RK_U32 ver_stride = mpp_frame_get_ver_stride(frame);
MppFrameFormat fmt = mpp_frame_get_fmt(frame);
assert((fmt == MPP_FMT_YUV420SP) || (fmt == MPP_FMT_YUV420SP_10BIT));
decoded_hor_stride = hor_stride;
decoded_ver_stride = ver_stride;
spdlog::info("Frame info changed {}({})x{}({})",
output_list->video_frm_width, hor_stride, output_list->video_frm_height, ver_stride);
output_list->video_fb_x = 0;
output_list->video_fb_y = 0;
output_list->video_fb_width = output_list->mode.hdisplay;
output_list->video_fb_height =output_list->mode.vdisplay;
osd_publish_uint_fact("video.width", NULL, 0, output_list->video_frm_width);
osd_publish_uint_fact("video.height", NULL, 0, output_list->video_frm_height);
// Drain any decoder-buffer refs held by the encoder pacer before freeing
// the group. Without this the group teardown races with the pacer's copy
// loop and the buffer fds become invalid while still in use.
if (frame_proc) frame_proc->drain_decoder_refs();
if (mpi.frm_grp) {
spdlog::debug("Freeing current mpp_buffer_group");
// First clean up all DRM resources for existing frames
for (int i = 0; i < MAX_FRAMES; i++) {
if (mpi.frame_to_drm[i].fb_id) {
drmModeRmFB(drm_fd, mpi.frame_to_drm[i].fb_id);
mpi.frame_to_drm[i].fb_id = 0;
}
if (mpi.frame_to_drm[i].prime_fd >= 0) {
close(mpi.frame_to_drm[i].prime_fd);
mpi.frame_to_drm[i].prime_fd = -1;
}
if (mpi.frame_to_drm[i].handle) {
struct drm_mode_destroy_dumb dmd = {
.handle = mpi.frame_to_drm[i].handle,
};
ioctl(drm_fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dmd);
mpi.frame_to_drm[i].handle = 0;
}
}
mpp_buffer_group_clear(mpi.frm_grp);
mpp_buffer_group_put(mpi.frm_grp); // This is important to release the group
mpi.frm_grp = NULL;
}
// create new external frame group and allocate (commit flow) new DRM buffers and DRM FB
int ret = mpp_buffer_group_get_external(&mpi.frm_grp, MPP_BUFFER_TYPE_DRM);
assert(!ret);
for (int i=0; i<MAX_FRAMES; i++) {
// new DRM buffer
struct drm_mode_create_dumb dmcd;
memset(&dmcd, 0, sizeof(dmcd));
dmcd.bpp = fmt==MPP_FMT_YUV420SP?8:10;
dmcd.width = hor_stride;
dmcd.height = ver_stride*2; // documentation say not v*2/3 but v*2 (additional info included)
do {
ret = ioctl(drm_fd, DRM_IOCTL_MODE_CREATE_DUMB, &dmcd);
} while (ret == -1 && (errno == EINTR || errno == EAGAIN));
assert(!ret);
// assert(dmcd.pitch==(fmt==MPP_FMT_YUV420SP?hor_stride:hor_stride*10/8));
// assert(dmcd.size==(fmt == MPP_FMT_YUV420SP?hor_stride:hor_stride*10/8)*ver_stride*2);
mpi.frame_to_drm[i].handle = dmcd.handle;
// commit DRM buffer to frame group
struct drm_prime_handle dph;
memset(&dph, 0, sizeof(struct drm_prime_handle));
dph.handle = dmcd.handle;
dph.fd = -1;
do {
ret = ioctl(drm_fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &dph);
} while (ret == -1 && (errno == EINTR || errno == EAGAIN));
assert(!ret);
MppBufferInfo info;
memset(&info, 0, sizeof(info));
info.type = MPP_BUFFER_TYPE_DRM;
info.size = dmcd.width*dmcd.height;
info.fd = dph.fd;
ret = mpp_buffer_commit(mpi.frm_grp, &info);
assert(!ret);
mpi.frame_to_drm[i].prime_fd = info.fd; // dups fd
if (dph.fd != info.fd) {
ret = close(dph.fd);
assert(!ret);
}
// allocate DRM FB from DRM buffer
uint32_t handles[4], pitches[4], offsets[4];
memset(handles, 0, sizeof(handles));
memset(pitches, 0, sizeof(pitches));
memset(offsets, 0, sizeof(offsets));
handles[0] = mpi.frame_to_drm[i].handle;
offsets[0] = 0;
pitches[0] = hor_stride;
handles[1] = mpi.frame_to_drm[i].handle;
offsets[1] = pitches[0] * ver_stride;
pitches[1] = pitches[0];
ret = drmModeAddFB2(drm_fd, output_list->video_frm_width, output_list->video_frm_height, DRM_FORMAT_NV12, handles, pitches, offsets, &mpi.frame_to_drm[i].fb_id, 0);
assert(!ret);
}
// register external frame group
ret = mpi.mpi->control(mpi.ctx, MPP_DEC_SET_EXT_BUF_GROUP, mpi.frm_grp);
ret = mpi.mpi->control(mpi.ctx, MPP_DEC_SET_INFO_CHANGE_READY, NULL);
ret = modeset_perform_modeset(drm_fd, output_list, output_list->video_request, &output_list->video_plane, mpi.frame_to_drm[0].fb_id, output_list->video_frm_width, output_list->video_frm_height, video_zpos);
assert(ret >= 0);
// dvr setup
if (dvr_raw != NULL) {
dvr_raw->set_video_params(output_list->video_frm_width, output_list->video_frm_height, codec);
}
if (dvr_reenc_inst != NULL) {
uint32_t rw, rh; reenc_target_dims(rw, rh);
dvr_reenc_inst->set_video_params(rw, rh, reenc_params.codec);
}
}
// __FRAME_THREAD__
//
// - allocate DRM buffers and DRM FB based on frame size
// - pick frame in blocking mode and output to screen overlay
void *__FRAME_THREAD__(void *param)
{
SchedulingHelper::set_thread_params_max_realtime("FRAME_THREAD",SchedulingHelper::PRIORITY_REALTIME_MID);
int i, ret;
MppFrame frame = NULL;
uint64_t last_frame_time;
pthread_setname_np(pthread_self(), "__FRAME");
while (!frm_eos) {
struct timespec ts, ats;
assert(!frame);
pthread_mutex_lock(&mpp_reinit_mutex);
if (mpp_reinit_pending.load(std::memory_order_acquire)) {
// Decoder is being reinitialized — release lock and wait
pthread_mutex_unlock(&mpp_reinit_mutex);
usleep(5000);
continue;
}
ret = mpi.mpi->decode_get_frame(mpi.ctx, &frame);
pthread_mutex_unlock(&mpp_reinit_mutex);
if (mpp_reinit_pending.load(std::memory_order_acquire)) {
// Reinit started while we were blocked — discard result
if (frame) {
mpp_frame_deinit(&frame);
frame = NULL;
}
continue;
}
assert(!ret);
clock_gettime(CLOCK_MONOTONIC, &ats);
if (frame) {
if (mpp_frame_get_info_change(frame)) {
// new resolution
init_buffer(frame);
} else {
// regular frame received
idr_notify_decoded_frame();
const RK_U32 errinfo = mpp_frame_get_errinfo(frame);
const RK_U32 discard = mpp_frame_get_discard(frame);
if (errinfo || discard) {
const char* reason = "decoder-issue";
if (errinfo && discard) {
reason = "decoder-errinfo+discard";
} else if (errinfo) {
reason = "decoder-errinfo";
} else if (discard) {
reason = "decoder-discard";
}
idr_request_decoder_issue(reason);
}
if (!mpi.first_frame_ts.tv_sec) {
ts = ats;
mpi.first_frame_ts = ats;
}
MppBuffer buffer = mpp_frame_get_buffer(frame);
if (buffer && !discard) {
output_list->video_poc = mpp_frame_get_poc(frame);
uint64_t feed_data_ts = mpp_frame_get_pts(frame);
MppBufferInfo info;
ret = mpp_buffer_info_get(buffer, &info);
assert(!ret);
for (i=0; i<MAX_FRAMES; i++) {
if (mpi.frame_to_drm[i].prime_fd == info.fd) break;
}
assert(i!=MAX_FRAMES);
ts = ats;
// send DRM FB to display thread
ret = pthread_mutex_lock(&video_mutex);
assert(!ret);
output_list->video_fb_id = mpi.frame_to_drm[i].fb_id;
//output_list->video_fb_index=i;
output_list->decoding_pts=feed_data_ts;
ret = pthread_cond_signal(&video_cond);
assert(!ret);
ret = pthread_mutex_unlock(&video_mutex);
assert(!ret);
if (frame_proc != nullptr &&
decoded_hor_stride > 0 && decoded_ver_stride > 0) {
MppFrameFormat fmt = mpp_frame_get_fmt(frame);
frame_proc->push_latest(buffer,
output_list->video_frm_width,
output_list->video_frm_height,
decoded_hor_stride,
decoded_ver_stride, fmt);
}
} else {
spdlog::warn("dropping frame (buffer={}, discard={})", buffer ? "ok" : "null", discard);
}
}
frm_eos = mpp_frame_get_eos(frame);
mpp_frame_deinit(&frame);
frame = NULL;
} else assert(0);
}
spdlog::info("Frame thread done.");
return nullptr;
}
void *__DISPLAY_THREAD__(void *param)
{
int ret;
pthread_setname_np(pthread_self(), "__DISPLAY");
while (!frm_eos) {
int fb_id;
bool osd_update;
ret = pthread_mutex_lock(&video_mutex);
assert(!ret);
while (output_list->video_fb_id==0 && !osd_update_ready) {
pthread_cond_wait(&video_cond, &video_mutex);
assert(!ret);
if (output_list->video_fb_id == 0 && frm_eos) {
ret = pthread_mutex_unlock(&video_mutex);
assert(!ret);
goto end;
}
}
fb_id = output_list->video_fb_id;
osd_update = osd_update_ready;
uint64_t decoding_pts=fb_id != 0 ? output_list->decoding_pts : get_time_ms();
output_list->video_fb_id=0;
osd_update_ready = false;
ret = pthread_mutex_unlock(&video_mutex);
assert(!ret);
// create new video_request
drmModeAtomicFree(output_list->video_request);
output_list->video_request = drmModeAtomicAlloc();
// show DRM FB in plane
uint32_t flags = DRM_MODE_ATOMIC_NONBLOCK;
if (fb_id != 0) {
flags = disable_vsync ? DRM_MODE_ATOMIC_NONBLOCK : DRM_MODE_ATOMIC_ALLOW_MODESET;
ret = set_drm_object_property(output_list->video_request, &output_list->video_plane, "FB_ID", fb_id);
assert(ret>0);
}
if(enable_osd) {
ret = pthread_mutex_lock(&osd_mutex);
assert(!ret);
if (enable_live_colortrans)
ret = set_drm_object_property(output_list->video_request, &output_list->osd_plane, "FB_ID", output_list->osd_bufs[output_list->osd_buf_switch].gl_fb_id);
else
ret = set_drm_object_property(output_list->video_request, &output_list->osd_plane, "FB_ID", output_list->osd_bufs[output_list->osd_buf_switch].fb);
assert(ret>0);
}
drmModeAtomicCommit(drm_fd, output_list->video_request, flags, NULL);
ret = pthread_mutex_unlock(&osd_mutex);
assert(!ret);
osd_publish_uint_fact("video.displayed_frame", NULL, 0, 1);
uint64_t decode_and_handover_display_ms=get_time_ms()-decoding_pts;
osd_publish_uint_fact("video.decode_and_handover_ms", NULL, 0, decode_and_handover_display_ms);
}
end:
spdlog::info("Display thread done.");
return nullptr;
}
// signal
int signal_flag = 0;
int return_value = 0;
void sig_handler(int signum)
{
spdlog::info("Received signal {}", signum);
signal_flag++;
mavlink_thread_signal++;
wfb_thread_signal++;
osd_thread_signal++;
if (dvr_raw != NULL) {
dvr_raw->shutdown();
}
if (dvr_reenc_inst != NULL) {
dvr_reenc_inst->shutdown();
}
if (frame_proc != NULL) {
frame_proc->shutdown();
}
if (reencoder != NULL) {
reencoder->shutdown();
}
return_value = signum;
}
void sigusr1_handler(int signum) {
spdlog::info("Received signal {}", signum);
bool was_enabled = dvr_enabled;
if (was_enabled) {
// Stopping
if (dvr_raw) dvr_raw->stop_recording();
if (dvr_reenc_inst) dvr_reenc_inst->stop_recording();
dvr_enabled = 0;
osd_publish_bool_fact("dvr.recording", NULL, 0, false);
} else {
// Starting
dvr_enabled = 1;
osd_publish_bool_fact("dvr.recording", NULL, 0, true);
if (dvr_raw) dvr_raw->start_recording();
if (dvr_reenc_inst) dvr_reenc_inst->start_recording();
if (reencoder) reencoder->request_idr();
}
}
void sigusr2_handler(int signum) {
// Toggle the disable_vsync flag
disable_vsync = disable_vsync ^ 1;
// Open the file for writing
std::ofstream outFile("/run/pixelpilot.msg");
if (!outFile.is_open()) {
spdlog::error("Error opening file!");
return; // Exit the function if the file cannot be opened
}
// Write the formatted text to the file
outFile << "disable_vsync: " << std::boolalpha << disable_vsync << std::endl;
outFile.close();
// Log the new state of disable_vsync
spdlog::info("disable_vsync: {}", disable_vsync);
}
// Helper: create a filename template with a suffix inserted before the extension.
// Returns a strdup'd string — caller must free.
static char* dvr_template_with_suffix(const char *tpl, const char *suffix) {
std::string s(tpl);
auto dot = s.rfind('.');
if (dot != std::string::npos)
s.insert(dot, suffix);
else
s.append(suffix);
return strdup(s.c_str());
}
// Shutdown helper for DVR + encoder teardown context.
struct DvrShutdownCtx {
Dvr *dvr_inst;
FrameProcessor *p;
MppEncoder *e;
pthread_t td, tp, te;
};
static void *dvr_shutdown_worker(void *arg) {
auto *ctx = static_cast<DvrShutdownCtx *>(arg);
if (ctx->tp) pthread_join(ctx->tp, nullptr);
if (ctx->te) pthread_join(ctx->te, nullptr);
if (ctx->td) pthread_join(ctx->td, nullptr);
delete ctx->p;
delete ctx->e;
delete ctx->dvr_inst;
delete ctx;
return nullptr;
}
// C-compatible interface for gsmenu live control of the DVR.
extern "C" {
void dvr_reenc_set_fps(int fps) {
if (dvr_reenc_inst) dvr_reenc_inst->stop_recording();
reenc_params.fps = fps;
if (dvr_reenc_inst) dvr_reenc_inst->set_video_framerate(fps);
if (frame_proc) frame_proc->set_fps(fps);
if (reencoder) reencoder->set_fps(fps);
}
void dvr_reenc_set_osd(int enabled) {
dvr_osd = (bool)enabled;
if (!enabled && frame_proc)
frame_proc->set_osd_blend(-1, 0, 0, 0);
}
void dvr_reenc_notify_colortrans(int enabled) {
if (!frame_proc) return;
if (enabled)
frame_proc->set_color_correction(live_colortrans_gain, live_colortrans_offset, drm_fd);
else
frame_proc->set_color_correction_enabled(false);
}
int dvr_reenc_get_fps(void) { return reenc_params.fps; }
int dvr_reenc_get_bitrate(void) { return reenc_params.bitrate_kbps; }
int dvr_reenc_get_osd(void) { return (int)dvr_osd; }
int dvr_reenc_get_codec(void) { return (int)reenc_params.codec - 1; } // 0=h264, 1=h265
int dvr_reenc_get_resolution(void) { return (int)reenc_params.resolution; } // 0=720p, 1=1080p
int dvr_get_mode(void) { return (int)dvr_mode; }
// Deprecated — use dvr_get_mode() instead
int dvr_reenc_is_reenc(void) { return dvr_mode != DVR_MODE_RAW; }
void dvr_set_max_size(int mb) {
dvr_max_file_size = (int64_t)mb * 1000000LL;
if (dvr_raw) dvr_raw->set_max_file_size(dvr_max_file_size);
if (dvr_reenc_inst) dvr_reenc_inst->set_max_file_size(dvr_max_file_size);
spdlog::info("DVR max file size set to {} MB", mb);
}
int dvr_get_max_size(void) { return (int)(dvr_max_file_size / 1000000LL); }
void drm_set_video_scale(float factor) {
if (output_list) {
output_list->video_scale_factor = factor;
modeset_apply_video_scale(drm_fd, output_list);
}
}
void dvr_reenc_set_resolution(int idx) {
if (dvr_reenc_inst) dvr_reenc_inst->stop_recording();
reenc_params.resolution = (EncResolution)idx;
if (frame_proc) frame_proc->set_resolution(reenc_params.resolution);
if (dvr_reenc_inst) {
uint32_t rw, rh; reenc_target_dims(rw, rh);
dvr_reenc_inst->set_video_params(rw, rh, reenc_params.codec);
}
}
void dvr_reenc_set_bitrate(int kbps) {
reenc_params.bitrate_kbps = kbps;
if (reencoder) reencoder->set_bitrate(kbps);
}
void dvr_reenc_set_codec(int idx) {
if (dvr_reenc_inst) dvr_reenc_inst->stop_recording();
VideoCodec vc = (idx == 1) ? VideoCodec::H265 : VideoCodec::H264;
reenc_params.codec = vc;
if (reencoder) reencoder->set_codec(vc);
if (dvr_reenc_inst) {
uint32_t rw, rh; reenc_target_dims(rw, rh);
dvr_reenc_inst->set_video_params(rw, rh, vc);
}
}
void dvr_start_all(void) {
dvr_enabled = 1;
osd_publish_bool_fact("dvr.recording", NULL, 0, true);
if (dvr_raw) dvr_raw->start_recording();
if (dvr_reenc_inst) dvr_reenc_inst->start_recording();
if (reencoder) reencoder->request_idr();
}
void dvr_stop_all(void) {
if (dvr_raw) dvr_raw->stop_recording();
if (dvr_reenc_inst) dvr_reenc_inst->stop_recording();
dvr_enabled = 0;
osd_publish_bool_fact("dvr.recording", NULL, 0, false);
}
// Switch DVR mode at runtime. Stops any active recording.
// mode: 0=raw, 1=reencode, 2=both
void dvr_set_mode(int mode) {
DvrMode new_mode = (DvrMode)mode;
if (new_mode == dvr_mode) return;
// Stop any active recording
dvr_stop_all();
bool old_has_raw = (dvr_mode == DVR_MODE_RAW || dvr_mode == DVR_MODE_BOTH);
bool old_has_reenc = (dvr_mode == DVR_MODE_REENCODE || dvr_mode == DVR_MODE_BOTH);
bool new_has_raw = (new_mode == DVR_MODE_RAW || new_mode == DVR_MODE_BOTH);
bool new_has_reenc = (new_mode == DVR_MODE_REENCODE || new_mode == DVR_MODE_BOTH);
// Tear down encoder pipeline if no longer needed
if (old_has_reenc && !new_has_reenc) {
FrameProcessor *p = frame_proc;
MppEncoder *e = reencoder;
Dvr *d = dvr_reenc_inst;
pthread_t tp = g_tid_fproc;
pthread_t te = g_tid_enc;
pthread_t td = g_tid_dvr_reenc;
frame_proc = nullptr;
reencoder = nullptr;
dvr_reenc_inst = nullptr;
g_tid_fproc = 0;
g_tid_enc = 0;
g_tid_dvr_reenc = 0;
if (p) p->shutdown();
if (e) e->shutdown();
if (d) d->shutdown();
auto *ctx = new DvrShutdownCtx{d, p, e, td, tp, te};
pthread_t cleanup_tid;
pthread_create(&cleanup_tid, NULL, dvr_shutdown_worker, ctx);
pthread_detach(cleanup_tid);
}
// Tear down raw DVR if no longer needed
if (old_has_raw && !new_has_raw) {
Dvr *d = dvr_raw;
pthread_t td = g_tid_dvr_raw;
dvr_raw = nullptr;
g_tid_dvr_raw = 0;
if (d) d->shutdown();
auto *ctx = new DvrShutdownCtx{d, nullptr, nullptr, td, 0, 0};
pthread_t cleanup_tid;
pthread_create(&cleanup_tid, NULL, dvr_shutdown_worker, ctx);
pthread_detach(cleanup_tid);
}
// Create raw DVR if newly needed
if (new_has_raw && !dvr_raw && dvr_template) {
dvr_thread_params args;
bool both = (new_mode == DVR_MODE_BOTH);
char *tpl = both ? dvr_template_with_suffix(dvr_template, "_raw") : dvr_template;
args.filename_template = tpl;
args.mp4_fragmentation_mode = mp4_fragmentation_mode;
args.dvr_filenames_with_sequence = dvr_filenames_with_sequence;
args.video_framerate = video_framerate;
args.max_file_size = dvr_max_file_size;
args.video_p.video_frm_width = output_list ? output_list->video_frm_width : 0;
args.video_p.video_frm_height = output_list ? output_list->video_frm_height : 0;
args.video_p.codec = codec;
dvr_raw = new Dvr(args);
pthread_create(&g_tid_dvr_raw, NULL, &Dvr::__THREAD__, dvr_raw);
}
// Create encoder pipeline + reenc DVR if newly needed
if (new_has_reenc && !reencoder && dvr_template) {
bool both = (new_mode == DVR_MODE_BOTH);
char *tpl = both ? dvr_template_with_suffix(dvr_template, "_reenc") : dvr_template;
dvr_thread_params args;
args.filename_template = tpl;
args.mp4_fragmentation_mode = mp4_fragmentation_mode;
args.dvr_filenames_with_sequence = dvr_filenames_with_sequence;
args.video_framerate = reenc_params.fps;
args.max_file_size = dvr_max_file_size;
uint32_t rw, rh; reenc_target_dims(rw, rh);
args.video_p.video_frm_width = rw;
args.video_p.video_frm_height = rh;
args.video_p.codec = reenc_params.codec;
dvr_reenc_inst = new Dvr(args);
pthread_create(&g_tid_dvr_reenc, NULL, &Dvr::__THREAD__, dvr_reenc_inst);
reencoder = new MppEncoder(reenc_params,
[](std::shared_ptr<std::vector<uint8_t>> nal) {
if (dvr_enabled && dvr_reenc_inst) dvr_reenc_inst->frame(nal);
});
pthread_create(&g_tid_enc, NULL, &MppEncoder::__THREAD__, reencoder);
frame_proc = new FrameProcessor(reencoder, reenc_params.fps, reenc_params.resolution, drm_fd);
if (enable_live_colortrans)
frame_proc->set_color_correction(live_colortrans_gain,
live_colortrans_offset, drm_fd);
pthread_create(&g_tid_fproc, NULL, &FrameProcessor::__THREAD__, frame_proc);
dvr_reenc_inst->on_start_cb = []() { if (reencoder) reencoder->request_idr(); };
}
dvr_mode = new_mode;
spdlog::info("DVR mode set to {}", mode == 0 ? "raw" : mode == 1 ? "reencode" : "both");
}
// Deprecated wrapper for backward compatibility
void dvr_reenc_set_mode(int enabled) {
dvr_set_mode(enabled ? DVR_MODE_REENCODE : DVR_MODE_RAW);
}
}
int decoder_stalled_count=0;
bool feed_packet_to_decoder(MppPacket *packet,void* data_p,int data_len){
mpp_packet_set_data(packet, data_p);
mpp_packet_set_size(packet, data_len);
mpp_packet_set_pos(packet, data_p);
mpp_packet_set_length(packet, data_len);
mpp_packet_set_pts(packet,(RK_S64) get_time_ms());
// Feed the data to mpp until either timeout (in which case the decoder might have stalled)
// or success
uint64_t data_feed_begin = get_time_ms();
int ret=0;
while (!signal_flag && MPP_OK != (ret = mpi.mpi->decode_put_packet(mpi.ctx, packet))) {
uint64_t elapsed = get_time_ms() - data_feed_begin;
osd_publish_uint_fact("video.decoder_feed_time_ms", NULL, 0, elapsed);
if (elapsed > 100) {
decoder_stalled_count++;
spdlog::warn("Cannot feed decoder, stalled {} ?", decoder_stalled_count);
return false;
}
usleep(2 * 1000);
}
return true;
}
std::unique_ptr<GstRtpReceiver> receiver;
static MppCodingType current_mpp_type = MPP_VIDEO_CodingHEVC;
static MppCodingType stream_mpp_type = MPP_VIDEO_CodingHEVC;
static void reinit_mpp_decoder(MppCodingType new_type) {
if (new_type == current_mpp_type) return;
spdlog::info("Reinitializing MPP decoder: {} -> {}",
current_mpp_type == MPP_VIDEO_CodingHEVC ? "H.265" : "H.264",
new_type == MPP_VIDEO_CodingHEVC ? "H.265" : "H.264");
// Signal frame thread to release the lock, then acquire it
mpp_reinit_pending.store(true, std::memory_order_release);
mpi.mpi->reset(mpi.ctx);
pthread_mutex_lock(&mpp_reinit_mutex);
mpp_destroy(mpi.ctx);
mpi.ctx = nullptr;
mpi.mpi = nullptr;
int ret = mpp_create(&mpi.ctx, &mpi.mpi);
assert(!ret);
set_mpp_decoding_parameters(mpi.mpi, mpi.ctx);
ret = mpp_init(mpi.ctx, MPP_CTX_DEC, new_type);
assert(!ret);
set_mpp_decoding_parameters(mpi.mpi, mpi.ctx);
int param = MPP_POLL_BLOCK;
ret = mpi.mpi->control(mpi.ctx, MPP_SET_OUTPUT_BLOCK, ¶m);
assert(!ret);
current_mpp_type = new_type;
mpp_reinit_pending.store(false, std::memory_order_release);
pthread_mutex_unlock(&mpp_reinit_mutex);
}
void switch_pipeline_source(const char * source_type, const char * source_path) {
if (strcmp(source_type, "file") == 0) {
VideoCodec file_codec = receiver->switch_to_file_playback(source_path);
MppCodingType new_type = (file_codec == VideoCodec::H265)
? MPP_VIDEO_CodingHEVC : MPP_VIDEO_CodingAVC;
reinit_mpp_decoder(new_type);
} else if (strcmp(source_type, "stream") == 0) {
receiver->switch_to_stream();
reinit_mpp_decoder(stream_mpp_type);
} else {
spdlog::error("Unknown source type: {}", source_type);
}
}
void fast_forward(double rate){
receiver->fast_forward();
}
void fast_rewind(double rate){
receiver->fast_rewind();
}
void skip_duration(int64_t skip_ms){
receiver->skip_duration(skip_ms);
}
void normal_playback() {
receiver->normal_playback();
}
void pause_playback() {
receiver->pause();
}
void resume_playback() {
receiver->resume();
}
class CustomMsgManager {
public:
CustomMsgManager(const char* fifoName, bool enabled) : fifoName(fifoName), fd(-1), enabled(enabled) {}
int open_fifo() {
if (!enabled) {
return 0;
}
// Kill FIFO if already exists
if (access(fifoName, F_OK) == 0) {
unlink(fifoName);
}
if (mkfifo(fifoName, 0622) == -1) {
spdlog::error("Failed to create FIFO {}: {}", fifoName, strerror(errno));
return -1;
}
// Change permissions to allow write for everyone
if (chmod(fifoName, 0622) == -1) {
spdlog::error("Failed to change permissions {}: {}", fifoName, strerror(errno));
return -2;
}
// Open the FIFO for reading
fd = open(fifoName, O_RDONLY | O_NONBLOCK);
if (fd == -1) {
spdlog::error("Failed to open FIFO {}: {}", fifoName, strerror(errno));
return -3;
}
return 0;
}
void check_message() {
if (!enabled) {
return;
} else if (fd == -1) {
spdlog::error("FIFO is not initialized.");
return; // Avoid reading if FIFO is not initialized
}
// fd is non-blocking
char chunk[120];
ssize_t bytes_read = read(fd, chunk, sizeof(chunk));
if (bytes_read > 0) {
buffer.append(chunk, bytes_read);
}
// Emit one fact per `\n`-terminated message. If the buffer grows past
// MAX_MSG_LEN without a newline, flush it anyway so a stuck writer
// cannot make us grow unboundedly.
while (true) {
size_t nl = buffer.find('\n');
if (nl == std::string::npos) {
if (buffer.size() >= MAX_MSG_LEN) {
publish_message(buffer);
buffer.clear();
}
break;
}
std::string msg = buffer.substr(0, nl);
buffer.erase(0, nl + 1);
if (!msg.empty()) {
publish_message(msg);
}
}
}
// Unescape `\\n` -> literal newline so writers that cannot emit a raw
// newline (eg shell `echo` without `-e`) can still build multi-line
// messages.
static std::string unescape_newlines(const std::string& in) {
std::string out;
out.reserve(in.size());
for (size_t i = 0; i < in.size(); ++i) {
if (in[i] == '\\' && i + 1 < in.size() && in[i + 1] == 'n') {
out.push_back('\n');
++i;
} else {
out.push_back(in[i]);
}
}
return out;
}
void publish_message(const std::string& raw) {
osd_tag tags[1];
strcpy(tags[0].key, "file");
strcpy(tags[0].val, fifoName);
std::string msg = unescape_newlines(raw);
osd_publish_str_fact("osd.custom_message", tags, 1, msg.c_str());
}
~CustomMsgManager() {
if (fd != -1) {
close(fd);
}
unlink(fifoName);
}
private:
static constexpr size_t MAX_MSG_LEN = 512;
const char* fifoName;
int fd; // File descriptor for the FIFO
bool enabled;
std::string buffer; // accumulates partial reads until a `\n` is seen
};
void main_loop() {
CustomMsgManager msg_manager(MSG_FIFO_NAME, osd_custom_message);
if (msg_manager.open_fifo() != 0) {
return;
}
while (!signal_flag) {
// TODO: put gsmenu main loop here
msg_manager.check_message();
os_sensors.run();
if (RXMODE == APFPV) {
wifi_monitor.run();
}
sleep(1);
}
return;
}
uint64_t first_frame_ms=0;
void read_gstreamerpipe_stream(MppPacket *packet, int gst_udp_port, const char *sock ,const VideoCodec& codec){
if (sock) {
receiver = std::make_unique<GstRtpReceiver>(sock, codec);
} else {
receiver = std::make_unique<GstRtpReceiver>(gst_udp_port, codec);
}
long long bytes_received = 0;
uint64_t period_start=0;
auto cb=[&packet,/*&decoder_stalled_count,*/ &bytes_received, &period_start](std::shared_ptr<std::vector<uint8_t>> frame){
// Let the gst pull thread run at quite high priority
static bool first= false;
static int stall_count = 0;
static uint64_t last_stall_idr_ms = 0;
if(first){
SchedulingHelper::set_thread_params_max_realtime("DisplayThread",SchedulingHelper::PRIORITY_REALTIME_LOW);
first= false;
}
bytes_received += frame->size();
uint64_t now = get_time_ms();
osd_publish_uint_fact("gstreamer.received_bytes", NULL, 0, frame->size());
const bool fed_ok = feed_packet_to_decoder(packet,frame->data(),frame->size());
if (!fed_ok) {
stall_count++;