-
Notifications
You must be signed in to change notification settings - Fork 204
/
motion.c
3249 lines (2773 loc) · 120 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) && !defined(PWCBSD))
#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"
/* Forward declarations */
static int motion_init(struct context *cnt);
static void motion_cleanup(struct context *cnt);
/**
* 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;
/* Set this when we want main to end or restart */
volatile unsigned int finish = 0;
/* Log file used instead of stderr and syslog */
FILE *ptr_logfile = NULL;
/**
* 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).
*/
unsigned int restart = 0;
/**
* image_ring_resize
*
* This routine is called from motion_loop to resize the image precapture ringbuffer
* NOTE: This function clears all images in the old ring buffer
* Parameters:
*
* cnt Pointer to the motion context structure
* new_size The new size of the ring buffer
*
* Returns: nothing
*/
static void image_ring_resize(struct context *cnt, int new_size)
{
/*
* Only resize if :
* Not in an event and
* decreasing at last position in new buffer
* increasing at last position in old buffer
* e.g. at end of smallest buffer
*/
if (cnt->event_nr != cnt->prev_event) {
int smallest;
if (new_size < cnt->imgs.image_ring_size) /* Decreasing */
smallest = new_size;
else /* Increasing */
smallest = cnt->imgs.image_ring_size;
if (cnt->imgs.image_ring_in == smallest - 1 || smallest == 0) {
MOTION_LOG(NTC, TYPE_ALL, NO_ERRNO, "%s: Resizing pre_capture buffer to %d items",
new_size);
/* Create memory for new ring buffer */
struct image_data *tmp;
tmp = mymalloc(new_size * sizeof(struct image_data));
/*
* Copy all information from old to new
* Smallest is 0 at initial init
*/
if (smallest > 0)
memcpy(tmp, cnt->imgs.image_ring, sizeof(struct image_data) * smallest);
/* In the new buffers, allocate image memory */
{
int i;
for(i = smallest; i < new_size; i++) {
tmp[i].image = mymalloc(cnt->imgs.size);
memset(tmp[i].image, 0x80, cnt->imgs.size); /* initialize to grey */
}
}
/* Free the old ring */
free(cnt->imgs.image_ring);
/* Point to the new ring */
cnt->imgs.image_ring = tmp;
cnt->imgs.image_ring_size = new_size;
}
}
}
/**
* image_ring_destroy
*
* This routine is called when we want to free the ring
*
* Parameters:
*
* cnt Pointer to the motion context structure
*
* Returns: nothing
*/
static void image_ring_destroy(struct context *cnt)
{
int i;
/* Exit if don't have any ring */
if (cnt->imgs.image_ring == NULL)
return;
/* Free all image buffers */
for (i = 0; i < cnt->imgs.image_ring_size; i++)
free(cnt->imgs.image_ring[i].image);
/* Free the ring */
free(cnt->imgs.image_ring);
cnt->imgs.image_ring = NULL;
cnt->imgs.image_ring_size = 0;
}
/**
* image_save_as_preview
*
* This routine is called when we detect motion and want to save a image in the preview buffer
*
* Parameters:
*
* cnt Pointer to the motion context structure
* img Pointer to the image_data structure we want to set as preview image
*
* Returns: nothing
*/
static void image_save_as_preview(struct context *cnt, struct image_data *img)
{
void * image;
/* Save preview image pointer */
image = cnt->imgs.preview_image.image;
/* Copy all info */
memcpy(&cnt->imgs.preview_image.image, img, sizeof(struct image_data));
/* restore image pointer */
cnt->imgs.preview_image.image = image;
/* Copy image */
memcpy(cnt->imgs.preview_image.image, img->image, cnt->imgs.size);
/*
* If we set output_all to yes and during the event
* there is no image with motion, diffs is 0, we are not going to save the preview event
*/
if (cnt->imgs.preview_image.diffs == 0)
cnt->imgs.preview_image.diffs = 1;
/* draw locate box here when mode = LOCATE_PREVIEW */
if (cnt->locate_motion_mode == LOCATE_PREVIEW) {
if (cnt->locate_motion_style == LOCATE_BOX) {
alg_draw_location(&img->location, &cnt->imgs, cnt->imgs.width, cnt->imgs.preview_image.image,
LOCATE_BOX, LOCATE_NORMAL, cnt->process_thisframe);
} else if (cnt->locate_motion_style == LOCATE_REDBOX) {
alg_draw_red_location(&img->location, &cnt->imgs, cnt->imgs.width, cnt->imgs.preview_image.image,
LOCATE_REDBOX, LOCATE_NORMAL, cnt->process_thisframe);
} else if (cnt->locate_motion_style == LOCATE_CROSS) {
alg_draw_location(&img->location, &cnt->imgs, cnt->imgs.width, cnt->imgs.preview_image.image,
LOCATE_CROSS, LOCATE_NORMAL, cnt->process_thisframe);
} else if (cnt->locate_motion_style == LOCATE_REDCROSS) {
alg_draw_red_location(&img->location, &cnt->imgs, cnt->imgs.width, cnt->imgs.preview_image.image,
LOCATE_REDCROSS, LOCATE_NORMAL, cnt->process_thisframe);
}
}
}
/**
* 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)
{
unsigned int j;
/* 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;
/*
* Don't restart thread when it ends,
* all threads restarts if global restart is set
*/
cnt_list[i]->restart = 0;
}
}
/*
* Set flag we want to quit main check threads loop
* if restart is set (above) we start up again
*/
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_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(NTC, TYPE_ALL, NO_ERRNO, "%s: Removed process id file (pid file).");
else
MOTION_LOG(ERR, TYPE_ALL, SHOW_ERRNO, "%s: Error removing pid file");
}
if (ptr_logfile) {
MOTION_LOG(NTC, TYPE_ALL, NO_ERRNO, "%s: Closing logfile (%s).",
cnt_list[0]->conf.log_file);
myfclose(ptr_logfile);
set_log_mode(LOGMODE_SYSLOG);
ptr_logfile = NULL;
}
}
/**
* motion_detected
*
* Called from 'motion_loop' when motion is detected
* Can be called when no motion if emulate_motion is set!
*
* Parameters:
*
* cnt - current thread's context struct
* dev - video device file descriptor
* img - pointer to the captured image_data with detected motion
*/
static void motion_detected(struct context *cnt, int dev, struct image_data *img)
{
struct config *conf = &cnt->conf;
struct images *imgs = &cnt->imgs;
struct coord *location = &img->location;
/* Draw location */
if (cnt->locate_motion_mode == LOCATE_ON) {
if (cnt->locate_motion_style == LOCATE_BOX) {
alg_draw_location(location, imgs, imgs->width, img->image, LOCATE_BOX,
LOCATE_BOTH, cnt->process_thisframe);
} else if (cnt->locate_motion_style == LOCATE_REDBOX) {
alg_draw_red_location(location, imgs, imgs->width, img->image, LOCATE_REDBOX,
LOCATE_BOTH, cnt->process_thisframe);
} else if (cnt->locate_motion_style == LOCATE_CROSS) {
alg_draw_location(location, imgs, imgs->width, img->image, LOCATE_CROSS,
LOCATE_BOTH, cnt->process_thisframe);
} else if (cnt->locate_motion_style == LOCATE_REDCROSS) {
alg_draw_red_location(location, imgs, imgs->width, img->image, LOCATE_REDCROSS,
LOCATE_BOTH, cnt->process_thisframe);
}
}
/* Calculate how centric motion is if configured preview center*/
if (cnt->new_img & NEWIMG_CENTER) {
unsigned int distX = abs((imgs->width / 2) - location->x);
unsigned int distY = abs((imgs->height / 2) - location->y);
img->cent_dist = distX * distX + distY * distY;
}
/* Do things only if we have got minimum_motion_frames */
if (img->flags & IMAGE_TRIGGER) {
/* Take action if this is a new event and we have a trigger image */
if (cnt->event_nr != cnt->prev_event) {
/*
* 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 = img->timestamp;
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, img->image, NULL, NULL, &img->timestamp_tm);
MOTION_LOG(NTC, TYPE_ALL, NO_ERRNO, "%s: Motion detected - starting event %d",
cnt->event_nr);
/* always save first motion frame as preview-shot, may be changed to an other one later */
if (cnt->new_img & (NEWIMG_FIRST | NEWIMG_BEST | NEWIMG_CENTER))
image_save_as_preview(cnt, img);
}
/* EVENT_MOTION triggers event_beep and on_motion_detected_command */
event(cnt, EVENT_MOTION, NULL, NULL, NULL, &img->timestamp_tm);
}
/* Limit framerate */
if (img->shot < conf->frame_limit) {
/*
* If config option stream_motion is enabled, send the latest motion detected image
* to the stream 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 stream.
* We also disable this in setup_mode.
*/
if (conf->stream_motion && !conf->setup_mode && img->shot != 1)
event(cnt, EVENT_STREAM, img->image, NULL, NULL, &img->timestamp_tm);
/*
* Save motion jpeg, if configured
* Output the image_out (motion) picture.
*/
if (conf->motion_img)
event(cnt, EVENT_IMAGEM_DETECTED, NULL, NULL, NULL, &img->timestamp_tm);
}
/* if track enabled and auto track on */
if (cnt->track.type && cnt->track.active)
cnt->moved = track_move(cnt, dev, location, imgs, 0);
}
/**
* process_image_ring
*
* Called from 'motion_loop' to save images / send images to movie
*
* Parameters:
*
* cnt - current thread's context struct
* max_images - Max number of images to process
* Set to IMAGE_BUFFER_FLUSH to send/save all images in buffer
*/
#define IMAGE_BUFFER_FLUSH ((unsigned int)-1)
static void process_image_ring(struct context *cnt, unsigned int max_images)
{
/*
* We are going to send an event, in the events there is still
* some code that use cnt->current_image
* so set it temporary to our image
*/
struct image_data *saved_current_image = cnt->current_image;
/* If image is flaged to be saved and not saved yet, process it */
do {
/* Check if we should save/send this image, breakout if not */
if ((cnt->imgs.image_ring[cnt->imgs.image_ring_out].flags & (IMAGE_SAVE | IMAGE_SAVED)) != IMAGE_SAVE)
break;
/* Set inte global cotext that we are working with this image */
cnt->current_image = &cnt->imgs.image_ring[cnt->imgs.image_ring_out];
if (cnt->imgs.image_ring[cnt->imgs.image_ring_out].shot < cnt->conf.frame_limit) {
if (cnt->log_level >= DBG) {
char tmp[32];
const char *t;
if (cnt->imgs.image_ring[cnt->imgs.image_ring_out].flags & IMAGE_TRIGGER)
t = "Trigger";
else if (cnt->imgs.image_ring[cnt->imgs.image_ring_out].flags & IMAGE_MOTION)
t = "Motion";
else if (cnt->imgs.image_ring[cnt->imgs.image_ring_out].flags & IMAGE_PRECAP)
t = "Precap";
else if (cnt->imgs.image_ring[cnt->imgs.image_ring_out].flags & IMAGE_POSTCAP)
t = "Postcap";
else
t = "Other";
mystrftime(cnt, tmp, sizeof(tmp), "%H%M%S-%q",
&cnt->imgs.image_ring[cnt->imgs.image_ring_out].timestamp_tm, NULL, 0);
draw_text(cnt->imgs.image_ring[cnt->imgs.image_ring_out].image, 10, 20,
cnt->imgs.width, tmp, cnt->conf.text_double);
draw_text(cnt->imgs.image_ring[cnt->imgs.image_ring_out].image, 10, 30,
cnt->imgs.width, t, cnt->conf.text_double);
}
/* Output the picture to jpegs and ffmpeg */
event(cnt, EVENT_IMAGE_DETECTED,
cnt->imgs.image_ring[cnt->imgs.image_ring_out].image, NULL, NULL,
&cnt->imgs.image_ring[cnt->imgs.image_ring_out].timestamp_tm);
/*
* Check if we must add any "filler" frames into movie to keep up fps
* Only if we are recording videos ( ffmpeg or extenal pipe )
*/
if ((cnt->imgs.image_ring[cnt->imgs.image_ring_out].shot == 0) &&
#ifdef HAVE_FFMPEG
(cnt->ffmpeg_output || (cnt->conf.useextpipe && cnt->extpipe))) {
#else
(cnt->conf.useextpipe && cnt->extpipe)) {
#endif
/*
* movie_last_shoot is -1 when file is created,
* we don't know how many frames there is in first sec
*/
if (cnt->movie_last_shot >= 0) {
if (cnt_list[0]->log_level >= DBG) {
int frames = cnt->movie_fps - (cnt->movie_last_shot + 1);
if (frames > 0) {
char tmp[15];
MOTION_LOG(DBG, TYPE_ALL, NO_ERRNO, "%s: Added %d fillerframes into movie",
frames);
sprintf(tmp, "Fillerframes %d", frames);
draw_text(cnt->imgs.image_ring[cnt->imgs.image_ring_out].image, 10, 40,
cnt->imgs.width, tmp, cnt->conf.text_double);
}
}
/* Check how many frames it was last sec */
while ((cnt->movie_last_shot + 1) < cnt->movie_fps) {
/* Add a filler frame into encoder */
event(cnt, EVENT_FFMPEG_PUT,
cnt->imgs.image_ring[cnt->imgs.image_ring_out].image, NULL, NULL,
&cnt->imgs.image_ring[cnt->imgs.image_ring_out].timestamp_tm);
cnt->movie_last_shot++;
}
}
cnt->movie_last_shot = 0;
} else if (cnt->imgs.image_ring[cnt->imgs.image_ring_out].shot != (cnt->movie_last_shot + 1)) {
/* We are out of sync! Propably we got motion - no motion - motion */
cnt->movie_last_shot = -1;
}
/*
* Save last shot added to movie
* only when we not are within first sec
*/
if (cnt->movie_last_shot >= 0)
cnt->movie_last_shot = cnt->imgs.image_ring[cnt->imgs.image_ring_out].shot;
}
/* Mark the image as saved */
cnt->imgs.image_ring[cnt->imgs.image_ring_out].flags |= IMAGE_SAVED;
/* Store it as a preview image, only if it have motion */
if (cnt->imgs.image_ring[cnt->imgs.image_ring_out].flags & IMAGE_MOTION) {
/* Check for most significant preview-shot when output_pictures=best */
if (cnt->new_img & NEWIMG_BEST) {
if (cnt->imgs.image_ring[cnt->imgs.image_ring_out].diffs > cnt->imgs.preview_image.diffs) {
image_save_as_preview(cnt, &cnt->imgs.image_ring[cnt->imgs.image_ring_out]);
}
}
/* Check for most significant preview-shot when output_pictures=center */
if (cnt->new_img & NEWIMG_CENTER) {
if (cnt->imgs.image_ring[cnt->imgs.image_ring_out].cent_dist < cnt->imgs.preview_image.cent_dist) {
image_save_as_preview(cnt, &cnt->imgs.image_ring[cnt->imgs.image_ring_out]);
}
}
}
/* Increment to image after last sended */
if (++cnt->imgs.image_ring_out >= cnt->imgs.image_ring_size)
cnt->imgs.image_ring_out = 0;
if (max_images != IMAGE_BUFFER_FLUSH) {
max_images--;
/* breakout if we have done max_images */
if (max_images == 0)
break;
}
/* loop until out and in is same e.g. buffer empty */
} while (cnt->imgs.image_ring_out != cnt->imgs.image_ring_in);
/* restore global context values */
cnt->current_image = saved_current_image;
}
/**
* 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: 0 OK
* -1 Fatal error, open loopback error
* -2 Fatal error, open SQL database error
* -3 Fatal error, image dimensions are not modulo 16
*/
static int motion_init(struct context *cnt)
{
FILE *picture;
/* Store thread number in TLS. */
pthread_setspecific(tls_key_threadnr, (void *)((unsigned long)cnt->threadnr));
cnt->currenttime_tm = mymalloc(sizeof(struct tm));
cnt->eventtime_tm = mymalloc(sizeof(struct tm));
/* Init frame time */
cnt->currenttime = time(NULL);
localtime_r(&cnt->currenttime, cnt->currenttime_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;
cnt->lightswitch_framecounter = 0;
cnt->detecting_motion = 0;
cnt->makemovie = 0;
MOTION_LOG(NTC, TYPE_ALL, NO_ERRNO, "%s: Thread %d started , motion detection %s",
(unsigned long)pthread_getspecific(tls_key_threadnr), cnt->pause ? "Disabled":"Enabled");
if (!cnt->conf.filepath)
cnt->conf.filepath = mystrdup(".");
/* set the device settings */
cnt->video_dev = vid_start(cnt);
/*
* We failed to get an initial image from a camera
* So we need to guess height and width based on the config
* file options.
*/
if (cnt->video_dev == -1) {
MOTION_LOG(WRN, TYPE_ALL, NO_ERRNO, "%s: Could not fetch initial image from camera "
"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;
} else if (cnt->video_dev == -2) {
MOTION_LOG(WRN, TYPE_ALL, NO_ERRNO, "%s: Could not fetch initial image from camera "
"Motion only supports width and height modulo 16");
return -3;
}
image_ring_resize(cnt, 1); /* Create a initial precapture ring buffer with 1 frame */
cnt->imgs.ref = mymalloc(cnt->imgs.size);
cnt->imgs.out = mymalloc(cnt->imgs.size);
memset(cnt->imgs.out, 0, cnt->imgs.size);
/* contains the moving objects of ref. frame */
cnt->imgs.ref_dyn = mymalloc(cnt->imgs.motionsize * sizeof(cnt->imgs.ref_dyn));
cnt->imgs.image_virgin = mymalloc(cnt->imgs.size);
cnt->imgs.smartmask = mymalloc(cnt->imgs.motionsize);
cnt->imgs.smartmask_final = mymalloc(cnt->imgs.motionsize);
cnt->imgs.smartmask_buffer = mymalloc(cnt->imgs.motionsize * sizeof(cnt->imgs.smartmask_buffer));
cnt->imgs.labels = mymalloc(cnt->imgs.motionsize * sizeof(cnt->imgs.labels));
cnt->imgs.labelsize = mymalloc((cnt->imgs.motionsize/2+1) * sizeof(cnt->imgs.labelsize));
/* Set output picture type */
if (!strcmp(cnt->conf.picture_type, "ppm"))
cnt->imgs.picture_type = IMAGE_TYPE_PPM;
else
cnt->imgs.picture_type = IMAGE_TYPE_JPEG;
/* allocate buffer here for preview buffer */
cnt->imgs.preview_image.image = mymalloc(cnt->imgs.size);
/*
* 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 */
/* Capture first image, or we will get an alarm on start */
if (cnt->video_dev > 0) {
int i;
for (i = 0; i < 5; i++) {
if (vid_next(cnt, cnt->imgs.image_virgin) == 0)
break;
SLEEP(2, 0);
}
if (i >= 5) {
memset(cnt->imgs.image_virgin, 0x80, cnt->imgs.size); /* initialize to grey */
draw_text(cnt->imgs.image_virgin, 10, 20, cnt->imgs.width,
"Error capturing first image", cnt->conf.text_double);
MOTION_LOG(ERR, TYPE_ALL, NO_ERRNO, "%s: Error capturing first image");
}
}
/* create a reference frame */
alg_update_reference_frame(cnt, RESET_REF_FRAME);
#if defined(HAVE_LINUX_VIDEODEV_H) && !defined(WITHOUT_V4L) && !defined(BSD)
/* open video loopback devices if enabled */
if (cnt->conf.vidpipe) {
MOTION_LOG(NTC, TYPE_ALL, NO_ERRNO, "%s: 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(ERR, TYPE_ALL, NO_ERRNO, "%s: Failed to open video loopback for normal pictures");
return -1;
}
}
if (cnt->conf.motionvidpipe) {
MOTION_LOG(NTC, TYPE_ALL, NO_ERRNO, "%s: 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(ERR, TYPE_ALL, NO_ERRNO, "%s: Failed to open video loopback for motion pictures");
return -1;
}
}
#endif /* !WITHOUT_V4L && !BSD */
#if defined(HAVE_MYSQL) || defined(HAVE_PGSQL) || defined(HAVE_SQLITE3)
if (cnt->conf.database_type) {
MOTION_LOG(NTC, TYPE_DB, NO_ERRNO, "%s: Database backend %s",
cnt->conf.database_type);
#ifdef HAVE_SQLITE3
if ((!strcmp(cnt->conf.database_type, "sqlite3")) && cnt->conf.sqlite3_db) {
MOTION_LOG(NTC, TYPE_DB, NO_ERRNO, "%s: DB %s",
cnt->conf.sqlite3_db);
if (sqlite3_open(cnt->conf.sqlite3_db, &cnt->database_sqlite3) != SQLITE_OK) {
MOTION_LOG(ERR, TYPE_DB, NO_ERRNO, "%s: Can't open database %s : %s\n",
cnt->conf.sqlite3_db, sqlite3_errmsg(cnt->database_sqlite3));
sqlite3_close(cnt->database_sqlite3);
exit(1);
}
}
#endif /* HAVE_SQLITE3 */
#ifdef HAVE_MYSQL
if ((!strcmp(cnt->conf.database_type, "mysql")) && (cnt->conf.database_dbname)) {
// close database to be sure that we are not leaking
mysql_close(cnt->database);
cnt->database = (MYSQL *) mymalloc(sizeof(MYSQL));
mysql_init(cnt->database);
if (!mysql_real_connect(cnt->database, cnt->conf.database_host, cnt->conf.database_user,
cnt->conf.database_password, cnt->conf.database_dbname, 0, NULL, 0)) {
MOTION_LOG(ERR, TYPE_DB, NO_ERRNO, "%s: Cannot connect to MySQL database %s on host %s with user %s",
cnt->conf.database_dbname, cnt->conf.database_host,
cnt->conf.database_user);
MOTION_LOG(ERR, TYPE_DB, NO_ERRNO, "%s: MySQL error was %s", mysql_error(cnt->database));
return -2;
}
#if (defined(MYSQL_VERSION_ID)) && (MYSQL_VERSION_ID > 50012)
my_bool my_true = TRUE;
mysql_options(cnt->database, MYSQL_OPT_RECONNECT, &my_true);
#endif
}
#endif /* HAVE_MYSQL */
#ifdef HAVE_PGSQL
if ((!strcmp(cnt->conf.database_type, "postgresql")) && (cnt->conf.database_dbname)) {
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.database_dbname, /* dbname */
(cnt->conf.database_host ? cnt->conf.database_host : ""), /* host (may be blank) */
(cnt->conf.database_user ? cnt->conf.database_user : ""), /* user (may be blank) */
(cnt->conf.database_password ? cnt->conf.database_password : ""), /* password (may be blank) */
cnt->conf.database_port
);
cnt->database_pg = PQconnectdb(connstring);
if (PQstatus(cnt->database_pg) == CONNECTION_BAD) {
MOTION_LOG(ERR, TYPE_DB, NO_ERRNO, "%s: Connection to PostgreSQL database '%s' failed: %s",
cnt->conf.database_dbname, PQerrorMessage(cnt->database_pg));
return -2;
}
}
#endif /* 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_movie * (FTYPE_MPEG + FTYPE_MPEG_MOTION) +
cnt->conf.sql_log_timelapse * FTYPE_MPEG_TIMELAPSE;
}
#endif /* defined(HAVE_MYSQL) || defined(HAVE_PGSQL) || defined(HAVE_SQLITE3) */
/* Load the mask file if any */
if (cnt->conf.mask_file) {
if ((picture = myfopen(cnt->conf.mask_file, "r", 0))) {
/*
* 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);
myfclose(picture);
} else {
MOTION_LOG(ERR, TYPE_ALL, SHOW_ERRNO, "%s: 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(ERR, TYPE_ALL, NO_ERRNO, "%s: Failed to read mask image. Mask feature disabled.");
} else {
MOTION_LOG(INF, TYPE_ALL, NO_ERRNO, "%s: 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(cnt->imgs.smartmask_buffer));
/* Set noise level */
cnt->noise = cnt->conf.noise;
/* Set threshold value */
cnt->threshold = cnt->conf.max_changes;
/* Initialize stream server if stream port is specified to not 0 */
if (cnt->conf.stream_port) {
if (stream_init(cnt) == -1) {
MOTION_LOG(ERR, TYPE_ALL, SHOW_ERRNO, "%s: Problem enabling motion-stream server in port %d",
cnt->conf.stream_port);
cnt->finish = 1;
} else {
MOTION_LOG(NTC, TYPE_ALL, NO_ERRNO, "%s: Started motion-stream server in port %d auth %s",
cnt->conf.stream_port, cnt->conf.stream_auth_method ? "Enabled":"Disabled");
}
}
/* Prevent first few frames from triggering motion... */
cnt->moved = 8;
/* 2 sec startup delay so FPS is calculated correct */
cnt->startup_frames = cnt->conf.frame_limit * 2;
return 0;
}
/**
* motion_cleanup
*
* This routine is called from motion_loop when thread ends to
* cleanup all memory etc. that motion_init did.
*
* Parameters:
*
* cnt Pointer to the motion context structure
*
* Returns: nothing
*/
static void motion_cleanup(struct context *cnt)
{
/* Stop stream */
event(cnt, EVENT_STOP, NULL, NULL, NULL, NULL);
if (cnt->video_dev >= 0) {
MOTION_LOG(INF, TYPE_ALL, NO_ERRNO, "%s: Calling vid_close() from motion_cleanup");
vid_close(cnt);
}
if (cnt->imgs.out) {
free(cnt->imgs.out);
cnt->imgs.out = NULL;
}
if (cnt->imgs.ref) {
free(cnt->imgs.ref);
cnt->imgs.ref = NULL;
}
if (cnt->imgs.ref_dyn) {
free(cnt->imgs.ref_dyn);
cnt->imgs.ref_dyn = NULL;
}
if (cnt->imgs.image_virgin) {
free(cnt->imgs.image_virgin);
cnt->imgs.image_virgin = NULL;
}
if (cnt->imgs.labels) {
free(cnt->imgs.labels);
cnt->imgs.labels = NULL;
}
if (cnt->imgs.labelsize) {
free(cnt->imgs.labelsize);
cnt->imgs.labelsize = NULL;
}
if (cnt->imgs.smartmask) {