forked from sackmotion/motion
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathmotion.c
2356 lines (2018 loc) · 73.9 KB
/
motion.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
/* motion.c
*
* Detect changes in a video stream.
* Copyright 2000 by Jeroen Vreeken ([email protected])
* This software is distributed under the GNU public license version 2
* See also the file 'COPYING'.
*
*/
#include "ffmpeg.h"
#include "motion.h"
#if (defined(BSD))
#include "video_freebsd.h"
#else
#include "video.h"
#endif /* BSD */
#include "conf.h"
#include "alg.h"
#include "track.h"
#include "event.h"
#include "picture.h"
#include "rotate.h"
/**
* tls_key_threadnr
*
* TLS key for storing thread number in thread-local storage.
*/
pthread_key_t tls_key_threadnr;
/**
* global_lock
*
* Protects any global variables (like 'threads_running') during updates,
* to prevent problems with multiple threads updating at the same time.
*/
//pthread_mutex_t global_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t global_lock;
/**
* cnt_list
*
* List of context structures, one for each main Motion thread.
*/
struct context **cnt_list=NULL;
/**
* threads_running
*
* Keeps track of number of Motion threads currently running. Also used
* by 'main' to know when all threads have exited.
*/
volatile int threads_running=0;
/*
* debug_level is for developers, normally used to control which
* types of messages get output.
*/
int debug_level;
/**
* restart
*
* Differentiates between a quit and a restart. When all threads have
* finished running, 'main' checks if 'restart' is true and if so starts
* up again (instead of just quitting).
*/
int restart=0;
/**
* context_init
*
* Initializes a context struct with the default values for all the
* variables.
*
* Parameters:
*
* cnt - the context struct to destroy
*
* Returns: nothing
*/
static void context_init (struct context *cnt)
{
/*
* We first clear the entire structure to zero, then fill in any
* values which have non-zero default values. Note that this
* assumes that a NULL address pointer has a value of binary 0
* (this is also assumed at other places within the code, i.e.
* there are instances of "if (ptr)"). Just for possible future
* changes to this assumption, any pointers which are intended
* to be initialised to NULL are listed within a comment.
*/
memset(cnt, 0, sizeof(struct context));
cnt->noise = 255;
cnt->lastrate = 25;
memcpy(&cnt->track, &track_template, sizeof(struct trackoptions));
cnt->pipe = -1;
cnt->mpipe = -1;
}
/**
* context_destroy
*
* Destroys a context struct by freeing allocated memory, calling the
* appropriate cleanup functions and finally freeing the struct itself.
*
* Parameters:
*
* cnt - the context struct to destroy
*
* Returns: nothing
*/
static void context_destroy(struct context *cnt)
{
int j;
if (cnt->imgs.out)
free(cnt->imgs.out);
if (cnt->imgs.ref)
free(cnt->imgs.ref);
if (cnt->imgs.image_virgin)
free(cnt->imgs.image_virgin);
if (cnt->imgs.image_ring_buffer)
free(cnt->imgs.image_ring_buffer);
if (cnt->imgs.labels)
free(cnt->imgs.labels);
if (cnt->imgs.labelsize)
free(cnt->imgs.labelsize);
if (cnt->imgs.smartmask)
free(cnt->imgs.smartmask);
if (cnt->imgs.smartmask_final)
free(cnt->imgs.smartmask_final);
if (cnt->imgs.smartmask_buffer)
free(cnt->imgs.smartmask_buffer);
if (cnt->imgs.common_buffer)
free(cnt->imgs.common_buffer);
if (cnt->imgs.timestamp)
free(cnt->imgs.timestamp);
if (cnt->imgs.shotstamp)
free(cnt->imgs.shotstamp);
if (cnt->imgs.preview_buffer)
free(cnt->imgs.preview_buffer);
rotate_deinit(cnt); /* cleanup image rotation data */
if(cnt->pipe != -1)
close(cnt->pipe);
if(cnt->mpipe != -1)
close(cnt->mpipe);
/* Cleanup the netcam part */
if(cnt->netcam)
netcam_cleanup(cnt->netcam, 0);
/* Cleanup the current time structure */
if (cnt->currenttime_tm)
free(cnt->currenttime_tm);
/* Cleanup the event time structure */
if (cnt->eventtime_tm)
free(cnt->eventtime_tm);
/* Free memory allocated for config parameters */
for (j = 0; config_params[j].param_name != NULL; j++) {
if (config_params[j].copy == copy_string) {
void **val;
val = (void *)((char *)cnt+(int)config_params[j].conf_value);
if (*val) {
free(*val);
*val = NULL;
}
}
}
free(cnt);
}
/**
* sig_handler
*
* Our SIGNAL-Handler. We need this to handle alarms and external signals.
*/
static void sig_handler(int signo)
{
int i;
switch(signo) {
case SIGALRM:
/* Somebody (maybe we ourself) wants us to make a snapshot
* This feature triggers snapshots on ALL threads that have
* snapshot_interval different from 0.
*/
if (cnt_list) {
i = -1;
while (cnt_list[++i]) {
if (cnt_list[i]->conf.snapshot_interval) {
cnt_list[i]->snapshot=1;
}
}
}
break;
case SIGUSR1:
/* Ouch! We have been hit from the outside! Someone wants us to
make a movie! */
if (cnt_list) {
i = -1;
while (cnt_list[++i])
cnt_list[i]->makemovie=1;
}
break;
case SIGHUP:
restart = 1;
/* Fall through, as the value of 'restart' is the only difference
* between SIGHUP and the ones below.
*/
case SIGINT:
case SIGQUIT:
case SIGTERM:
/* Somebody wants us to quit! We should better finish the actual
movie and end up! */
if (cnt_list) {
i = -1;
while (cnt_list[++i]) {
cnt_list[i]->makemovie=1;
cnt_list[i]->finish=1;
}
}
break;
case SIGSEGV:
exit(0);
}
}
/**
* sigchild_handler
*
* This function is a POSIX compliant replacement of the commonly used
* signal(SIGCHLD, SIG_IGN).
*/
static void sigchild_handler(int signo ATTRIBUTE_UNUSED)
{
#ifdef WNOHANG
while (waitpid(-1, NULL, WNOHANG) > 0) {};
#endif /* WNOHANG */
return;
}
/**
* motion_detected
*
* Called from 'motion_loop' when motion is detected, or when to act as if
* motion was detected (e.g. in post capture).
*
* Parameters:
*
* cnt - current thread's context struct
* diffs - number of different pixels between the reference image and the
* new image (may be zero)
* dev - video device file descriptor
* devpipe - file descriptor of still image pipe
* devmpipe - file descriptor of motion pipe
* newimg - pointer to the newly captured image
*/
static void motion_detected(struct context *cnt, int diffs, int dev, unsigned char *newimg)
{
struct config *conf = &cnt->conf;
struct images *imgs = &cnt->imgs;
struct coord *location = &cnt->location;
cnt->lasttime = cnt->currenttime;
/* Take action if this is a new event */
if (cnt->event_nr != cnt->prev_event) {
int i, tmpshots;
struct tm tmptime;
cnt->preview_max = 0;
/* Reset prev_event number to current event and save event time
* in both time_t and struct tm format.
*/
cnt->prev_event = cnt->event_nr;
cnt->eventtime = cnt->currenttime;
localtime_r(&cnt->eventtime, cnt->eventtime_tm);
/* Since this is a new event we create the event_text_string used for
* the %C conversion specifier. We may already need it for
* on_motion_detected_commend so it must be done now.
*/
mystrftime(cnt, cnt->text_event_string, sizeof(cnt->text_event_string),
cnt->conf.text_event, cnt->eventtime_tm, NULL, 0);
/* EVENT_FIRSTMOTION triggers on_event_start_command and event_ffmpeg_newfile */
event(cnt, EVENT_FIRSTMOTION, newimg, NULL, NULL, cnt->currenttime_tm);
if (cnt->conf.setup_mode)
motion_log(-1, 0, "Motion detected - starting event %d", cnt->event_nr);
/* pre_capture frames are written as jpegs and to the ffmpeg film
* We store the current cnt->shots temporarily until we are done with
* the pre_capture stuff
*/
tmpshots = cnt->shots;
for (i=cnt->precap_cur; i < cnt->precap_nr; i++) {
localtime_r(cnt->imgs.timestamp + i, &tmptime);
cnt->shots = *(cnt->imgs.shotstamp + i);
event(cnt, EVENT_IMAGE_DETECTED,
cnt->imgs.image_ring_buffer + (cnt->imgs.size * i), NULL, NULL, &tmptime);
}
if (cnt->precap_cur) {
localtime_r(cnt->imgs.timestamp+cnt->precap_nr, &tmptime);
cnt->shots = *(cnt->imgs.shotstamp + cnt->precap_nr);
event(cnt, EVENT_IMAGE_DETECTED,
cnt->imgs.image_ring_buffer + (cnt->imgs.size * cnt->precap_nr),
NULL, NULL, &tmptime);
}
for (i=0; i < cnt->precap_cur-1; i++) {
localtime_r(cnt->imgs.timestamp + i, &tmptime);
cnt->shots = *(cnt->imgs.shotstamp + i);
event(cnt, EVENT_IMAGE_DETECTED,
cnt->imgs.image_ring_buffer + (cnt->imgs.size * i),
NULL, NULL, &tmptime);
}
/* If output_normal=first always capture first motion frame as preview-shot */
if (cnt->new_img == NEWIMG_FIRST){
cnt->preview_shot = 1;
if (cnt->locate == LOCATE_PREVIEW){
alg_draw_location(location, imgs, imgs->width, newimg, LOCATE_NORMAL);
}
}
cnt->shots = tmpshots;
}
/* motion_detected is called with diffs = 0 during post_capture
* and if cnt->conf.output_all is enabled. We only want to draw location
* and call EVENT_MOTION when it is a picture frame with actual motion detected.
*/
if (diffs) {
if (cnt->locate == LOCATE_ON)
alg_draw_location(location, imgs, imgs->width, newimg, LOCATE_BOTH);
/* EVENT_MOTION triggers event_beep and on_motion_detected_command */
event(cnt, EVENT_MOTION, NULL, NULL, NULL, cnt->currenttime_tm);
}
/* Check for most significant preview-shot when output_normal=best */
if (cnt->new_img == NEWIMG_BEST && diffs > cnt->preview_max) {
memcpy(cnt->imgs.preview_buffer, newimg, cnt->imgs.size);
cnt->preview_max = diffs;
if (cnt->locate == LOCATE_PREVIEW){
alg_draw_location(location, imgs, imgs->width, cnt->imgs.preview_buffer, LOCATE_NORMAL);
}
}
if (cnt->shots < conf->frame_limit) {
cnt->lastshottime = cnt->currenttime;
/* Output the latest picture 'image_new' or image_out for motion picture. */
event(cnt, EVENT_IMAGE_DETECTED, newimg, NULL, NULL, cnt->currenttime_tm);
/* If config option webcam_motion is enabled, send the latest motion detected image
* to the webcam but only if it is not the first shot within a second. This is to
* avoid double frames since we already have sent a frame to the webcam.
* We also disable this in setup_mode.
*/
if (conf->webcam_motion && !conf->setup_mode && cnt->shots != 1)
event(cnt, EVENT_WEBCAM, newimg, NULL, NULL, cnt->currenttime_tm);
cnt->preview_shot = 0;
}
if (cnt->track.type != 0 && diffs != 0) {
cnt->moved = track_move(cnt, dev, &cnt->location, imgs, 0);
}
}
/**
* motion_remove_pid
*
* This function remove the process id file ( pid file ) before motion exit.
*
*/
static void motion_remove_pid(void)
{
if ((cnt_list[0]->daemon) && (cnt_list[0]->conf.pid_file) && (restart == 0)){
if (!unlink(cnt_list[0]->conf.pid_file)) motion_log(LOG_INFO, 0, "Removed process id file (pid file).");
else motion_log(LOG_INFO, 1, "Error removing pid file");
}
}
/**
* motion_init
*
* This routine is called from motion_loop (the main thread of the program) to do
* all of the initialisation required before starting the actual run.
*
* Parameters:
*
* cnt Pointer to the motion context structure
*
* Returns: nothing
*/
static void motion_init(struct context *cnt)
{
int i;
FILE *picture;
/* Store thread number in TLS. */
pthread_setspecific(tls_key_threadnr, (void *)((unsigned long)cnt->threadnr));
cnt->diffs = 0;
cnt->currenttime_tm = mymalloc(sizeof(struct tm));
cnt->eventtime_tm = mymalloc(sizeof(struct tm));
cnt->smartmask_speed = 0;
/* We initialize cnt->event_nr to 1 and cnt->prev_event to 0 (not really needed) so
* that certain code below does not run until motion has been detected the first time */
cnt->event_nr = 1;
cnt->prev_event = 0;
motion_log(LOG_DEBUG, 0, "Thread started");
if (!cnt->conf.filepath)
cnt->conf.filepath = strdup(".");
/* set the device settings */
cnt->video_dev = vid_start(cnt);
/* We still cannot handle a V4L type camera not being available
* during startup. We have no other option than to die
*/
if (cnt->video_dev == -1 && !cnt->conf.netcam_url) {
motion_log(LOG_ERR, 0, "Capture error calling vid_start");
motion_log(-1 , 0, "Thread finishing...");
motion_remove_pid();
exit(1);
}
/* We failed to get an initial image from a network camera
* So we need to guess height and width based on the config
* file options.
*/
if (cnt->video_dev == -1) {
motion_log(LOG_ERR, 0, "Could not fetch initial image from network camera");
motion_log(LOG_ERR, 0, "Motion continues using width and height from config file(s)");
cnt->imgs.width = cnt->conf.width;
cnt->imgs.height = cnt->conf.height;
cnt->imgs.size = cnt->conf.width * cnt->conf.height * 3 / 2;
cnt->imgs.motionsize = cnt->conf.width * cnt->conf.height;
cnt->imgs.type = VIDEO_PALETTE_YUV420P;
}
cnt->imgs.image_ring_buffer = mymalloc(cnt->imgs.size);
memset(cnt->imgs.image_ring_buffer, 0x80, cnt->imgs.size); /* initialize to grey */
cnt->imgs.ref = mymalloc(cnt->imgs.size);
cnt->imgs.out = mymalloc(cnt->imgs.size);
cnt->imgs.image_virgin = mymalloc(cnt->imgs.size);
memset(cnt->imgs.image_virgin, 0x80, cnt->imgs.size); /* initialize to grey */
cnt->imgs.smartmask = mymalloc(cnt->imgs.motionsize);
cnt->imgs.smartmask_final = mymalloc(cnt->imgs.motionsize);
cnt->imgs.smartmask_buffer = mymalloc(cnt->imgs.motionsize * sizeof(int));
cnt->imgs.labels = mymalloc(cnt->imgs.motionsize * sizeof(cnt->imgs.labels));
cnt->imgs.labelsize = mymalloc((cnt->imgs.motionsize/2+1) * sizeof(cnt->imgs.labelsize));
cnt->imgs.timestamp = mymalloc(sizeof(time_t));
cnt->imgs.shotstamp = mymalloc(sizeof(int));
/* Allocate a buffer for temp. usage in some places */
/* Only despeckle & bayer2rgb24() for now for now... */
cnt->imgs.common_buffer = mymalloc(3 * cnt->imgs.width * cnt->imgs.height);
/* Now is a good time to init rotation data. Since vid_start has been
* called, we know that we have imgs.width and imgs.height. When capturing
* from a V4L device, these are copied from the corresponding conf values
* in vid_start. When capturing from a netcam, they get set in netcam_start,
* which is called from vid_start.
*
* rotate_init will set cap_width and cap_height in cnt->rotate_data.
*/
rotate_init(cnt); /* rotate_deinit is called in main */
/* Allow videodevice to settle in */
/* Capture first image, or we will get an alarm on start */
if (cnt->video_dev > 0) {
for (i = 0; i < 10; i++) {
if (vid_next(cnt, cnt->imgs.image_virgin) == 0)
break;
SLEEP(2,0);
}
/* We still cannot handle a V4L type camera not being available
* during startup. We have no other option than to die
*/
if (i >= 10) {
motion_log(LOG_ERR, 0, "Error capturing first image");
motion_log(-1, 0, "Thread finishing...");
motion_remove_pid();
exit(1);
}
}
/* create a reference frame */
memcpy(cnt->imgs.ref, cnt->imgs.image_virgin, cnt->imgs.size);
#ifndef WITHOUT_V4L
#if (!defined(BSD))
/* open video loopback devices if enabled */
if (cnt->conf.vidpipe) {
if (cnt->conf.setup_mode)
motion_log(-1, 0, "Opening video loopback device for normal pictures");
/* vid_startpipe should get the output dimensions */
cnt->pipe = vid_startpipe(cnt->conf.vidpipe, cnt->imgs.width, cnt->imgs.height, cnt->imgs.type);
if (cnt->pipe < 0) {
motion_log(LOG_ERR, 0, "Failed to open video loopback");
motion_log(-1, 0, "Thread finishing...");
motion_remove_pid();
exit(1);
}
}
if (cnt->conf.motionvidpipe) {
if (cnt->conf.setup_mode)
motion_log(-1, 0, "Opening video loopback device for motion pictures");
/* vid_startpipe should get the output dimensions */
cnt->mpipe = vid_startpipe(cnt->conf.motionvidpipe, cnt->imgs.width, cnt->imgs.height, cnt->imgs.type);
if (cnt->mpipe < 0) {
motion_log(LOG_ERR, 0, "Failed to open video loopback");
motion_log(-1, 0, "Thread finishing...");
motion_remove_pid();
exit(1);
}
}
#endif /* BSD */
#endif /*WITHOUT_V4L*/
#ifdef HAVE_MYSQL
if(cnt->conf.mysql_db) {
cnt->database = (MYSQL *) mymalloc(sizeof(MYSQL));
mysql_init(cnt->database);
if (!mysql_real_connect(cnt->database, cnt->conf.mysql_host, cnt->conf.mysql_user,
cnt->conf.mysql_password, cnt->conf.mysql_db, 0, NULL, 0)) {
motion_log(LOG_ERR, 0, "Cannot connect to MySQL database %s on host %s with user %s",
cnt->conf.mysql_db, cnt->conf.mysql_host, cnt->conf.mysql_user);
motion_log(LOG_ERR, 0, "MySQL error was %s", mysql_error(cnt->database));
motion_log(-1, 0, "Thread finishing...");
motion_remove_pid();
exit(1);
}
}
#endif /* HAVE_MYSQL */
#ifdef HAVE_PGSQL
if (cnt->conf.pgsql_db) {
char connstring[255];
/* create the connection string.
Quote the values so we can have null values (blank)*/
snprintf(connstring, 255,
"dbname='%s' host='%s' user='%s' password='%s' port='%d'",
cnt->conf.pgsql_db, /* dbname */
(cnt->conf.pgsql_host ? cnt->conf.pgsql_host : ""), /* host (may be blank) */
(cnt->conf.pgsql_user ? cnt->conf.pgsql_user : ""), /* user (may be blank) */
(cnt->conf.pgsql_password ? cnt->conf.pgsql_password : ""), /* password (may be blank) */
cnt->conf.pgsql_port
);
cnt->database_pg = PQconnectdb(connstring);
if (PQstatus(cnt->database_pg) == CONNECTION_BAD) {
motion_log(LOG_ERR, 0, "Connection to PostgreSQL database '%s' failed: %s",
cnt->conf.pgsql_db, PQerrorMessage(cnt->database_pg));
motion_log(-1, 0, "Thread finishing...");
motion_remove_pid();
exit(1);
}
}
#endif /* HAVE_PGSQL */
#if defined(HAVE_MYSQL) || defined(HAVE_PGSQL)
/* Set the sql mask file according to the SQL config options*/
cnt->sql_mask = cnt->conf.sql_log_image * (FTYPE_IMAGE + FTYPE_IMAGE_MOTION) +
cnt->conf.sql_log_snapshot * FTYPE_IMAGE_SNAPSHOT +
cnt->conf.sql_log_mpeg * (FTYPE_MPEG + FTYPE_MPEG_MOTION) +
cnt->conf.sql_log_timelapse * FTYPE_MPEG_TIMELAPSE;
#endif /* defined(HAVE_MYSQL) || defined(HAVE_PGSQL) */
/* Load the mask file if any */
if (cnt->conf.mask_file) {
if ((picture = fopen(cnt->conf.mask_file, "r"))) {
/* NOTE: The mask is expected to have the output dimensions. I.e., the mask
* applies to the already rotated image, not the capture image. Thus, use
* width and height from imgs.
*/
cnt->imgs.mask = get_pgm(picture, cnt->imgs.width, cnt->imgs.height);
fclose(picture);
} else {
motion_log(LOG_ERR, 1, "Error opening mask file %s", cnt->conf.mask_file);
/* Try to write an empty mask file to make it easier
for the user to edit it */
put_fixed_mask(cnt, cnt->conf.mask_file);
}
if (!cnt->imgs.mask) {
motion_log(LOG_ERR, 0, "Failed to read mask image. Mask feature disabled.");
} else {
if (cnt->conf.setup_mode)
motion_log(-1, 0, "Maskfile \"%s\" loaded.",cnt->conf.mask_file);
}
} else
cnt->imgs.mask=NULL;
/* Always initialize smart_mask - someone could turn it on later... */
memset(cnt->imgs.smartmask, 0, cnt->imgs.motionsize);
memset(cnt->imgs.smartmask_final, 255, cnt->imgs.motionsize);
memset(cnt->imgs.smartmask_buffer, 0, cnt->imgs.motionsize*sizeof(int));
/* Set noise level */
cnt->noise = cnt->conf.noise;
/* Set threshold value */
cnt->threshold = cnt->conf.max_changes;
/* Initialize webcam server if webcam port is specified to not 0 */
if (cnt->conf.webcam_port) {
if ( webcam_init(cnt) == -1 ) {
motion_log(LOG_ERR, 1, "Problem enabling stream server in port %d", cnt->conf.webcam_port);
cnt->finish = 1;
cnt->makemovie = 0;
}else motion_log(LOG_DEBUG, 0, "Started stream webcam server in port %d", cnt->conf.webcam_port);
}
/* Prevent first few frames from triggering motion... */
cnt->moved = 8;
}
/**
* motion_loop
*
* Thread function for the motion handling threads.
*
*/
static void *motion_loop(void *arg)
{
struct context *cnt = arg;
int i, j, detecting_motion = 0;
time_t lastframetime = 0;
int postcap = 0;
int frame_buffer_size;
int smartmask_ratio = 0;
int smartmask_count = 20;
int smartmask_lastrate = 0;
int olddiffs = 0;
int text_size_factor;
int passflag = 0;
long int *rolling_average_data;
long int rolling_average_limit, required_frame_time, frame_delay, delay_time_nsec;
int rolling_frame = 0;
struct timeval tv1, tv2;
unsigned long int rolling_average, elapsedtime;
unsigned long long int timenow = 0, timebefore = 0;
unsigned char *newimg = NULL; /* Pointer to where new image is stored */
int vid_return_code = 0; /* Return code used when calling vid_next */
int minimum_frame_time_downcounter = cnt->conf.minimum_frame_time; /* time in seconds to skip between capturing images */
int get_image = 1; /* Flag used to signal that we capture new image when we run the loop */
/* Next two variables are used for snapshot and timelapse feature
* time_last_frame is set to 1 so that first coming timelapse or second=0
* is acted upon.
*/
unsigned long int time_last_frame=1, time_current_frame;
motion_init(cnt);
/* Initialize the double sized characters if needed. */
if(cnt->conf.text_double)
text_size_factor = 2;
else
text_size_factor = 1;
/* Work out expected frame rate based on config setting */
if (cnt->conf.frame_limit < 2) cnt->conf.frame_limit = 2;
required_frame_time = 1000000L / cnt->conf.frame_limit;
frame_delay = required_frame_time;
/*
* Reserve enough space for a 10 second timing history buffer. Note that,
* if there is any problem on the allocation, mymalloc does not return.
*/
rolling_average_limit = 10 * cnt->conf.frame_limit;
rolling_average_data = mymalloc(sizeof(long int) * rolling_average_limit);
/* Preset history buffer with expected frame rate */
for (j=0; j< rolling_average_limit; j++)
rolling_average_data[j]=required_frame_time;
/* MAIN MOTION LOOP BEGINS HERE */
/* Should go on forever... unless you bought vaporware :) */
while (!cnt->finish || cnt->makemovie) {
/***** MOTION LOOP - PREPARE FOR NEW FRAME SECTION *****/
/* Get current time and preserver last time for frame interval calc. */
timebefore = timenow;
gettimeofday(&tv1, NULL);
timenow = tv1.tv_usec + 1000000L * tv1.tv_sec;
/* since we don't have sanity checks done when options are set,
* this sanity check must go in the main loop :(, before pre_captures
* are attempted. */
if (cnt->conf.minimum_motion_frames < 1)
cnt->conf.minimum_motion_frames = 1;
if (cnt->conf.pre_capture < 0)
cnt->conf.pre_capture = 0;
/* Check if our buffer is still the right size
* If pre_capture or minimum_motion_frames has been changed
* via the http remote control we need to re-size the ring buffer
*/
frame_buffer_size = cnt->conf.pre_capture + cnt->conf.minimum_motion_frames - 1;
if (cnt->precap_nr != frame_buffer_size) {
/* Only decrease if at last position in new buffer */
if (frame_buffer_size > cnt->precap_nr || frame_buffer_size == cnt->precap_cur) {
unsigned char *tmp;
time_t *tmp2;
int *tmp3;
int smallest;
smallest = (cnt->precap_nr < frame_buffer_size) ? cnt->precap_nr : frame_buffer_size;
tmp=mymalloc(cnt->imgs.size*(1+frame_buffer_size));
tmp2=mymalloc(sizeof(time_t)*(1+frame_buffer_size));
tmp3=mymalloc(sizeof(int)*(1+frame_buffer_size));
memcpy(tmp, cnt->imgs.image_ring_buffer, cnt->imgs.size * (1+smallest));
memcpy(tmp2, cnt->imgs.timestamp, sizeof(time_t) * (1+smallest));
memcpy(tmp3, cnt->imgs.shotstamp, sizeof(int) * (1+smallest));
free(cnt->imgs.image_ring_buffer);
free(cnt->imgs.timestamp);
free(cnt->imgs.shotstamp);
cnt->imgs.image_ring_buffer = tmp;
cnt->imgs.timestamp = tmp2;
cnt->imgs.shotstamp = tmp3;
cnt->precap_nr = frame_buffer_size;
}
}
/* Get time for current frame */
cnt->currenttime = time(NULL);
/* localtime returns static data and is not threadsafe
* so we use localtime_r which is reentrant and threadsafe
*/
localtime_r(&cnt->currenttime, cnt->currenttime_tm);
/* If we have started on a new second we reset the shots variable
* lastrate is updated to be the number of the last frame. last rate
* is used as the ffmpeg framerate when motion is detected.
*/
if (lastframetime != cnt->currenttime) {
cnt->lastrate = cnt->shots + 1;
cnt->shots = -1;
lastframetime = cnt->currenttime;
if (cnt->conf.minimum_frame_time) {
minimum_frame_time_downcounter--;
if (minimum_frame_time_downcounter == 0)
get_image = 1;
}
else
get_image = 1;
}
/* Increase the shots variable for each frame captured within this second */
cnt->shots++;
if (get_image){
if (cnt->conf.minimum_frame_time) {
minimum_frame_time_downcounter = cnt->conf.minimum_frame_time;
get_image = 0;
}
/* Store time with pre_captured image*/
*(cnt->imgs.timestamp + cnt->precap_cur) = cnt->currenttime;
/* Store shot number with pre_captured image*/
*(cnt->imgs.shotstamp+cnt->precap_cur) = cnt->shots;
/* newimg now points to the current image. With precap_cur incremented it
* will be pointing to the position in the buffer for the NEXT image frame
* not the current!!! So newimg points to current frame about to be loaded
* and the cnt->precap_cur already have been incremented to point to the
* next frame.
*/
newimg = cnt->imgs.image_ring_buffer + (cnt->imgs.size * (cnt->precap_cur++));
/* If we are at the end of the ring buffer go to the start */
if (cnt->precap_cur > cnt->precap_nr)
cnt->precap_cur=0;
/***** MOTION LOOP - RETRY INITIALIZING NETCAM SECTION *****/
/* If a network camera is not available we keep on retrying every 10 seconds
* until it shows up.
*/
if (cnt->video_dev == -1 && cnt->conf.netcam_url &&
cnt->currenttime % 10 == 0 && cnt->shots == 0) {
motion_log(LOG_ERR, 0,
"Retrying until successful initial connection with network camera");
netcam_cleanup(cnt->netcam, 1);
cnt->netcam = NULL;
cnt->video_dev = vid_start(cnt);
/* if the netcam has different dimensions than in the config file
* we need to restart Motion to re-allocate all the buffers
*/
if (cnt->imgs.width != cnt->imgs.width || cnt->imgs.height != cnt->conf.height) {
motion_log(LOG_ERR, 0, "Network camera has finally become available");
motion_log(LOG_ERR, 0, "Network camera image has different width and height "
"from what is in the config file. You should fix that");
motion_log(LOG_ERR, 0, "Restarting Motion to reinitialize all "
"image buffers to new picture dimensions");
kill(getpid(), 1);
break;
}
}
/***** MOTION LOOP - IMAGE CAPTURE SECTION *****/
/* Fetch next frame from camera
* If vid_next returns 0 all is well and we got a new picture
* Any non zero value is an error.
* 0 = OK, valid picture
* <0 = fatal error - leave the thread by breaking out of the main loop
* >0 = non fatal error - copy last image or show grey image with message
*/
vid_return_code = vid_next(cnt, newimg);
// VALID PICTURE
if (vid_return_code == 0) {
cnt->lost_connection = 0;
/* If all is well reset missing_frame_counter */
if (cnt->missing_frame_counter >= MISSING_FRAMES_TIMEOUT * cnt->conf.frame_limit) {
/* If we previously logged starting a grey image, now log video re-start */
motion_log(LOG_ERR, 0, "Video signal re-acquired");
// event for re-acquired video signal can be called here
}
cnt->missing_frame_counter = 0;
#ifdef HAVE_FFMPEG
/* Deinterlace the image with ffmpeg, before the image is modified. */
if(cnt->conf.ffmpeg_deinterlace) {
ffmpeg_deinterlace(newimg, cnt->imgs.width, cnt->imgs.height);
}
#endif
/* save the newly captured still virgin image to a buffer
* which we will not alter with text and location graphics
*/
memcpy(cnt->imgs.image_virgin, newimg, cnt->imgs.size);
/* If the camera is a netcam we let the camera decide the pace.
* Otherwise we will keep on adding duplicate frames.
* By resetting the timer the framerate becomes maximum the rate
* of the Netcam.
*/
if (cnt->conf.netcam_url) {
gettimeofday(&tv1, NULL);
timenow = tv1.tv_usec + 1000000L * tv1.tv_sec;
}
// FATAL ERROR - leave the thread by breaking out of the main loop
} else if (vid_return_code < 0) {
/* Fatal error - break out of main loop terminating thread */
motion_log(LOG_ERR, 0, "Video device fatal error - terminating camera thread");
break;
// NO FATAL ERROR - copy last image or show grey image with message
} else {
cnt->lost_connection = 1;
if (debug_level)
motion_log(-1, 0, "vid_return_code %d", vid_return_code);
/* Netcams that change dimensions while Motion is running will
* require that Motion restarts to reinitialize all the many
* buffers inside Motion. It will be a mess to try and recover any
* other way
*/
if (vid_return_code == NETCAM_RESTART_ERROR) {
motion_log(LOG_ERR, 0, "Restarting Motion to reinitialize all "
"image buffers");
kill(getpid(), 1);
break;
}
/* First missed frame - store timestamp */
if (!cnt->missing_frame_counter)
cnt->connectionlosttime = cnt->currenttime;
/* If we are waiting for first image prevent the
* cnt->connectionlosttime from being updated each time we come back
*/
if (cnt->video_dev == -1)
cnt->missing_frame_counter = 1;
/* Increase missing_frame_counter
* The first MISSING_FRAMES_TIMEOUT seconds we copy previous virgin image
* After 30 seconds we put a grey error image in the buffer
* Note: at low_cpu the timeout will be longer but we live with that
* If we still have not yet received the initial image from a camera
* we go straight for the grey error image.
*/
if (cnt->video_dev != -1 &&
++cnt->missing_frame_counter < (MISSING_FRAMES_TIMEOUT * cnt->conf.frame_limit)) {
memcpy(newimg, cnt->imgs.image_virgin, cnt->imgs.size);
} else {
char tmpout[80];
char tmpin[] = "CONNECTION TO CAMERA LOST\\nSINCE %Y-%m-%d %T";
struct tm tmptime;
localtime_r(&cnt->connectionlosttime, &tmptime);
memset(newimg, 0x80, cnt->imgs.size);
mystrftime(cnt, tmpout, sizeof(tmpout), tmpin, &tmptime, NULL, 0);
draw_text(newimg, 10, 20 * text_size_factor, cnt->imgs.width,
tmpout, cnt->conf.text_double);
/* Write error message only once */
if (cnt->missing_frame_counter == MISSING_FRAMES_TIMEOUT * cnt->conf.frame_limit) {
motion_log(LOG_ERR, 0, "Video signal lost - Adding grey image");
// Event for lost video signal can be called from here
}
}
}
/***** MOTION LOOP - MOTION DETECTION SECTION *****/
/* The actual motion detection takes place in the following
* diffs is the number of pixels detected as changed
* Make a differences picture in image_out
*
* alg_diff_standard is the slower full feature motion detection algorithm
* alg_diff first calls a fast detection algorithm which only looks at a
* fraction of the pixels. If this detects possible motion alg_diff_standard
* is called.
*/
if (cnt->threshold && !cnt->pause) {
/* if we've already detected motion and we want to see if there's
* still motion, don't bother trying the fast one first. IF there's
* motion, the alg_diff will trigger alg_diff_standard
* anyway
*/
if (detecting_motion || cnt->conf.setup_mode)
cnt->diffs = alg_diff_standard(cnt, cnt->imgs.image_virgin);
else
cnt->diffs = alg_diff(cnt, cnt->imgs.image_virgin);
/* Lightswitch feature - has light intensity changed?
* This can happen due to change of light conditions or due to a sudden change of the camera
* sensitivity. If alg_lightswitch detects lightswitch we suspend motion detection the next
* 5 frames to allow the camera to settle.
*/
if (cnt->conf.lightswitch) {
if (alg_lightswitch(cnt, cnt->diffs)) {
if (cnt->conf.setup_mode)
motion_log(-1, 0, "Lightswitch detected");
if (cnt->moved < 5)
cnt->moved = 5;
cnt->diffs = 0;
}
}
/* Switchfilter feature tries to detect a change in the video signal
* from one camera to the next. This is normally used in the Round
* Robin feature. The algorithm is not very safe.
* The algorithm takes a little time so we only call it when needed
* ie. when feature is enabled and diffs>threshold.
* We do not suspend motion detection like we did for lightswitch
* because with Round Robin this is controlled by roundrobin_skip.
*/
if (cnt->conf.switchfilter && cnt->diffs > cnt->threshold) {
cnt->diffs = alg_switchfilter(cnt, cnt->diffs, newimg);
if (cnt->diffs <= cnt->threshold) {
cnt->diffs = 0;
if (cnt->conf.setup_mode)
motion_log(-1, 0, "Switchfilter detected");
}
}
/* Despeckle feature
* First we run (as given by the despeckle option iterations
* of erode and dilate algorithms.