-
Notifications
You must be signed in to change notification settings - Fork 0
/
wimsconstructioncam.cpp
1750 lines (1728 loc) · 77.7 KB
/
wimsconstructioncam.cpp
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
/////////////////////////////////////////////////////////////////////////////
// MIT License
//
// Copyright(c) 2022 William C Bonner
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this softwareand associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and /or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright noticeand this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <arpa/inet.h>
#include <cfloat>
#include <chrono>
#include <climits>
#define _USE_MATH_DEFINES
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <gd.h> // apt install libgd-dev
#include <getopt.h>
#include <iomanip>
#include <iostream>
#include <libexif/exif-data.h> // apt install libexif-dev
#include <locale>
#include <map>
#include <netdb.h>
#include <netinet/in.h>
#include <queue>
#include <sstream>
#include <sysexits.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h> // wait()
#include <time.h> // clock_settime()
#include <unistd.h> // For close()
#include <vector>
#ifdef _USE_GPSD
#include <gps.h> // apt install libgps-dev
#include <libgpsmm.h> // apt install libgps-dev
#endif
// GPSD Client HOWTO https://gpsd.io/client-howto.html#_c_examples
// https://www.ubuntupit.com/best-gps-tools-for-linux/
// https://www.linuxlinks.com/GPSTools/
/////////////////////////////////////////////////////////////////////////////
#if __has_include("wimsconstructioncam-version.h")
#include "wimsconstructioncam-version.h"
#endif
#ifndef WimsConstructionCam_VERSION
#define WimsConstructionCam_VERSION "(non-CMake)"
#endif // !GoveeBTTempLogger_VERSION
/////////////////////////////////////////////////////////////////////////////
static const std::string ProgramVersionString("WimsConstructionCam Version " WimsConstructionCam_VERSION " Built on: " __DATE__ " at " __TIME__);
/////////////////////////////////////////////////////////////////////////////
int ConsoleVerbosity(1);
int TimeoutMinutes(0);
bool UseGPSD(false);
bool VideoHD(false);
bool Video4k(false);
bool RotateStills180Degrees(false);
bool HDR_Processing(false);
bool b24Hour(false);
bool bRunOnce(false);
bool bRunWithNoCamera(false); // This is to run as a service, processing images from another machine
int MaxDailyMovies(2);
double Latitude(0);
double Longitude(0);
int GigabytesFreeSpace(3);
/////////////////////////////////////////////////////////////////////////////
std::string timeToISO8601(const time_t& TheTime, const bool LocalTime = false)
{
std::ostringstream ISOTime;
struct tm UTC;
struct tm* timecallresult(nullptr);
if (LocalTime)
timecallresult = localtime_r(&TheTime, &UTC);
else
timecallresult = gmtime_r(&TheTime, &UTC);
if (nullptr != timecallresult)
{
ISOTime.fill('0');
if (!((UTC.tm_year == 70) && (UTC.tm_mon == 0) && (UTC.tm_mday == 1)))
{
ISOTime << UTC.tm_year + 1900 << "-";
ISOTime.width(2);
ISOTime << UTC.tm_mon + 1 << "-";
ISOTime.width(2);
ISOTime << UTC.tm_mday << "T";
}
ISOTime.width(2);
ISOTime << UTC.tm_hour << ":";
ISOTime.width(2);
ISOTime << UTC.tm_min << ":";
ISOTime.width(2);
ISOTime << UTC.tm_sec;
}
return(ISOTime.str());
}
std::string getTimeISO8601(const bool LocalTime = false)
{
time_t timer;
time(&timer);
std::string isostring(timeToISO8601(timer, LocalTime));
std::string rval;
rval.assign(isostring.begin(), isostring.end());
return(rval);
}
time_t ISO8601totime(const std::string& ISOTime)
{
time_t timer(0);
if (ISOTime.length() >= 19)
{
struct tm UTC;
UTC.tm_year = stoi(ISOTime.substr(0, 4)) - 1900;
UTC.tm_mon = stoi(ISOTime.substr(5, 2)) - 1;
UTC.tm_mday = stoi(ISOTime.substr(8, 2));
UTC.tm_hour = stoi(ISOTime.substr(11, 2));
UTC.tm_min = stoi(ISOTime.substr(14, 2));
UTC.tm_sec = stoi(ISOTime.substr(17, 2));
UTC.tm_gmtoff = 0;
UTC.tm_isdst = -1;
UTC.tm_zone = 0;
#ifdef _MSC_VER
_tzset();
_get_daylight(&(UTC.tm_isdst));
#endif
#ifdef __USE_MISC
timer = timegm(&UTC);
if (timer == -1)
return(0); // if timegm() returned an error value, leave time set at epoch
#else
timer = mktime(&UTC);
if (timer == -1)
return(0); // if mktime() returned an error value, leave time set at epoch
timer -= timezone; // HACK: Works in my initial testing on the raspberry pi, but it's currently not DST
#endif
#ifdef _MSC_VER
long Timezone_seconds = 0;
_get_timezone(&Timezone_seconds);
timer -= Timezone_seconds;
int DST_hours = 0;
_get_daylight(&DST_hours);
long DST_seconds = 0;
_get_dstbias(&DST_seconds);
timer += DST_hours * DST_seconds;
#endif
}
return(timer);
}
// Microsoft Excel doesn't recognize ISO8601 format dates with the "T" seperating the date and time
// This function puts a space where the T goes for ISO8601. The dates can be decoded with ISO8601totime()
std::string timeToExcelDate(const time_t& TheTime, const bool LocalTime = false) { std::string ExcelDate(timeToISO8601(TheTime, LocalTime)); ExcelDate.replace(10, 1, " "); return(ExcelDate); }
std::string timeToExcelLocal(const time_t& TheTime) { return(timeToExcelDate(TheTime, true)); }
std::string getTimeExcelLocal(void)
{
time_t timer;
time(&timer);
std::string isostring(timeToExcelLocal(timer));
std::string rval;
rval.assign(isostring.begin(), isostring.end());
return(rval);
}
/////////////////////////////////////////////////////////////////////////////
inline double radians(const double& degrees) { return((degrees * M_PI) / 180.0); }
inline double degrees(const double& radians) { return((radians * 180.0) / M_PI); }
double Time2JulianDate(const time_t& TheTime)
{
double JulianDay = 0;
struct tm UTC;
if (0 != gmtime_r(&TheTime, &UTC))
{
// https://en.wikipedia.org/wiki/Julian_day
// JDN = (1461 × (Y + 4800 + (M ? 14)/12))/4 +(367 × (M ? 2 ? 12 × ((M ? 14)/12)))/12 ? (3 × ((Y + 4900 + (M - 14)/12)/100))/4 + D ? 32075
JulianDay = (1461 * ((UTC.tm_year + 1900) + 4800 + ((UTC.tm_mon + 1) - 14) / 12)) / 4
+ (367 * ((UTC.tm_mon + 1) - 2 - 12 * (((UTC.tm_mon + 1) - 14) / 12))) / 12
- (3 * (((UTC.tm_year + 1900) + 4900 + ((UTC.tm_mon + 1) - 14) / 12) / 100)) / 4
+ (UTC.tm_mday)
- 32075;
// JD = JDN + (hour-12)/24 + minute/1440 + second/86400
double partialday = (static_cast<double>((UTC.tm_hour - 12)) / 24) + (static_cast<double>(UTC.tm_min) / 1440.0) + (static_cast<double>(UTC.tm_sec) / 86400.0);
JulianDay += partialday;
}
return(JulianDay);
}
time_t JulianDate2Time(const double JulianDate)
{
time_t TheTime = (JulianDate - 2440587.5) * 86400.0;
return(TheTime);
}
double JulianDate2JulianDay(const double JulianDate)
{
double n = JulianDate - 2451545.0 + 0.0008;
return(n);
}
/////////////////////////////////////////////////////////////////////////////
// These equations all come from https://en.wikipedia.org/wiki/Sunrise_equation
double getMeanSolarTime(const double JulianDay, const double longitude)
{
// an approximation of mean solar time expressed as a Julian day with the day fraction.
double MeanSolarTime = JulianDay - (longitude / 360);
return (MeanSolarTime);
}
double getSolarMeanAnomaly(const double MeanSolarTime)
{
double SolarMeanAnomaly = fmod(357.5291 + 0.98560028 * MeanSolarTime, 360);
return(SolarMeanAnomaly);
}
double getEquationOfTheCenter(const double SolarMeanAnomaly)
{
double EquationOfTheCenter = 1.9148 * sin(radians(SolarMeanAnomaly)) + 0.0200 * sin(radians(2 * SolarMeanAnomaly)) + 0.0003 * sin(radians(3 * SolarMeanAnomaly));
return(EquationOfTheCenter);
}
double getEclipticLongitude(const double SolarMeanAnomaly, const double EquationOfTheCenter)
{
double EclipticLongitude = fmod(SolarMeanAnomaly + EquationOfTheCenter + 180 + 102.9372, 360);
return(EclipticLongitude);
}
double getSolarTransit(const double MeanSolarTime, const double SolarMeanAnomaly, const double EclipticLongitude)
{
// the Julian date for the local true solar transit (or solar noon).
double SolarTransit = 2451545.0 + MeanSolarTime + 0.0053 * sin(radians(SolarMeanAnomaly)) - 0.0069 * sin(radians(2 * EclipticLongitude));
return(SolarTransit);
}
double getDeclinationOfTheSun(const double EclipticLongitude)
{
double DeclinationOfTheSun = sin(radians(EclipticLongitude)) * sin(radians(23.44));
return(DeclinationOfTheSun);
}
double getHourAngle(const double Latitude, const double DeclinationOfTheSun)
{
double HourAngle = (sin(radians(-0.83)) - sin(radians(Latitude)) * sin(radians(DeclinationOfTheSun))) / (cos(radians(Latitude)) * cos(radians(DeclinationOfTheSun)));
return(HourAngle);
}
double getSunrise(const double SolarTransit, const double HourAngle)
{
double Sunrise = SolarTransit - (HourAngle / 360);
return(Sunrise);
}
double getSunset(const double SolarTransit, const double HourAngle)
{
double Sunset = SolarTransit + (HourAngle / 360);
return(Sunset);
}
/////////////////////////////////////////////////////////////////////////////
// From NOAA Spreadsheet https://gml.noaa.gov/grad/solcalc/calcdetails.html
bool getSunriseSunset(time_t& Sunrise, time_t& Sunset, const time_t& TheTime, const double Latitude, double Longitude)
{
bool rval = false;
struct tm LocalTime;
if (0 != localtime_r(&TheTime, &LocalTime))
{
// if we don't have a valid latitude or longitude, declare sunrise to be midnight, and sunset one second before midnight
if ((Latitude == 0) || (Longitude == 0))
{
LocalTime.tm_hour = 0;
LocalTime.tm_min = 0;
LocalTime.tm_sec = 0;
Sunrise = mktime(&LocalTime);
Sunset = Sunrise + 24*60*60 - 1;
}
else
{
double JulianDay = Time2JulianDate(TheTime); // F
double JulianCentury = (JulianDay - 2451545) / 36525; // G
double GeomMeanLongSun = fmod(280.46646 + JulianCentury * (36000.76983 + JulianCentury * 0.0003032), 360); // I
double GeomMeanAnomSun = 357.52911 + JulianCentury * (35999.05029 - 0.0001537 * JulianCentury); // J
double EccentEarthOrbit = 0.016708634 - JulianCentury * (0.000042037 + 0.0000001267 * JulianCentury); // K
double SunEqOfCtr = sin(radians(GeomMeanAnomSun)) * (1.914602 - JulianCentury * (0.004817 + 0.000014 * JulianCentury)) + sin(radians(2 * GeomMeanAnomSun)) * (0.019993 - 0.000101 * JulianCentury) + sin(radians(3 * GeomMeanAnomSun)) * 0.000289; // L
double SunTrueLong = GeomMeanLongSun + SunEqOfCtr; // M
double SunAppLong = SunTrueLong - 0.00569 - 0.00478 * sin(radians(125.04 - 1934.136 * JulianCentury)); // P
double MeanObliqEcliptic = 23 + (26 + ((21.448 - JulianCentury * (46.815 + JulianCentury * (0.00059 - JulianCentury * 0.001813)))) / 60) / 60; // Q
double ObliqCorr = MeanObliqEcliptic + 0.00256 * cos(radians(125.04 - 1934.136 * JulianCentury)); // R
double SunDeclin = degrees(asin(sin(radians(ObliqCorr)) * sin(radians(SunAppLong)))); // T
double var_y = tan(radians(ObliqCorr / 2)) * tan(radians(ObliqCorr / 2)); // U
double EquationOfTime = 4 * degrees(var_y * sin(2 * radians(GeomMeanLongSun)) - 2 * EccentEarthOrbit * sin(radians(GeomMeanAnomSun)) + 4 * EccentEarthOrbit * var_y * sin(radians(GeomMeanAnomSun)) * sin(2 * radians(GeomMeanLongSun)) - 0.5 * var_y * var_y * sin(4 * radians(GeomMeanLongSun)) - 1.25 * EccentEarthOrbit * EccentEarthOrbit * sin(2 * radians(GeomMeanAnomSun))); // V
double HASunriseDeg = degrees(acos(cos(radians(90.833)) / (cos(radians(Latitude)) * cos(radians(SunDeclin))) - tan(radians(Latitude)) * tan(radians(SunDeclin)))); // W
double SolarNoon = (720 - 4 * Longitude - EquationOfTime + LocalTime.tm_gmtoff / 60) / 1440; // X
double SunriseTime = SolarNoon - HASunriseDeg * 4 / 1440; // Y
double SunsetTime = SolarNoon + HASunriseDeg * 4 / 1440; // Z
LocalTime.tm_hour = 0;
LocalTime.tm_min = 0;
LocalTime.tm_sec = 0;
time_t Midnight = mktime(&LocalTime);
Sunrise = Midnight + SunriseTime * 86400;
Sunset = Midnight + SunsetTime * 86400;
}
rval = true;
}
return(rval);
}
/////////////////////////////////////////////////////////////////////////////
bool getLatLon(double& Latitude, double& Longitude)
{
bool rval = false;
#ifdef _USE_GPSD
gpsmm gps_rec("localhost", DEFAULT_GPSD_PORT);
if (gps_rec.stream(WATCH_ENABLE | WATCH_JSON) == NULL)
{
if (ConsoleVerbosity > 0)
std::cout << "[" << getTimeExcelLocal() << "] " << "No GPSD running." << std::endl;
else
std::cerr << "No GPSD running." << std::endl;
}
else
{
#if GPSD_API_MAJOR_VERSION < 9
timestamp_t last_timestamp = 0;
#else
timespec_t last_timestamp;
timespec_get(&last_timestamp, TIME_UTC);
#endif
int doloop = 0;
while (doloop < 5)
{
struct gps_data_t* newdata;
if (!gps_rec.waiting(1000000)) // wait 1 second, time is in microseconds
{
doloop++;
continue;
}
if ((newdata = gps_rec.read()) == NULL)
{
std::cerr << "GPSD read error." << std::endl;
doloop += 10;
}
else
{
if (newdata->set & MODE_SET)
if ((newdata->fix.mode > 2) && (newdata->set & LATLON_SET) && (newdata->set & TIME_SET))
{
if ((newdata->fix.latitude != 0) && (newdata->fix.longitude != 0)) // simple test that niether of these are zero
{
Latitude = newdata->fix.latitude;
Longitude = newdata->fix.longitude;
rval = true;
if (ConsoleVerbosity > 0)
std::cout << "[" << getTimeExcelLocal() << "] Latitude: " << std::setprecision(std::numeric_limits<double>::max_digits10) << newdata->fix.latitude << " Longitude: " << std::setprecision(std::numeric_limits<double>::max_digits10) << newdata->fix.longitude << std::endl;
else
std::cerr << "Latitude: " << std::setprecision(std::numeric_limits<double>::max_digits10) << newdata->fix.latitude << " Longitude: " << std::setprecision(std::numeric_limits<double>::max_digits10) << newdata->fix.longitude << std::endl;
doloop += 10;
}
timespec GPSTime = newdata->fix.time;
timespec SystemTime;
timespec_get(&SystemTime, TIME_UTC);
if (ConsoleVerbosity > 0)
std::cout << "[" << getTimeExcelLocal() << "] SystemTime: " << timeToISO8601(mkgmtime(gmtime(&SystemTime.tv_sec))) << " GPSTime: " << timeToISO8601(mkgmtime(gmtime(&GPSTime.tv_sec))) << " Seconds Difference: " << fabs(difftime(GPSTime.tv_sec, SystemTime.tv_sec)) << std::endl;
else
std::cerr << "SystemTime: " << timeToISO8601(mkgmtime(gmtime(&SystemTime.tv_sec))) << " GPSTime: " << timeToISO8601(mkgmtime(gmtime(&GPSTime.tv_sec))) << " Seconds Difference: " << fabs(difftime(GPSTime.tv_sec, SystemTime.tv_sec)) << std::endl;
if (fabs(difftime(GPSTime.tv_sec, SystemTime.tv_sec)) > 60 * 60) // if GPSTime is an hour or more ahead of SystemTime, we want to set the SystemTime.
clock_settime(CLOCK_REALTIME, &GPSTime);
doloop++;
}
}
}
}
#endif
return(rval);
}
/////////////////////////////////////////////////////////////////////////////
bool ValidateDirectory(const std::filesystem::path& DirectoryName)
{
bool rval = false;
// https://linux.die.net/man/2/stat
struct stat StatBuffer;
if (0 == stat(DirectoryName.c_str(), &StatBuffer))
if (S_ISDIR(StatBuffer.st_mode))
{
// https://linux.die.net/man/2/access
if (0 == access(DirectoryName.c_str(), R_OK | W_OK))
rval = true;
else
{
switch (errno)
{
case EACCES:
std::cerr << DirectoryName << " (" << errno << ") The requested access would be denied to the file, or search permission is denied for one of the directories in the path prefix of pathname." << std::endl;
break;
case ELOOP:
std::cerr << DirectoryName << " (" << errno << ") Too many symbolic links were encountered in resolving pathname." << std::endl;
break;
case ENAMETOOLONG:
std::cerr << DirectoryName << " (" << errno << ") pathname is too long." << std::endl;
break;
case ENOENT:
std::cerr << DirectoryName << " (" << errno << ") A component of pathname does not exist or is a dangling symbolic link." << std::endl;
break;
case ENOTDIR:
std::cerr << DirectoryName << " (" << errno << ") A component used as a directory in pathname is not, in fact, a directory." << std::endl;
break;
case EROFS:
std::cerr << DirectoryName << " (" << errno << ") Write permission was requested for a file on a read-only file system." << std::endl;
break;
case EFAULT:
std::cerr << DirectoryName << " (" << errno << ") pathname points outside your accessible address space." << std::endl;
break;
case EINVAL:
std::cerr << DirectoryName << " (" << errno << ") mode was incorrectly specified." << std::endl;
break;
case EIO:
std::cerr << DirectoryName << " (" << errno << ") An I/O error occurred." << std::endl;
break;
case ENOMEM:
std::cerr << DirectoryName << " (" << errno << ") Insufficient kernel memory was available." << std::endl;
break;
case ETXTBSY:
std::cerr << DirectoryName << " (" << errno << ") Write access was requested to an executable which is being executed." << std::endl;
break;
default:
std::cerr << DirectoryName << " (" << errno << ") An unknown error." << std::endl;
}
}
}
return(rval);
}
bool ValidateFile(const std::filesystem::path& FileName)
{
//auto FileStatus(std::filesystem::status(FileName));
//bool rval = FileStatus.permissions();
bool rval = false;
// https://linux.die.net/man/2/stat
struct stat StatBuffer;
if (0 == stat(FileName.c_str(), &StatBuffer))
if (S_ISREG(StatBuffer.st_mode))
{
// https://linux.die.net/man/2/access
if (0 == access(FileName.c_str(), R_OK))
rval = true;
else
{
switch (errno)
{
case EACCES:
std::cerr << FileName << " (" << errno << ") The requested access would be denied to the file, or search permission is denied for one of the directories in the path prefix of pathname." << std::endl;
break;
case ELOOP:
std::cerr << FileName << " (" << errno << ") Too many symbolic links were encountered in resolving pathname." << std::endl;
break;
case ENAMETOOLONG:
std::cerr << FileName << " (" << errno << ") pathname is too long." << std::endl;
break;
case ENOENT:
std::cerr << FileName << " (" << errno << ") A component of pathname does not exist or is a dangling symbolic link." << std::endl;
break;
case ENOTDIR:
std::cerr << FileName << " (" << errno << ") A component used as a directory in pathname is not, in fact, a directory." << std::endl;
break;
case EROFS:
std::cerr << FileName << " (" << errno << ") Write permission was requested for a file on a read-only file system." << std::endl;
break;
case EFAULT:
std::cerr << FileName << " (" << errno << ") pathname points outside your accessible address space." << std::endl;
break;
case EINVAL:
std::cerr << FileName << " (" << errno << ") mode was incorrectly specified." << std::endl;
break;
case EIO:
std::cerr << FileName << " (" << errno << ") An I/O error occurred." << std::endl;
break;
case ENOMEM:
std::cerr << FileName << " (" << errno << ") Insufficient kernel memory was available." << std::endl;
break;
case ETXTBSY:
std::cerr << FileName << " (" << errno << ") Write access was requested to an executable which is being executed." << std::endl;
break;
default:
std::cerr << FileName << " (" << errno << ") An unknown error." << std::endl;
}
}
}
return(rval);
}
/////////////////////////////////////////////////////////////////////////////
std::filesystem::path GetImageDirectory(const std::filesystem::path DestinationDir, const time_t& TheTime)
{
std::filesystem::path OutputDirectoryPath(DestinationDir);
std::ostringstream OutputDirectoryName;
struct tm UTC;
if (0 != localtime_r(&TheTime, &UTC))
{
OutputDirectoryName.fill('0');
OutputDirectoryName << UTC.tm_year + 1900;
OutputDirectoryName.width(2);
OutputDirectoryName << UTC.tm_mon + 1;
OutputDirectoryName.width(2);
OutputDirectoryName << UTC.tm_mday;
OutputDirectoryPath /= OutputDirectoryName.str();
}
if (!std::filesystem::exists(OutputDirectoryPath))
{
if (std::filesystem::create_directory(OutputDirectoryPath))
{
std::filesystem::permissions(OutputDirectoryPath,
std::filesystem::perms::owner_all | std::filesystem::perms::group_all | std::filesystem::perms::others_read | std::filesystem::perms::others_exec,
std::filesystem::perm_options::add);
if (ConsoleVerbosity > 0)
std::cout << "[" << getTimeExcelLocal() << "] Directory Created: " << OutputDirectoryPath << std::endl;
else
std::cerr << "Directory Created : " << OutputDirectoryPath << std::endl;
}
}
return(OutputDirectoryPath);
}
int GetLastImageNum(const std::filesystem::path DestinationDir)
{
int LastImageNum = 0;
if (std::filesystem::exists(DestinationDir))
{
std::deque<std::filesystem::path> files;
for (auto const& dir_entry : std::filesystem::directory_iterator{ DestinationDir })
if (dir_entry.is_regular_file())
if ((dir_entry.path().extension() == ".jpg") && (dir_entry.file_size() > 0))
files.push_back(dir_entry);
if (!files.empty())
{
sort(files.begin(), files.end());
LastImageNum = atoi(files.back().stem().string().substr(4, 4).c_str());
}
}
return(LastImageNum);
}
/////////////////////////////////////////////////////////////////////////////
bool GenerateFreeSpace(const int MinFreeSpaceGB, const std::filesystem::path DestinationDir)
{
bool bDirectoryEmpty = false;
unsigned long long MinFreeSpace = (unsigned long long)(MinFreeSpaceGB) << 30ll;
struct statvfs64 buffer2;
if (0 == statvfs64(DestinationDir.c_str(), &buffer2))
{
if (ConsoleVerbosity > 0)
{
std::cout << "[" << getTimeExcelLocal() << "] " << DestinationDir.string() << " optimal transfer block size: " << buffer2.f_bsize << std::endl;
std::cout << "[" << getTimeExcelLocal() << "] " << DestinationDir.string() << " total data blocks in file system: " << buffer2.f_blocks << std::endl;
std::cout << "[" << getTimeExcelLocal() << "] " << DestinationDir.string() << " free blocks in fs: " << buffer2.f_bfree << std::endl;
std::cout << "[" << getTimeExcelLocal() << "] " << DestinationDir.string() << " free blocks avail to non-superuser: " << buffer2.f_bavail << std::endl;
std::cout << "[" << getTimeExcelLocal() << "] " << DestinationDir.string() << " Drive Size: " << buffer2.f_bsize * buffer2.f_blocks << " Free Space: " << buffer2.f_bsize * buffer2.f_bavail << std::endl;
}
std::deque<std::filesystem::path> files;
std::deque<std::filesystem::path> directories;
for (auto const& dir_entry : std::filesystem::directory_iterator{ DestinationDir })
if (dir_entry.is_regular_file())
files.push_back(dir_entry);
else if (dir_entry.is_directory())
{
if ((dir_entry.path().stem() == "..") || (dir_entry.path().stem() == "."))
continue;
else
directories.push_back(dir_entry);
}
// delete directories first, theoretically deleting the images before deleting the movies.
sort(directories.begin(), directories.end());
while ((!directories.empty()) && (buffer2.f_bsize * buffer2.f_bavail < MinFreeSpace))
{
auto count_removed = std::filesystem::remove_all(*directories.begin());
if (0 != statvfs64(DestinationDir.c_str(), &buffer2))
break;
if (ConsoleVerbosity > 0)
std::cout << "[" << getTimeExcelLocal() << "] Directory Deleted: " << *directories.begin() << " (files deleted:: " << count_removed << ") Free Space: " << buffer2.f_bsize * buffer2.f_bavail << " < " << MinFreeSpace << std::endl;
else
std::cerr << " Directory Deleted: " << *directories.begin() << " (files deleted:: " << count_removed << ") Free Space: " << buffer2.f_bsize * buffer2.f_bavail << " < " << MinFreeSpace << std::endl;
directories.pop_front();
}
sort(files.begin(), files.end());
while ((!files.empty()) && (buffer2.f_bsize * buffer2.f_bavail < MinFreeSpace)) // This loop will make sure that there's free space on the drive.
{
struct stat buffer;
if (0 == stat(files.begin()->c_str(), &buffer))
if (std::filesystem::remove(*files.begin()))
{
if (ConsoleVerbosity > 0)
std::cout << "[" << getTimeExcelLocal() << "] File Deleted: " << *files.begin() << "(" << buffer.st_size << ") Free Space: " << buffer2.f_bsize * buffer2.f_bavail << " < " << MinFreeSpace << std::endl;
else
std::cerr << " File Deleted: " << *files.begin() << "(" << buffer.st_size << ") Free Space: " << buffer2.f_bsize * buffer2.f_bavail << " < " << MinFreeSpace << std::endl;
}
files.pop_front();
bDirectoryEmpty = files.empty(); // if the last file from the current directory was deleted, we can signal to the calling function that it can delete the directpry
if (0 != statvfs64(DestinationDir.c_str(), &buffer2))
break;
}
}
return(bDirectoryEmpty);
}
/////////////////////////////////////////////////////////////////////////////
std::string GetHostnameFromMediaDirectory(const std::filesystem::path& MediaDirectory)
{
std::string HostName(MediaDirectory);
if (HostName.find("/DCIM") == std::string::npos)
HostName.clear();
else
{
HostName.erase(HostName.find("/DCIM"));
if (HostName.rfind("/") != std::string::npos)
HostName.erase(0, 1+HostName.rfind("/"));
}
return(HostName);
}
std::string GetHostname(void)
{
std::string HostName;
char MyHostName[HOST_NAME_MAX] = { 0 }; // hostname used for data recordkeeping
if (gethostname(MyHostName, sizeof(MyHostName)) == 0)
HostName = MyHostName;
return(HostName);
}
/////////////////////////////////////////////////////////////////////////////
void CreateClockFile(const std::filesystem::path& FileName, const time_t ClockTime, const int Width = 512)
{
const int Radius = Width / 2;
/* Declare the image */
auto im = gdImageCreate(Width + 1, Width + 1);
//im = gdImageCreateTrueColor(Radius * 2 + 1, Radius * 2 + 1);
gdImageSaveAlpha(im, GD_TRUE);
/* Declare color indexes */
/* Allocate the color black (red, green and blue all minimum). Since this is the first color in a new image, it will be the background color. */
auto black = gdImageColorAllocateAlpha(im, 0, 0, 0, gdAlphaTransparent);
gdImageColorTransparent(im, black);
// 2.0.2: first color allocated would automatically be background in a
// palette based image. Since this is a truecolor image, with an
// automatic background of black, we must fill it explicitly.
// gdImageFilledRectangle(im, 0, 0, gdImageSX(im), gdImageSY(im), black);
/* Allocate the color white (red, green and blue all maximum). */
auto white = gdImageColorAllocateAlpha(im, gdRedMax, gdGreenMax, gdBlueMax, (gdAlphaOpaque + gdAlphaTransparent) / 2);
gdImageSetAntiAliased(im, white);
gdImageSetThickness(im, 2);
auto CenterX = Radius;
auto CenterY = Radius;
auto TickLength = Radius / 16;
auto MinuteHandLength = Radius - TickLength * 2;
auto HourHandLength = MinuteHandLength * 2 / 3;
for (auto minutes = 0; minutes < 60; minutes++) // create shorter tick marks on the minutes
{
auto TickXo = CenterX + Radius * sin(radians(minutes * 6.0)); // outer end of tick mark
auto TickYo = CenterY - Radius * cos(radians(minutes * 6.0)); // outer end of tick mark
auto TickXi = CenterX + (Radius - TickLength) * sin(radians(minutes * 6.0)); // inner end of tick mark
auto TickYi = CenterY - (Radius - TickLength) * cos(radians(minutes * 6.0)); // inner end of tick mark
gdImageLine(im, TickXi, TickYi, TickXo, TickYo, white);
}
for (auto hour = 0; hour < 12; hour++) // create longer tick marks one the hour markers
{
auto TickXo = CenterX + Radius * sin(radians(hour * 30.0)); // outer end of tick mark
auto TickYo = CenterY - Radius * cos(radians(hour * 30.0)); // outer end of tick mark
auto TickXi = CenterX + (Radius - TickLength * 2) * sin(radians(hour * 30.0)); // inner end of tick mark
auto TickYi = CenterY - (Radius - TickLength * 2) * cos(radians(hour * 30.0)); // inner end of tick mark
gdImageLine(im, TickXi, TickYi, TickXo, TickYo, white);
}
struct tm UTC;
if (nullptr != gmtime_r(&ClockTime, &UTC))
{
double HourDegrees(UTC.tm_hour * 30 + UTC.tm_min / 2);
double MinuteDegrees(UTC.tm_min * 6);
auto MinuteXo = CenterX + MinuteHandLength * sin(radians(MinuteDegrees));
auto MinuteYo = CenterY - MinuteHandLength * cos(radians(MinuteDegrees));
gdImageLine(im, CenterX, CenterY, MinuteXo, MinuteYo, white);
auto HourXo = CenterX + HourHandLength * sin(radians(HourDegrees));
auto HourYo = CenterY - HourHandLength * cos(radians(HourDegrees));
gdImageLine(im, CenterX, CenterY, HourXo, HourYo, white);
}
/* Output the image to the disk file in PNG format. */
int PNG_Memory_Blob_Size(0);
auto PNG_Memory_Blob = gdImagePngPtr(im, &PNG_Memory_Blob_Size);
if (PNG_Memory_Blob != nullptr)
{
std::ofstream OutFile(FileName);
if (OutFile.is_open())
OutFile.write((const char*)PNG_Memory_Blob, PNG_Memory_Blob_Size);
gdFree(PNG_Memory_Blob);
}
/* Destroy the image in memory. */
gdImageDestroy(im);
}
/** Callback function handling an ExifEntry. */
void content_foreach_EXIF(ExifEntry* entry, void* callback_data)
{
if (entry->tag == EXIF_TAG_DATE_TIME_ORIGINAL)
{
char valuebuffer[32];
exif_entry_get_value(entry, valuebuffer, sizeof(valuebuffer));
time_t TheTime(ISO8601totime(std::string(valuebuffer)));
time_t* ptrTime = (time_t*)callback_data;
*ptrTime = TheTime;
}
}
/** Callback function handling an ExifContent (corresponds 1:1 to an IFD). */
void data_foreach_IFD(ExifContent* content, void* callback_data) { exif_content_foreach_entry(content, content_foreach_EXIF, callback_data); }
time_t getTimeFromExif(const std::filesystem::path FileName)
{
time_t TheTime(0);
ExifData* d = exif_data_new_from_file(FileName.c_str());
if (nullptr != d)
{
void* callback_data = (void*)&TheTime;
exif_data_foreach_content(d, data_foreach_IFD, callback_data);
exif_data_unref(d);
}
return(TheTime);
}
/////////////////////////////////////////////////////////////////////////////
volatile pid_t CameraProgram_PID = 0;
void SignalHandlerSIGALRM(int signal)
{
std::cerr << "***************** SIGALRM: Caught Alarm, sending child SIGINT. ************************" << std::endl;
kill(CameraProgram_PID, SIGINT);
}
bool CreateDailyStills(const std::string DestinationDir, const time_t& CurrentTime, const time_t& StopTime, const bool bRotate, const std::string & TuningFileName)
{
bool rval = false;
std::ostringstream OutputFormat; // raspistill outputname format string
std::ostringstream FrameStart; // first filename for raspistill to use in current loop
std::ostringstream Timeout; // how many milliseconds raspistill will run
// Minutes in Day = 60 * 24 = 1440
int MinutesLeftInDay = 1440;
struct tm UTC;
if (0 != localtime_r(&CurrentTime, &UTC))
{
int CurrentMinuteInDay = UTC.tm_hour * 60 + UTC.tm_min;
struct tm StopTimeTM;
if (0 != localtime_r(&StopTime, &StopTimeTM))
{
if (UTC.tm_mday == StopTimeTM.tm_mday)
MinutesLeftInDay = (StopTimeTM.tm_hour * 60 + StopTimeTM.tm_min) - CurrentMinuteInDay;
else
MinutesLeftInDay = 1440 - CurrentMinuteInDay; //1440 is the maximum number of minutes in a day = 24*60
}
else
MinutesLeftInDay = 1440 - CurrentMinuteInDay;
if (TimeoutMinutes == 0)
Timeout << MinutesLeftInDay * 60 * 1000;
else
Timeout << TimeoutMinutes * 60 * 1000;
OutputFormat.fill('0');
OutputFormat.width(2);
OutputFormat << UTC.tm_mon + 1;
OutputFormat.width(2);
OutputFormat << UTC.tm_mday;
OutputFormat << "\%04d.jpg";
std::filesystem::path OutPutSpec(GetImageDirectory(DestinationDir, CurrentTime) / OutputFormat.str());
FrameStart << GetLastImageNum(GetImageDirectory(DestinationDir, CurrentTime)) + 1;
if (ConsoleVerbosity > 0)
{
std::cout << "[" << getTimeExcelLocal() << "] OutputFormat: " << OutPutSpec.string() << std::endl;
std::cout << "[" << getTimeExcelLocal() << "] FrameStart: " << FrameStart.str() << std::endl;
std::cout << "[" << getTimeExcelLocal() << "] Timeout: " << Timeout.str() << std::endl;
}
std::vector<std::string> mycommand;
mycommand.push_back("raspistill");
mycommand.push_back("--nopreview");
if (bRotate)
{
mycommand.push_back("--hflip");
mycommand.push_back("--vflip");
}
mycommand.push_back("--thumb"); mycommand.push_back("none");
mycommand.push_back("--timeout"); mycommand.push_back(Timeout.str());
mycommand.push_back("--timelapse"); mycommand.push_back("60000");
mycommand.push_back("--output"); mycommand.push_back(OutPutSpec);
mycommand.push_back("--framestart"); mycommand.push_back(FrameStart.str());
if (ConsoleVerbosity > 0)
{
std::cout << "[" << getTimeExcelLocal() << "] execvp:";
for (auto iter = mycommand.begin(); iter != mycommand.end(); iter++)
std::cout << " " << *iter;
std::cout << std::endl;
}
else
{
for (auto iter = mycommand.begin(); iter != mycommand.end(); iter++)
std::cerr << " " << *iter;
std::cerr << std::endl;
}
std::vector<char*> args;
for (auto arg = mycommand.begin(); arg != mycommand.end(); arg++)
args.push_back((char*)arg->c_str());
args.push_back(NULL);
/* Attempt to fork */
pid_t pid = fork();
if (pid == 0)
{
/* A zero PID indicates that this is the child process */
/* Replace the child fork with a new process */
if (execvp(args[0], &args[0]) == -1)
exit(EXIT_FAILURE);
}
else if (pid > 0)
{
/* A positive (non-negative) PID indicates the parent process */
// I've been having problems with the camera app locking up. This alarm sequence should let me kill it if it doesn't exit in the specified number of minutes.
CameraProgram_PID = pid;
auto OldAlarmHandler = std::signal(SIGALRM, SignalHandlerSIGALRM);
alarm((MinutesLeftInDay + 1) * 60);
int CameraProgram_exit_status = 0;
wait(&CameraProgram_exit_status); // Wait for child process to end
alarm(0); // disable alarm
std::signal(SIGALRM, OldAlarmHandler); // restore alarm handler
// https://github.com/raspberrypi/userland/blob/master/host_applications/linux/apps/raspicam/RaspiStill.c
// raspistill should exit with a 0 (EX_OK) on success, or 70 (EX_SOFTWARE)
if ((EXIT_FAILURE == WEXITSTATUS(CameraProgram_exit_status)) ||
(EX_SOFTWARE == WEXITSTATUS(CameraProgram_exit_status)) ||
(255 == WEXITSTATUS(CameraProgram_exit_status))) // ERROR: the system should be configured for the legacy camera stack
{
mycommand.front() = "libcamera-still";
mycommand.push_back("--verbose"); mycommand.push_back("0");
if (!TuningFileName.empty())
{
mycommand.push_back("--tuning-file"); mycommand.push_back(TuningFileName);
}
if (HDR_Processing)
{
// The next three pair of arguments are an HDR experiment
//mycommand.push_back("--ev"); mycommand.push_back("-2");
//mycommand.push_back("--denoise"); mycommand.push_back("cdn_off");
//mycommand.push_back("--post-process-file"); mycommand.push_back("/usr/local/etc/wimsconstructioncam/hdr.json");
// with the Raspberry Pi Camera Module 3 there is a new option
mycommand.push_back("--hdr");
}
//mycommand.push_back("--autofocus-mode"); // new option with PiCamera V3 (20230124) https://www.raspberrypi.com/documentation/computers/camera_software.html
//mycommand.push_back("continuous"); // new option with PiCamera V3 (20230124)
// Add EXIF tags with the ImageDescription as programversion and Artist as machine hostname
mycommand.push_back("--exif"); mycommand.push_back("IFD0.ImageDescription=" + ProgramVersionString); // (20230329)
mycommand.push_back("--exif"); mycommand.push_back("IFD0.Artist=" + GetHostname()); // (20230329)
mycommand.push_back("--lens-position"); mycommand.push_back("0.0"); // Moves the lens to a fixed focal distance, 0.0 will move the lens to the "infinity" position (20230207)
if (ConsoleVerbosity > 0)
{
std::cout << "[" << getTimeExcelLocal() << "] execvp:";
for (auto iter = mycommand.begin(); iter != mycommand.end(); iter++)
std::cout << " " << *iter;
std::cout << std::endl;
}
else
{
for (auto iter = mycommand.begin(); iter != mycommand.end(); iter++)
std::cerr << " " << *iter;
std::cerr << std::endl;
}
args.clear();
for (auto iter = mycommand.begin(); iter != mycommand.end(); iter++)
args.push_back((char*)iter->c_str());
args.push_back(NULL);
pid = fork();
if (pid == 0)
{
/* A zero PID indicates that this is the child process */
/* Replace the child fork with a new process */
//HACK: Redirecting stderr to /dev/null so that libcamera app doesn't fill up syslog
//FILE* devnull = fopen("/dev/null","w");
//if (devnull != NULL)
//{
// dup2(fileno(devnull), STDERR_FILENO);
// fclose(devnull);
//}
if (execvp(args[0], &args[0]) == -1)
exit(EXIT_FAILURE);
}
else if (pid > 0)
{
/* A positive (non-negative) PID indicates the parent process */
// I've been having problems with the camera app locking up. This alarm sequence should let me kill it if it doesn't exit in the specified number of minutes.
CameraProgram_PID = pid;
auto OldAlarmHandler = std::signal(SIGALRM, SignalHandlerSIGALRM);
alarm((MinutesLeftInDay + 1) * 60);
wait(&CameraProgram_exit_status); // Wait for child process to end
alarm(0); // disable alarm
std::signal(SIGALRM, OldAlarmHandler); // restore alarm handler
// https://github.com/raspberrypi/libcamera-apps/blob/main/apps/libcamera_still.cpp
// libcamera-still exits with a 0 on success, or -1 if it catches an exception.
if (EXIT_SUCCESS == WEXITSTATUS(CameraProgram_exit_status) && (EXIT_SUCCESS == WTERMSIG(CameraProgram_exit_status)))
rval = true;
}
}
else if (EXIT_SUCCESS == WEXITSTATUS(CameraProgram_exit_status) && (EXIT_SUCCESS == WTERMSIG(CameraProgram_exit_status)))
rval = true;
if (ConsoleVerbosity > 0)
std::cout << "[" << getTimeExcelLocal() << "] " << mycommand.front() << " ended with exit (" << WEXITSTATUS(CameraProgram_exit_status) << ") and signal (" << WTERMSIG(CameraProgram_exit_status) << ")" << std::endl;
else if (!rval)
std::cerr << mycommand.front() << " ended with exit (" << WEXITSTATUS(CameraProgram_exit_status) << ") and signal (" << WTERMSIG(CameraProgram_exit_status) << ")" << std::endl;
}
else
{
std::cerr << " Fork error! CameraProgram." << std::endl; /* something went wrong */
}
}
return(rval);
}
bool CreateDailyClocks(const std::filesystem::path& DailyDirectory, const std::filesystem::path& ClockDirectory)
{
for (auto const& dir_entry : std::filesystem::directory_iterator{ DailyDirectory })
{
if (dir_entry.is_regular_file())
if (dir_entry.path().extension() == ".jpg")
{
time_t TheTime(getTimeFromExif(dir_entry.path()));
std::filesystem::path ClockName(ClockDirectory);
ClockName /= dir_entry.path().filename();
ClockName.replace_extension(".png");
CreateClockFile(ClockName, TheTime);
}
}
return(false);
}
bool CreateDailyMovie(const std::filesystem::path& DailyDirectory, std::string VideoTextOverlay, const bool bVideoHD, const bool bVideo4k, const bool bVideoNative = false)
{
bool rval = false;
std::deque<std::filesystem::path> JPGfiles;
for (auto const& dir_entry : std::filesystem::directory_iterator{ DailyDirectory })
if (dir_entry.is_regular_file())
if (dir_entry.path().extension() == ".jpg")
JPGfiles.push_back(dir_entry);
if (!JPGfiles.empty())
{
sort(JPGfiles.begin(), JPGfiles.end());
// What follows is a simple test that if there are newer images
// than the video files, empty the deque of video files and create
// a video file, possibly overwriting an older video.
struct stat64 FirstJPGStat, LastJPGStat;
if ((0 == stat64(JPGfiles.front().c_str(), &FirstJPGStat)) &&
(0 == stat64(JPGfiles.back().c_str(), &LastJPGStat)))
{
struct tm UTC;
if (0 != localtime_r(&FirstJPGStat.st_mtim.tv_sec, &UTC))
{
std::queue<std::filesystem::path> VideoFiles;
std::filesystem::path VideoDirectory(DailyDirectory.parent_path());
std::ostringstream ssVideoFileName; // ffmpeg output video name
ssVideoFileName.fill('0');
ssVideoFileName.width(4);
ssVideoFileName << UTC.tm_year + 1900;
ssVideoFileName.width(2);
ssVideoFileName << UTC.tm_mon + 1;
ssVideoFileName.width(2);
ssVideoFileName << UTC.tm_mday;
const std::string HostName(GetHostnameFromMediaDirectory(DailyDirectory));
if (!HostName.empty())
ssVideoFileName << "-" << HostName;
if (bVideoHD)
{
std::filesystem::path VideoFileName(VideoDirectory / ssVideoFileName.str());
VideoFileName += "-1080p.mp4";
struct stat64 VideoStat;
if (0 == stat64(VideoFileName.c_str(), &VideoStat))
{
if (LastJPGStat.st_mtim.tv_sec > VideoStat.st_mtim.tv_sec)
VideoFiles.push(VideoFileName);
}
else
VideoFiles.push(VideoFileName);
}
if (bVideo4k)
{
std::filesystem::path VideoFileName(VideoDirectory / ssVideoFileName.str());
VideoFileName += "-2160p.mp4";
struct stat64 VideoStat;
if (0 == stat64(VideoFileName.c_str(), &VideoStat))
{
if (LastJPGStat.st_mtim.tv_sec > VideoStat.st_mtim.tv_sec)
VideoFiles.push(VideoFileName);
}
else
VideoFiles.push(VideoFileName);
}
if (bVideoNative)
{
std::filesystem::path VideoFileName(VideoDirectory / ssVideoFileName.str());
VideoFileName += ".mp4";
struct stat64 VideoStat;
if (0 == stat64(VideoFileName.c_str(), &VideoStat))
{
if (LastJPGStat.st_mtim.tv_sec > VideoStat.st_mtim.tv_sec)
VideoFiles.push(VideoFileName);
}
else