forked from iizukanao/picam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.c
6120 lines (5540 loc) · 219 KB
/
stream.c
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
/*
* Capture video from Raspberry Pi Camera and audio from ALSA,
* encode them to H.264/AAC, and mux them to MPEG-TS.
*
* H.264 encoder: Raspberry Pi H.264 hardware encoder (via OpenMAX IL)
* AAC encoder : fdk-aac (via libavcodec)
* MPEG-TS muxer: libavformat
*/
#if defined(__cplusplus)
extern "C" {
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/statvfs.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <alsa/asoundlib.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/mathematics.h>
#include <getopt.h>
#include "bcm_host.h"
#include "ilclient.h"
#include "hooks.h"
#include "mpegts.h"
#include "httplivestreaming.h"
#include "state.h"
#include "log.h"
#include "text.h"
#include "dispmanx.h"
#include "timestamp.h"
#include "subtitle.h"
#define PROGRAM_NAME "picam"
#define PROGRAM_VERSION "1.4.6"
// Audio-only stream is created if this is 1 (for debugging)
#define AUDIO_ONLY 0
// ALSA buffer size for capture will be multiplied by this number
#define ALSA_BUFFER_MULTIPLY 100
// ALSA buffer size for playback will be multiplied by this number (max: 16)
#define ALSA_PLAYBACK_BUFFER_MULTIPLY 10
// If this is 1, PTS will be reset to zero when it exceeds PTS_MODULO
#define ENABLE_PTS_WRAP_AROUND 0
#if ENABLE_PTS_WRAP_AROUND
// Both PTS and DTS are 33 bit and wraps around to zero
#define PTS_MODULO 8589934592
#endif
// Internal flag indicates that audio is available for read
#define AVAIL_AUDIO 2
// If this value is increased, audio gets faster than video
#define N_BUFFER_COUNT_ACTUAL 1
// If this value is increased, video gets faster than audio
#define AUDIO_BUFFER_CHUNKS 0
// How much PTS difference between audio and video is
// considered to be too large
#define PTS_DIFF_TOO_LARGE 45000 // 90000 == 1 second
// enum
#define EXPOSURE_AUTO 0
#define EXPOSURE_NIGHT 1
// Number of packets to chase recording for each cycle
#define REC_CHASE_PACKETS 10
// Which color (YUV) is used to fill blank borders
#define FILL_COLOR_Y 0
#define FILL_COLOR_U 128
#define FILL_COLOR_V 128
// Whether or not to pass pBuffer from camera to video_encode directly
#define ENABLE_PBUFFER_OPTIMIZATION_HACK 1
#if ENABLE_PBUFFER_OPTIMIZATION_HACK
static OMX_BUFFERHEADERTYPE *video_encode_input_buf = NULL;
static OMX_U8 *video_encode_input_buf_pBuffer_orig = NULL;
#endif
#define ENABLE_AUTO_GOP_SIZE_CONTROL_FOR_VFR 1
// OpenMAX IL ports
static const int CAMERA_PREVIEW_PORT = 70;
static const int CAMERA_CAPTURE_PORT = 71;
static const int CAMERA_INPUT_PORT = 73;
static const int CLOCK_OUTPUT_1_PORT = 80;
static const int VIDEO_RENDER_INPUT_PORT = 90;
static const int VIDEO_ENCODE_INPUT_PORT = 200;
static const int VIDEO_ENCODE_OUTPUT_PORT = 201;
// Directory to put recorded MPEG-TS files
static char *rec_dir = "rec";
static char *rec_tmp_dir = "rec/tmp";
static char *rec_archive_dir = "rec/archive";
// Whether or not to enable clock OMX component
static const int is_clock_enabled = 1;
// Pace of PTS
typedef enum {
PTS_SPEED_NORMAL,
PTS_SPEED_UP,
PTS_SPEED_DOWN,
} pts_mode_t;
typedef struct EncodedPacket {
int64_t pts;
uint8_t *data;
int size;
int stream_index;
int flags;
} EncodedPacket;
static const int log_level_default = LOG_LEVEL_INFO;
static int video_width;
static const int video_width_default = 1280;
static int video_width_32;
static int video_height;
static const int video_height_default = 720;
static int video_height_16;
static float video_fps;
static const float video_fps_default = 30.0f;
static int video_pts_step;
static const int video_pts_step_default = 0;
static int video_gop_size;
static const int video_gop_size_default = 0;
static int video_rotation;
static const int video_rotation_default = 0;
static int video_hflip;
static const int video_hflip_default = 0;
static int video_vflip;
static const int video_vflip_default = 0;
static long video_bitrate;
static const long video_bitrate_default = 2000 * 1000; // 2 Mbps
static char video_avc_profile[21];
static const char *video_avc_profile_default = "constrained_baseline";
typedef struct video_avc_profile_option {
char *name;
OMX_VIDEO_AVCPROFILETYPE profile;
} video_avc_profile_option;
static const video_avc_profile_option video_avc_profile_options[] = {
{ .name = "constrained_baseline", .profile = OMX_VIDEO_AVCProfileConstrainedBaseline },
{ .name = "baseline", .profile = OMX_VIDEO_AVCProfileBaseline },
{ .name = "main", .profile = OMX_VIDEO_AVCProfileMain },
{ .name = "high", .profile = OMX_VIDEO_AVCProfileHigh },
};
static char video_avc_level[4];
static const char *video_avc_level_default = "3.1";
typedef struct video_avc_level_option {
char *name;
OMX_VIDEO_AVCLEVELTYPE level;
} video_avc_level_option;
static const video_avc_level_option video_avc_level_options[] = {
{ .name = "1", .level = OMX_VIDEO_AVCLevel1 },
{ .name = "1b", .level = OMX_VIDEO_AVCLevel1b },
{ .name = "1.1", .level = OMX_VIDEO_AVCLevel11 },
{ .name = "1.2", .level = OMX_VIDEO_AVCLevel12 },
{ .name = "1.3", .level = OMX_VIDEO_AVCLevel13 },
{ .name = "2", .level = OMX_VIDEO_AVCLevel2 },
{ .name = "2.1", .level = OMX_VIDEO_AVCLevel21 },
{ .name = "2.2", .level = OMX_VIDEO_AVCLevel22 },
{ .name = "3", .level = OMX_VIDEO_AVCLevel3 },
{ .name = "3.1", .level = OMX_VIDEO_AVCLevel31 },
{ .name = "3.2", .level = OMX_VIDEO_AVCLevel32 },
{ .name = "4", .level = OMX_VIDEO_AVCLevel4 },
{ .name = "4.1", .level = OMX_VIDEO_AVCLevel41 },
{ .name = "4.2", .level = OMX_VIDEO_AVCLevel42 },
{ .name = "5", .level = OMX_VIDEO_AVCLevel5 },
{ .name = "5.1", .level = OMX_VIDEO_AVCLevel51 },
};
static int video_qp_min;
static const int video_qp_min_default = -1;
static int video_qp_max;
static const int video_qp_max_default = -1;
static int video_qp_initial;
static const int video_qp_initial_default = -1;
static int video_slice_dquant;
static const int video_slice_dquant_default = -1;
static char alsa_dev[256];
static const char *alsa_dev_default = "hw:0,0";
static char audio_preview_dev[256];
static const char *audio_preview_dev_default = "plughw:0,0";
static long audio_bitrate;
static const long audio_bitrate_default = 40000; // 40 Kbps
static int is_audio_channels_specified = 0;
static int audio_channels;
static int audio_preview_channels;
static const int audio_channels_default = 1; // mono
static int audio_sample_rate;
static const int audio_sample_rate_default = 48000;
static int is_hlsout_enabled;
static const int is_hlsout_enabled_default = 0;
static char hls_output_dir[256];
static const char *hls_output_dir_default = "/run/shm/video";
static int is_rtspout_enabled;
static const int is_rtspout_enabled_default = 0;
static char rtsp_video_control_path[256];
static const char *rtsp_video_control_path_default = "/tmp/node_rtsp_rtmp_videoControl";
static char rtsp_audio_control_path[256];
static const char *rtsp_audio_control_path_default = "/tmp/node_rtsp_rtmp_audioControl";
static char rtsp_video_data_path[256];
static const char *rtsp_video_data_path_default = "/tmp/node_rtsp_rtmp_videoData";
static char rtsp_audio_data_path[256];
static const char *rtsp_audio_data_path_default = "/tmp/node_rtsp_rtmp_audioData";
static int is_tcpout_enabled;
static const int is_tcpout_enabled_default = 0;
static char tcp_output_dest[256];
static int is_auto_exposure_enabled;
static const int is_auto_exposure_enabled_default = 0;
static int is_vfr_enabled; // whether variable frame rate is enabled
static const int is_vfr_enabled_default = 0;
static float auto_exposure_threshold;
static const float auto_exposure_threshold_default = 5.0f;
static float roi_left;
static const float roi_left_default = 0.0f;
static float roi_top;
static const float roi_top_default = 0.0f;
static float roi_width;
static const float roi_width_default = 1.0f;
static float roi_height;
static const float roi_height_default = 1.0f;
static char white_balance[13];
static const char *white_balance_default = "auto";
typedef struct white_balance_option {
char *name;
OMX_WHITEBALCONTROLTYPE control;
} white_balance_option;
static const white_balance_option white_balance_options[] = {
{ .name = "off", .control = OMX_WhiteBalControlOff },
{ .name = "auto", .control = OMX_WhiteBalControlAuto },
{ .name = "sun", .control = OMX_WhiteBalControlSunLight },
{ .name = "cloudy", .control = OMX_WhiteBalControlCloudy },
{ .name = "shade", .control = OMX_WhiteBalControlShade },
{ .name = "tungsten", .control = OMX_WhiteBalControlTungsten },
{ .name = "fluorescent", .control = OMX_WhiteBalControlFluorescent },
{ .name = "incandescent", .control = OMX_WhiteBalControlIncandescent },
{ .name = "flash", .control = OMX_WhiteBalControlFlash },
{ .name = "horizon", .control = OMX_WhiteBalControlHorizon },
};
static char exposure_control[14];
static const char *exposure_control_default = "auto";
typedef struct exposure_control_option {
char *name;
OMX_EXPOSURECONTROLTYPE control;
} exposure_control_option;
static const exposure_control_option exposure_control_options[] = {
{ .name = "off", .control = OMX_ExposureControlOff },
{ .name = "auto", .control = OMX_ExposureControlAuto },
{ .name = "night", .control = OMX_ExposureControlNight },
{ .name = "nightpreview", .control = OMX_ExposureControlNightWithPreview },
{ .name = "backlight", .control = OMX_ExposureControlBackLight },
{ .name = "spotlight", .control = OMX_ExposureControlSpotLight },
{ .name = "sports", .control = OMX_ExposureControlSports },
{ .name = "snow", .control = OMX_ExposureControlSnow },
{ .name = "beach", .control = OMX_ExposureControlBeach },
{ .name = "verylong", .control = OMX_ExposureControlVeryLong },
{ .name = "fixedfps", .control = OMX_ExposureControlFixedFps },
{ .name = "antishake", .control = OMX_ExposureControlAntishake },
{ .name = "fireworks", .control = OMX_ExposureControlFireworks },
{ .name = "largeaperture", .control = OMX_ExposureControlLargeAperture },
{ .name = "smallaperture", .control = OMX_ExposureControlSmallAperture },
};
// Red gain used when AWB is off
static float awb_red_gain;
static const float awb_red_gain_default = 0.0f;
// Blue gain used when AWB is off
static float awb_blue_gain;
static const float awb_blue_gain_default = 0.0f;
static char exposure_metering[8];
static const char *exposure_metering_default = "average";
typedef struct exposure_metering_option {
char *name;
OMX_METERINGTYPE metering;
} exposure_metering_option;
static const exposure_metering_option exposure_metering_options[] = {
{ .name = "average", .metering = OMX_MeteringModeAverage },
{ .name = "spot", .metering = OMX_MeteringModeSpot },
{ .name = "matrix", .metering = OMX_MeteringModeMatrix },
{ .name = "backlit", .metering = OMX_MeteringModeBacklit },
};
static int manual_exposure_compensation = 0; // EV compensation
static float exposure_compensation;
static int manual_exposure_aperture = 0; // f-number
static float exposure_aperture;
static int manual_exposure_shutter_speed = 0; // in microseconds
static unsigned int exposure_shutter_speed;
static int manual_exposure_sensitivity = 0; // ISO
static unsigned int exposure_sensitivity;
static char state_dir[256];
static const char *state_dir_default = "state";
static char hooks_dir[256];
static const char *hooks_dir_default = "hooks";
static float audio_volume_multiply;
static const float audio_volume_multiply_default = 1.0f;
static int audio_min_value;
static int audio_max_value;
static int is_hls_encryption_enabled;
static const int is_hls_encryption_enabled_default = 0;
static char hls_encryption_key_uri[256];
static const char *hls_encryption_key_uri_default = "stream.key";
static uint8_t hls_encryption_key[16] = {
0x75, 0xb0, 0xa8, 0x1d, 0xe1, 0x74, 0x87, 0xc8,
0x8a, 0x47, 0x50, 0x7a, 0x7e, 0x1f, 0xdf, 0x73,
};
static uint8_t hls_encryption_key_default[16] = {
0x75, 0xb0, 0xa8, 0x1d, 0xe1, 0x74, 0x87, 0xc8,
0x8a, 0x47, 0x50, 0x7a, 0x7e, 0x1f, 0xdf, 0x73,
};
static uint8_t hls_encryption_iv[16] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
};
static uint8_t hls_encryption_iv_default[16] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
};
static int is_preview_enabled;
static const int is_preview_enabled_default = 0;
static int is_previewrect_enabled;
static const int is_previewrect_enabled_default = 0;
static int preview_x;
static int preview_y;
static int preview_width;
static int preview_height;
static int preview_opacity;
static uint32_t blank_background_color;
static const int preview_opacity_default = 255;
static int record_buffer_keyframes;
static const int record_buffer_keyframes_default = 5;
static int is_timestamp_enabled = 0;
static char timestamp_format[128];
static const char *timestamp_format_default = "%a %b %d %l:%M:%S %p";
static LAYOUT_ALIGN timestamp_layout;
static const LAYOUT_ALIGN timestamp_layout_default = LAYOUT_ALIGN_BOTTOM | LAYOUT_ALIGN_RIGHT;
static int timestamp_horizontal_margin;
static const int timestamp_horizontal_margin_default = 10;
static int timestamp_vertical_margin;
static const int timestamp_vertical_margin_default = 10;
static int timestamp_pos_x;
static int timestamp_pos_y;
static int is_timestamp_abs_pos_enabled = 0;
static TEXT_ALIGN timestamp_text_align;
static const TEXT_ALIGN timestamp_text_align_default = TEXT_ALIGN_LEFT;
static char timestamp_font_name[128];
static const char *timestamp_font_name_default = "FreeMono:style=Bold";
static char timestamp_font_file[1024];
static int timestamp_font_face_index;
static const int timestamp_font_face_index_default = 0;
static float timestamp_font_points;
static const float timestamp_font_points_default = 14.0f;
static int timestamp_font_dpi;
static const int timestamp_font_dpi_default = 96;
static int timestamp_color;
static const int timestamp_color_default = 0xffffff;
static int timestamp_stroke_color;
static const int timestamp_stroke_color_default = 0x000000;
static float timestamp_stroke_width;
static const float timestamp_stroke_width_default = 1.3f;
static int timestamp_letter_spacing;
static const int timestamp_letter_spacing_default = 0;
// how many keyframes should we look back for the next recording
static int recording_look_back_keyframes;
static int64_t video_current_pts = 0;
static int64_t audio_current_pts = 0;
static int64_t last_pts = 0;
static int64_t time_for_last_pts = 0; // Used in VFR mode
pts_mode_t pts_mode = PTS_SPEED_NORMAL;
// Counter for PTS speed up/down
static int speed_up_count = 0;
static int speed_down_count = 0;
static int audio_pts_step_base;
#if AUDIO_BUFFER_CHUNKS > 0
uint16_t *audio_buffer[AUDIO_BUFFER_CHUNKS];
int audio_buffer_index = 0;
int is_audio_buffer_filled = 0;
#endif
// If this value is 1, audio capturing is always disabled.
static int disable_audio_capturing = 0;
static pthread_t audio_nop_thread;
static int fr_q16;
// Function prototypes
static int camera_set_white_balance(char *wb);
static int camera_set_exposure_control(char *ex);
static int camera_set_custom_awb_gains();
static void encode_and_send_image();
static void encode_and_send_audio();
void start_record();
void stop_record();
#if ENABLE_AUTO_GOP_SIZE_CONTROL_FOR_VFR
static void set_gop_size(int gop_size);
#endif
static long long video_frame_count = 0;
static long long audio_frame_count = 0;
static int64_t video_start_time;
static int64_t audio_start_time;
static int is_video_recording_started = 0;
static int is_audio_recording_started = 0;
static uint8_t *last_video_buffer = NULL;
static size_t last_video_buffer_size = 0;
static int keyframes_count = 0;
static int video_pending_drop_frames = 0;
static int audio_pending_drop_frames = 0;
static COMPONENT_T *video_encode = NULL;
static COMPONENT_T *component_list[5];
static int n_component_list = 0;
static ILCLIENT_T *ilclient;
static ILCLIENT_T *cam_client;
static COMPONENT_T *camera_component = NULL;
static COMPONENT_T *render_component = NULL;
static COMPONENT_T *clock_component = NULL;
static TUNNEL_T tunnel[3]; // Must be null-terminated
static int n_tunnel = 0;
static AVFormatContext *tcp_ctx;
static pthread_mutex_t tcp_mutex = PTHREAD_MUTEX_INITIALIZER;
static int current_exposure_mode = EXPOSURE_AUTO;
static int keepRunning = 1;
static int frame_count = 0;
static int current_audio_frames = 0;
static uint8_t *codec_configs[2];
static int codec_config_sizes[2];
static int codec_config_total_size = 0;
static int n_codec_configs = 0;
static struct timespec tsBegin = { .tv_sec = 0, .tv_nsec = 0 };
static AVFormatContext *rec_format_ctx;
static int flush_recording_seconds = 5; // Flush recording data every 5 seconds
static time_t rec_start_time;
static HTTPLiveStreaming *hls;
// NAL unit type 9
static uint8_t access_unit_delimiter[] = {
0x00, 0x00, 0x00, 0x01, 0x09, 0xf0,
};
static int access_unit_delimiter_length = 6;
// sound
static snd_pcm_t *capture_handle;
static snd_pcm_t *audio_preview_handle;
static snd_pcm_hw_params_t *alsa_hw_params;
static uint16_t *samples;
static AVFrame *av_frame;
static int audio_fd_count;
static struct pollfd *poll_fds; // file descriptors for polling audio
static int is_first_audio;
static int period_size;
static int audio_buffer_size;
static int is_audio_preview_enabled;
static const int is_audio_preview_enabled_default = 0;
static int is_audio_preview_device_opened = 0;
// threads
static pthread_mutex_t mutex_writing = PTHREAD_MUTEX_INITIALIZER;
// UNIX domain sockets
static int sockfd_video;
static int sockfd_video_control;
static int sockfd_audio;
static int sockfd_audio_control;
static uint8_t *encbuf = NULL;
static int encbuf_size = -1;
static pthread_t rec_thread;
static pthread_cond_t rec_cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t rec_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t rec_write_mutex = PTHREAD_MUTEX_INITIALIZER;
static int rec_thread_needs_write = 0;
static int rec_thread_needs_exit = 0;
static int rec_thread_frame = 0;
static int rec_thread_needs_flush = 0;
EncodedPacket **encoded_packets; // circular buffer
static int current_encoded_packet = -1;
static int *keyframe_pointers;
static int current_keyframe_pointer = -1;
static int is_keyframe_pointers_filled = 0;
static int encoded_packets_size;
// hooks
static pthread_t hooks_thread;
char recording_filepath[256];
char recording_tmp_filepath[256];
char recording_archive_filepath[1024];
char recording_basename[256];
char recording_dest_dir[1024];
int is_recording = 0;
static MpegTSCodecSettings codec_settings;
static int is_audio_muted = 0;
// Will be set to 1 when the camera finishes capturing
static int is_camera_finished = 0;
#if ENABLE_AUTO_GOP_SIZE_CONTROL_FOR_VFR
// Variables for variable frame rate
static int64_t last_keyframe_pts = 0;
static int frames_since_last_keyframe = 0;
#endif
static float min_fps = -1.0f;
static float max_fps = -1.0f;
// Query camera capabilities and exit
static int query_and_exit = 0;
static pthread_mutex_t camera_finish_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t camera_finish_cond = PTHREAD_COND_INITIALIZER;
static char errbuf[1024];
static void unmute_audio() {
log_info("unmute");
is_audio_muted = 0;
}
static void mute_audio() {
log_info("mute");
is_audio_muted = 1;
}
// Check if disk usage is >= 95%
static int is_disk_almost_full() {
struct statvfs stat;
statvfs("/", &stat);
int used_percent = ceil( (stat.f_blocks - stat.f_bfree) * 100.0f / stat.f_blocks);
log_info("disk_usage=%d%% ", used_percent);
if (used_percent >= 95) {
return 1;
} else {
return 0;
}
}
static void mark_keyframe_packet() {
current_keyframe_pointer++;
if (current_keyframe_pointer >= record_buffer_keyframes) {
current_keyframe_pointer = 0;
if (!is_keyframe_pointers_filled) {
is_keyframe_pointers_filled = 1;
}
}
keyframe_pointers[current_keyframe_pointer] = current_encoded_packet;
}
static void prepare_encoded_packets() {
int audio_fps = audio_sample_rate / 1 / period_size;
encoded_packets_size = (video_fps + 1) * record_buffer_keyframes * 2 +
(audio_fps + 1) * record_buffer_keyframes * 2 + 100;
int malloc_size = sizeof(EncodedPacket *) * encoded_packets_size;
encoded_packets = malloc(malloc_size);
if (encoded_packets == NULL) {
log_error("error: cannot allocate memory for encoded_packets\n");
exit(EXIT_FAILURE);
}
memset(encoded_packets, 0, malloc_size);
}
static int write_encoded_packets(int max_packets, int origin_pts) {
int ret;
AVPacket avpkt;
EncodedPacket *enc_pkt;
av_init_packet(&avpkt);
int wrote_packets = 0;
pthread_mutex_lock(&rec_write_mutex);
while (1) {
wrote_packets++;
enc_pkt = encoded_packets[rec_thread_frame];
avpkt.pts = avpkt.dts = enc_pkt->pts - origin_pts;
avpkt.data = enc_pkt->data;
avpkt.size = enc_pkt->size;
avpkt.stream_index = enc_pkt->stream_index;
avpkt.flags = enc_pkt->flags;
ret = av_write_frame(rec_format_ctx, &avpkt);
if (ret < 0) {
av_strerror(ret, errbuf, sizeof(errbuf));
log_error("error: write_encoded_packets: av_write_frame: %s\n", errbuf);
}
if (++rec_thread_frame == encoded_packets_size) {
rec_thread_frame = 0;
}
if (rec_thread_frame == current_encoded_packet) {
break;
}
if (wrote_packets == max_packets) {
break;
}
}
pthread_mutex_unlock(&rec_write_mutex);
av_free_packet(&avpkt);
return wrote_packets;
}
static void add_encoded_packet(int64_t pts, uint8_t *data, int size, int stream_index, int flags) {
EncodedPacket *packet;
if (++current_encoded_packet == encoded_packets_size) {
current_encoded_packet = 0;
}
packet = encoded_packets[current_encoded_packet];
if (packet != NULL) {
int next_keyframe_pointer = current_keyframe_pointer + 1;
if (next_keyframe_pointer >= record_buffer_keyframes) {
next_keyframe_pointer = 0;
}
if (current_encoded_packet == keyframe_pointers[next_keyframe_pointer]) {
log_warn("warning: Record buffer is starving. Recorded file may not start from keyframe. Try reducing the value of --gopsize.\n");
}
av_freep(&packet->data);
} else {
packet = malloc(sizeof(EncodedPacket));
if (packet == NULL) {
perror("malloc for EncodedPacket");
return;
}
encoded_packets[current_encoded_packet] = packet;
}
packet->pts = pts;
packet->data = data;
packet->size = size;
packet->stream_index = stream_index;
packet->flags = flags;
}
static void free_encoded_packets() {
int i;
EncodedPacket *packet;
for (i = 0; i < encoded_packets_size; i++) {
packet = encoded_packets[i];
if (packet != NULL) {
av_freep(&packet->data);
free(packet);
}
}
}
void setup_av_frame(AVFormatContext *format_ctx) {
AVCodecContext *audio_codec_ctx;
int ret;
int buffer_size;
#if AUDIO_ONLY
audio_codec_ctx = format_ctx->streams[0]->codec;
#else
audio_codec_ctx = format_ctx->streams[1]->codec;
#endif
av_frame = av_frame_alloc();
if (!av_frame) {
log_error("error: av_frame_alloc failed\n");
exit(EXIT_FAILURE);
}
av_frame->sample_rate = audio_codec_ctx->sample_rate;
log_debug("sample_rate: %d\n", audio_codec_ctx->sample_rate);
av_frame->nb_samples = audio_codec_ctx->frame_size;
log_debug("nb_samples: %d\n", audio_codec_ctx->frame_size);
av_frame->format = audio_codec_ctx->sample_fmt;
log_debug("sample_fmt: %d\n", audio_codec_ctx->sample_fmt);
av_frame->channel_layout = audio_codec_ctx->channel_layout;
log_debug("audio_codec_ctx->channel_layout: %" PRIu64 "\n", audio_codec_ctx->channel_layout);
log_debug("av_frame->channel_layout: %" PRIu64 "\n", av_frame->channel_layout);
log_debug("audio_codec_ctx->channels: %d\n", audio_codec_ctx->channels);
log_debug("av_frame->channels: %d\n", av_frame->channels);
buffer_size = av_samples_get_buffer_size(NULL, audio_codec_ctx->channels,
audio_codec_ctx->frame_size, audio_codec_ctx->sample_fmt, 0);
samples = av_malloc(buffer_size);
if (!samples) {
log_error("error: av_malloc for samples failed\n");
exit(EXIT_FAILURE);
}
log_debug("allocated %d bytes for audio samples\n", buffer_size);
#if AUDIO_BUFFER_CHUNKS > 0
int i;
for (i = 0; i < AUDIO_BUFFER_CHUNKS; i++) {
audio_buffer[i] = av_malloc(buffer_size);
if (!audio_buffer[i]) {
log_error("error: av_malloc for audio_buffer[%d] failed\n", i);
exit(EXIT_FAILURE);
}
}
#endif
period_size = buffer_size / audio_channels / sizeof(short);
audio_pts_step_base = 90000.0f * period_size / audio_sample_rate;
log_debug("audio_pts_step_base: %d\n", audio_pts_step_base);
ret = avcodec_fill_audio_frame(av_frame, audio_codec_ctx->channels, audio_codec_ctx->sample_fmt,
(const uint8_t*)samples, buffer_size, 0);
if (ret < 0) {
av_strerror(ret, errbuf, sizeof(errbuf));
log_error("error: avcodec_fill_audio_frame failed: %s\n", errbuf);
exit(EXIT_FAILURE);
}
}
// Create dir if it does not exist
int create_dir(const char *dir) {
struct stat st;
int err;
err = stat(dir, &st);
if (err == -1) {
if (errno == ENOENT) {
// create directory
if (mkdir(dir, 0755) == 0) { // success
log_info("created directory: ./%s\n", dir);
} else { // error
log_error("error creating directory ./%s: %s\n",
dir, strerror(errno));
return -1;
}
} else {
perror("stat directory");
return -1;
}
} else {
if (!S_ISDIR(st.st_mode)) {
log_error("error: ./%s is not a directory\n", dir);
return -1;
}
}
if (access(dir, R_OK) != 0) {
log_error("error: cannot access directory ./%s: %s\n",
dir, strerror(errno));
return -1;
}
return 0;
}
void *rec_thread_stop(int skip_cleanup) {
FILE *fsrc, *fdest;
int read_len;
uint8_t *copy_buf;
log_info("stop rec\n");
if (!skip_cleanup) {
copy_buf = malloc(BUFSIZ);
if (copy_buf == NULL) {
perror("malloc for copy_buf");
pthread_exit(0);
}
pthread_mutex_lock(&rec_write_mutex);
mpegts_close_stream(rec_format_ctx);
mpegts_destroy_context(rec_format_ctx);
pthread_mutex_unlock(&rec_write_mutex);
log_debug("copy ");
fsrc = fopen(recording_tmp_filepath, "r");
if (fsrc == NULL) {
log_error("error: failed to open %s: %s\n",
recording_tmp_filepath, strerror(errno));
}
fdest = fopen(recording_archive_filepath, "a");
if (fdest == NULL) {
log_error("error: failed to open %s: %s\n",
recording_archive_filepath, strerror(errno));
fclose(fsrc);
}
while (1) {
read_len = fread(copy_buf, 1, BUFSIZ, fsrc);
if (read_len > 0) {
fwrite(copy_buf, 1, read_len, fdest);
}
if (read_len != BUFSIZ) {
break;
}
}
if (feof(fsrc)) {
fclose(fsrc);
fclose(fdest);
} else {
log_error("error: rec_thread_stop: not an EOF?: %s\n", strerror(errno));
}
// Create a symlink
char symlink_dest_path[1024];
size_t rec_dir_len = strlen(rec_dir);
struct stat file_stat;
// If recording_archive_filepath starts with "rec/", then remove it
if (strncmp(recording_archive_filepath, rec_dir, rec_dir_len) == 0 &&
recording_archive_filepath[rec_dir_len] == '/') {
snprintf(symlink_dest_path, sizeof(symlink_dest_path),
recording_archive_filepath + rec_dir_len + 1);
} else if (recording_archive_filepath[0] == '/') { // absolute path
snprintf(symlink_dest_path, sizeof(symlink_dest_path),
recording_archive_filepath);
} else { // relative path
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) == NULL) {
log_error("error: failed to get current working directory: %s\n",
strerror(errno));
cwd[0] = '.';
cwd[1] = '.';
cwd[2] = '\0';
}
snprintf(symlink_dest_path, sizeof(symlink_dest_path),
"%s/%s", cwd, recording_archive_filepath);
}
log_debug("symlink(%s, %s)\n", symlink_dest_path, recording_filepath);
if (lstat(recording_filepath, &file_stat) == 0) { // file (symlink) exists
log_info("replacing existing symlink: %s\n", recording_filepath);
unlink(recording_filepath);
}
if (symlink(symlink_dest_path, recording_filepath) != 0) {
log_error("error: cannot create symlink from %s to %s: %s\n",
symlink_dest_path, recording_filepath, strerror(errno));
}
// unlink tmp file
log_debug("unlink");
unlink(recording_tmp_filepath);
state_set(state_dir, "last_rec", recording_filepath);
free(copy_buf);
}
is_recording = 0;
state_set(state_dir, "record", "false");
pthread_exit(0);
}
void flush_record() {
rec_thread_needs_flush = 1;
}
void stop_record() {
rec_thread_needs_exit = 1;
}
void check_record_duration() {
time_t now;
if (is_recording) {
now = time(NULL);
if (now - rec_start_time > flush_recording_seconds) {
flush_record();
}
}
}
void *rec_thread_start() {
time_t rawtime;
struct tm *timeinfo;
AVPacket av_pkt;
int wrote_packets;
int is_caught_up = 0;
int unique_number = 1;
int64_t rec_start_pts, rec_end_pts;
char state_buf[256];
EncodedPacket *enc_pkt;
int filename_decided = 0;
uint8_t *copy_buf;
FILE *fsrc, *fdest;
int read_len;
char *dest_dir;
int has_error;
has_error = 0;
copy_buf = malloc(BUFSIZ);
if (copy_buf == NULL) {
perror("malloc for copy_buf");
pthread_exit(0);
}
time(&rawtime);
timeinfo = localtime(&rawtime);
rec_start_time = time(NULL);
rec_start_pts = -1;
if (recording_dest_dir[0] != 0) {
dest_dir = recording_dest_dir;
} else {
dest_dir = rec_archive_dir;
}
if (recording_basename[0] != 0) { // basename is already decided
snprintf(recording_filepath, sizeof(recording_filepath),
"%s/%s", rec_dir, recording_basename);
snprintf(recording_archive_filepath, sizeof(recording_archive_filepath),
"%s/%s", dest_dir, recording_basename);
snprintf(recording_tmp_filepath, sizeof(recording_tmp_filepath),
"%s/%s", rec_tmp_dir, recording_basename);
filename_decided = 1;
} else {
strftime(recording_basename, sizeof(recording_basename), "%Y-%m-%d_%H-%M-%S", timeinfo);
snprintf(recording_filepath, sizeof(recording_filepath),
"%s/%s.ts", rec_dir, recording_basename);
if (access(recording_filepath, F_OK) != 0) { // filename is decided
sprintf(recording_basename + strlen(recording_basename), ".ts"); // add ".ts"
snprintf(recording_archive_filepath, sizeof(recording_archive_filepath),
"%s/%s", dest_dir, recording_basename);
snprintf(recording_tmp_filepath, sizeof(recording_tmp_filepath),
"%s/%s", rec_tmp_dir, recording_basename);
filename_decided = 1;
}
while (!filename_decided) {
unique_number++;
snprintf(recording_filepath, sizeof(recording_filepath),
"%s/%s-%d.ts", rec_dir, recording_basename, unique_number);
if (access(recording_filepath, F_OK) != 0) { // filename is decided
sprintf(recording_basename + strlen(recording_basename), "-%d.ts", unique_number);
snprintf(recording_archive_filepath, sizeof(recording_archive_filepath),
"%s/%s", dest_dir, recording_basename);
snprintf(recording_tmp_filepath, sizeof(recording_tmp_filepath),
"%s/%s", rec_tmp_dir, recording_basename);
filename_decided = 1;
}
}
}
// Remove existing file
if (unlink(recording_archive_filepath) == 0) {
log_info("removed existing file: %s\n", recording_archive_filepath);
}
pthread_mutex_lock(&rec_write_mutex);
rec_format_ctx = mpegts_create_context(&codec_settings);
mpegts_open_stream(rec_format_ctx, recording_tmp_filepath, 0);
is_recording = 1;
log_info("start rec to %s\n", recording_archive_filepath);
state_set(state_dir, "record", "true");
pthread_mutex_unlock(&rec_write_mutex);
int look_back_keyframes;
if (recording_look_back_keyframes != -1) {
look_back_keyframes = recording_look_back_keyframes;
} else {
look_back_keyframes = record_buffer_keyframes;
}
int start_keyframe_pointer;
if (!is_keyframe_pointers_filled) { // first cycle has not been finished
if (look_back_keyframes - 1 > current_keyframe_pointer) { // not enough pre-start buffer