~audio-recorder/audio-recorder/trunk

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
/*
 * Copyright (c) Linux community.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
*/
#include <string.h>
#include <glib.h>
#include <math.h>
#include "timer.h"

#include "utility.h"
#include "support.h"
#include "dconf.h"
#include "log.h"
#include "gst-vad.h"
#include "audio-sources.h"
#include "rec-manager.h"

/*
  Sample commands:

  Clock time:

  start at 09:30 pm
  start at 21:30
  start at 21:30:00

  -- During runtime:
       * Compare clock time to given timer value (clock time hh:mm:ss).
       * Start recorder (pipeline) if condition is TRUE.
       * User must stop recording manually (or by other command).
  -----------------------------------------------------

  Clock time or duration of recording:

  stop at 11:30 am
  stop after 1h 20m
  stop after 1 hour 20 min
  pause after 20 min

  -- During runtime:
       * Compare clock time to the given timer value.
       * Compare duration to the given timer limit.
       * Stop or pause recorder (pipeline) if condition is TRUE.
  -----------------------------------------------------

  Managing "silence".

  stop if silence
  stop if silence 5s
  stop if silence 5s 0.4
  stop if silence 5s 40%

  -- During runtime:
       * Make sure VAD is running.
       * Send threshold signals to this module (timer.c)
       * Recorder will stop if threshold < limit.
  ------------------------------------------------------

  pause if silence 5s 0.3
  pause if silence 5s 30%
  pause if silence 5s -24dB
  pause if silence

  -- During runtime:
       * Make sure VAD is running.
       * Send threshold signals to this module (timer.c)
       * Recorder will PAUSE if threshold < limit, and PLAY if threshold >= limit.
  ---------------------------------------------------------

  Using "sound", "voice" and "audio" commands.

  start if sound
  start if sound 0.3
  start if voice 30%
  start if voice 0.3
  start if audio -20dB

  NOTICE: Unfortunately these commands cannot handle time delay very well!

  These commands fire immediately after the volume exceeds/or is beneath the given limit (default limit is 0.3, or 30%).

  -- During runtime:
       * Make sure VAD is running.
       * Send threshold signals to gst-recorder.c.
       * Recorder will START if threshold >= limit, and PAUSE if threshold < limit.
  ---------------------------------------------------------    

  File size:

  stop after 10MB
  pause if 2MB

  -- During runtime:
       * Take recorded file size and compare it to value in the timer command (in timer.c).
       * Start recorder (pipeline) if condition is TRUE.
  ---------------------------------------------------------    

  stop after 2 GB | 12 pm | silence 4s
  start at 10:20 pm | voice 

  Multiple conditions on one line, separated by "|" or "or".
  ---------------------------------------------------------    

  Notice: The words "voice", "audio" and "sound" have all *same meaning*. Ok!

  The word "silence" is relative to the given volume level/threshold. 
  Silence has both duration (in seconds) and volume limit.

  Volume limit can be given as:
  -Decimal value between [0, 1.0].
  -% value between [0%, 100%]. So 1.0 = 100%.
  -Or decibel value.
  
*/

// Timer function call frequency in seconds
#define TIMER_CALL_FREQ 1

// Default silence duration (in seconds)
#define DEF_SILENCE_DURATION 3

// Timer function id
static guint g_timer_func_id = 0;

// A GList of TimerRec nodes from the timer-parser.c
G_LOCK_DEFINE_STATIC(g_t_list);
static GList *g_t_list = NULL;

// Timer's start time
static struct tm g_timer_start_time;

void timer_func_stop();
gboolean timer_func_cb(gpointer user_data);
void timer_func_exit_cb(gpointer user_data);

void timer_func_exec_command(TimerRec *tr);

static void timer_set_start_time();
static struct tm timer_get_start_time();
static void timer_update_records_1();

static gchar timer_test_filesize(TimerRec *tr);
static gchar timer_test_clock_time(TimerRec *tr);
static gchar timer_test_time_duration(TimerRec *tr);

static void test_silence(TimerRec *tr, GstClockTimeDiff time_diff, gdouble rms);
static void test_sound(TimerRec *tr, GstClockTimeDiff time_diff, gdouble rms);
static void execute_action(TimerRec *tr, gchar action);

void timer_module_init() {
    LOG_DEBUG("Init timer.c.\n");

    // Init gst-vad.c
    vad_module_init();

    g_timer_func_id = 0;

    // Init parser module
    parser_module_init();

    // Start the timer function
    timer_func_start();
}

void timer_module_exit() {
    LOG_DEBUG("Clean up timer.c.\n");

    // Stop timer function
    timer_func_stop();

    // Clean up parser module
    parser_module_exit();

    // Clean up gst-vad.c
    vad_module_exit();

    g_t_list = NULL;
}

void timer_set_debug_flag(gboolean on_off) {
    // Set debug flag. Please see application options:
    // $ audio-recorder --help
    vad_set_debug_flag(on_off);
}

void timer_module_reset(gint for_state) {
    // Reset timer before we move to the given state

    switch (for_state) {
    case GST_STATE_PLAYING:
        timer_update_records_1();
        break;

    case GST_STATE_PAUSED:
    case GST_STATE_NULL:
        //timer_update_records_2();
        break;

    default:
        ;
    }
}

void timer_module_rec_start() {
    // Called when recording stops.

    // Reset timer
    timer_update_records_1();
}

// --------------------------------------------------
// The actual timer function
// --------------------------------------------------

void timer_func_start() {
    // Already running?
    if (g_timer_func_id > 0) {
        return;
    }

    // Start the timer function
    g_timer_func_id = g_timeout_add_seconds_full(G_PRIORITY_DEFAULT, TIMER_CALL_FREQ, (GSourceFunc)timer_func_cb, 
                                                 (gpointer)1/*!= 0*/, (GDestroyNotify)timer_func_exit_cb);
}

void timer_func_stop() {
    // Stop the timer funcion
    if (g_timer_func_id > 0) {
        g_source_remove(g_timer_func_id);
    }
    g_timer_func_id = 0;
}

void timer_func_exit_cb(gpointer user_data) {
    // Nothing to cleanup
    ;
}

void timer_settings_changed() {
    // Increment the counter so various modules know that the timer-settings have been altered
    gint count = 0;
    conf_get_int_value("timer-setting-counter", &count);
    conf_save_int_value("timer-setting-counter", count+1);
}

static void timer_update_records_1() {
    // Reset timer nodes
    G_LOCK(g_t_list);

    GList *item = g_list_first(g_t_list);
    while (item) {
        TimerRec *tr = (TimerRec*)item->data;

        // Start to count from 0
        tr->time_below = 0.0;
        tr->time_above = 0.0;

        // Next item
        item = g_list_next(item);
    }

    G_UNLOCK(g_t_list);
}

#if 0 
static void timer_update_records_2() {
    // Reset timer nodes

    G_LOCK(g_t_list);

    GList *item = g_list_first(g_t_list);
    while (item) {
        //TimerRec *tr = (TimerRec*)item->data;

        // Start to count from 0
        //tr->seconds = 0;
        //tr->seconds_x = 0;

        // Next item
        item = g_list_next(item);
    }
    G_UNLOCK(g_t_list);
}
#endif

static void timer_clear_list() {
    // Reset the timer list

    // Lock g_timer_list
    G_LOCK(g_t_list);

    parser_free_list();
    g_t_list = NULL;

    // Unlock
    G_UNLOCK(g_t_list);
}

static void timer_set_start_time() {
    // Set timer's start time
    time_t t = time(NULL);
    localtime_r(&t, &g_timer_start_time);
}

static struct tm timer_get_start_time() {
    return g_timer_start_time;
}

gdouble normalize_threshold(gdouble threshold, gchar *threshold_unit) {
    gdouble val = threshold;
    if (!threshold_unit) return val;

    // dB?
    if (threshold_unit[0] == 'd')  {
        // rms_dB:
        // RMS, http://en.wikipedia.org/wiki/Root_mean_square
        // From dB to a normalized 0 - 1.0 value.
        val = pow(10, threshold / 20);
    }
    // [0 - 100]% ?
    else if (threshold_unit[0] == '%')  {
        val = val / 100.0;

    // Already in [0 - 1.0]
    } else {
        // val = threshold;
    }

    return val;
}

gboolean check_need_VAD() {
    GList *item = g_list_first(g_t_list);
    while (item) {
        TimerRec *tr = (TimerRec*)item->data;

        if (!g_strcmp0(tr->label, "silence") ||
            !g_strcmp0(tr->label, "voice") ||
            !g_strcmp0(tr->label, "sound") ||
            !g_strcmp0(tr->label, "audio")) {

            return TRUE;
        }

        // Next item
        item = g_list_next(item);
    }
    return FALSE;
}

void normalize_values() {
    GList *item = g_list_first(g_t_list);
    while (item) {
        TimerRec *tr = (TimerRec*)item->data;

        // Convert hh:mm:ss to seconds
        tr->norm_secs = (gdouble)(tr->val[0]*3600 + tr->val[1]*60 + tr->val[2]);

        // Convert tr->threshold to [0 - 1.0] from tr->threshold_unit
        tr->norm_threshold = normalize_threshold(tr->threshold, tr->threshold_unit);

        // Next item
        item = g_list_next(item);
    }
}

gboolean timer_func_cb(gpointer user_data) {
    // The actual timer function

    // Timer is ON/OFF?
    static gboolean timer_active = FALSE;

    // Counter to detect if GConf settings have been altered
    static gint setting_counter = -1;

    // Do we need VAD-pipeline?
    static gboolean need_VAD = FALSE;

    // Timer (GConf) settings changed?
    gint val = 0;
    conf_get_int_value("timer-setting-counter", &val);

    if (val == setting_counter) {
        // No changes in parameters.
        // Evaluate timer values.
        goto EVAL_0;
    }

    // Save settings counter
    setting_counter = val;

    // Get new values from GConf and parse values
    conf_get_boolean_value("timer-active", &timer_active);

    LOG_TIMER("Timer settings changed:<%s>\n", (timer_active ? "timer ON" : "timer OFF"));

    // Timer is ON/OFF?
    if (!timer_active) {
        // It's OFF

        timer_clear_list();

        // Stop the listener
        vad_stop_VAD();

        goto LBL_1;
    }
    
    // Set timer's start time
    timer_set_start_time();

    // Free the old g_t_list
    timer_clear_list();

    // Set lock
    G_LOCK(g_t_list);

    // Get timer text
    gchar *timer_text = NULL;
    conf_get_string_value("timer-text", &timer_text);

    LOG_TIMER("----------------\nTimer text is:\n<%s>\n--------------\n", timer_text);

    // Parse timer conditions.
    // This will return pointer to the g_timer_list (GList) in timer-parser.c.
    g_t_list = parser_parse_actions(timer_text);

    g_free(timer_text);

    if (g_list_length(g_t_list) < 1) {
        LOG_TIMER("The timer has no conditions.\n");

    } else {
        LOG_TIMER("The timer conditions are:\n");

#if defined(DEBUG_TIMER)
        // Debug print the command list
        parser_print_list(g_t_list);
#endif
    }

    // Important: Start VAD-pipeline only when we needed.
    // Only "silence", "voice", "audio" and "sound" commands/conditions need VAD (Voice Activity Detection).
    need_VAD = check_need_VAD();
    
    // Check if recorder was started with --debug-signal (or -d) argument
    need_VAD = need_VAD || vad_get_debug_flag();

    // Normalize values
    normalize_values();

    G_UNLOCK(g_t_list);

  EVAL_0:

    // Timer is ON?
    if (!timer_active) {
        // No.
        // Make sure the VAD has stopped (do not waste CPU cycles)
        vad_stop_VAD();
        goto LBL_1;
    }

    // Yes. Timer is ON.

    // Do we need data from gst-vad.c?
    if (!need_VAD) {
        // No.
        // Make sure the VAD has stopped (do not waste CPU cycles)
        vad_stop_VAD();

    } else {
        // Yes.
        // Start VAD.
        vad_start_VAD();
    }

    // ------------------------
    // Evaluate timer commands
    // ------------------------

    // For all TimerRec structures in GList...
    GList *item = g_list_first(g_t_list);
    while (item) {
        TimerRec *tr = (TimerRec*)item->data;

        // Set lock
        G_LOCK(g_t_list);

        // Check the timer condition
        timer_func_exec_command(tr);

        // Unlock
        G_UNLOCK(g_t_list);

        // Next item
        item = g_list_next(item);
    }

LBL_1:
    // Continue calling this function
    return TRUE;
}

void timer_func_exec_command(TimerRec *tr) {

    // Actions: 'S'=start, 'T'=stop, 'P'=pause, 'p'=pause, 'c'=continue, 0=No action.
    gchar action = 0;

    // Test filesize?
    if (tr->data_type == 'f') {
        // stop/pause if ### bytes/KB/MB/GB/TB
        // Example:
        // stop/pause if 250 MB

        action = timer_test_filesize(tr);

        if (action) {
            LOG_TIMER("Filesize test = TRUE.\n");
        }

        // Test clock time ##:##:##?
    } else if (tr->data_type == 't') {
        // start/stop/pause at ##:##:## am/pm (where ##:##:## is a clock time in hh:mm:ss format)
        // Example:
        // start/stop/pause at 10:15:00 pm

        action = timer_test_clock_time(tr);

        if (action) {
            LOG_TIMER("Clock time test = TRUE.\n");
        }

        // Test time duration?
    } else if (tr->data_type == 'd') {
        // start/stop/pause after # hour # min # seconds
        // Example:
        // start/stop/pause after 1 h 25 min

        action = timer_test_time_duration(tr);

        if (action) {
            LOG_TIMER("Test for time period/duration = TRUE.\n");
        }
    }

    execute_action(tr, action);
}

static gchar timer_test_filesize(TimerRec *tr) {
    // Test filesize.
    // stop/pause if/after/on ### bytes/KB/MB/GB/TB
    // Examples:
    //  stop after 250 MB
    //  pause if 1.2 GB

    gchar action = 0;

    // Get output filename
    gchar *filename = rec_manager_get_output_filename();

    if (!filename) {
        return action;
    }

    // Get file size
    gdouble filesize = 1.0 * get_file_size(filename);

    LOG_TIMER("Testing filesize: filesize=%3.1f bytes, unit=%s, current filesize=%3.1f bytes, filename=<%s>\n",
              tr->val[0], tr->label, filesize, filename);

    g_free(filename);

    // Filesize limit exceeded?
    if (filesize >= tr->val[0]) {
        // Execute
        action = tr->action;
    }

    return action;
}

static gchar timer_test_clock_time(TimerRec *tr) {
    // Test clock time.
    // start/stop/pause at ##:##:## am/pm (where ##:##:## is a clock time in hh:mm:ss format)
    // Examples:
    //  start at 10:15:00 pm
    //  pause at 9:30 am
    //  stop at 23:00

    gchar action = 0;

    // Get current, local date & time
    time_t t = time(NULL);
    struct tm *tmp;
    tmp = localtime(&t);

    gint64 clock_secs = tmp->tm_hour*3600 + tmp->tm_min*60 + tmp->tm_sec;

    gint64 timer_secs = tr->val[0]*3600 +  tr->val[1]*60 +  tr->val[2];

    LOG_TIMER("Test clock time: current time is %02d:%02d:%02d  timer setting is %02.0f:%02.0f:%02.0f (day_of_year:%d/%d) diff in seconds:%ld\n", 
     tmp->tm_hour, tmp->tm_min, tmp->tm_sec, tr->val[0], tr->val[1], tr->val[2], tmp->tm_yday, 
     tr->day_of_year, (long)(timer_secs - clock_secs));

    // Note:
    // Do NOT fire if current clock time is 60 minutes or more over the trigger value.
    // Eg. Do not fire if clock time is 14:00:00, and timer setting is 12:10:00 pm. 
    // We will assume here that the user means 12:10pm tomorrow, not today.

    gint64 diff_secs = (clock_secs - timer_secs);

    gboolean do_action = (diff_secs > 0 && diff_secs < (60 * 60)/*1 HOUR HARD-CODED*/);

    if (do_action && tr->day_of_year != tmp->tm_yday) {

        action = tr->action;

        // Save day_of_year so we know when the clock turns around (to the next day).
        // This timer command will become valid and fire again.
        tr->day_of_year = tmp->tm_yday;
    }

    return action;
}

static gchar timer_test_time_duration(TimerRec *tr) {
    // Test time duration/time period.
    // start/stop/pause after # hour/h # minuntes/m/min # seconds/s/sec
    // Examples:
    //  start after 1 h 25 min
    //  stop after 30 minutes
    //  pause after 1 h 15 m 20 s

    gchar action = 0;

    // Action is 'T' (sTop) or 'P' (Pause) recording?
    if (tr->action == 'T'  || tr->action == 'P') {
        // Eg. stop/pause after 8 min 20 sec

        // Compare recording's stream time to the given timer value.

        // Get actual recording time in seconds
        gint64 recording_time_secs = rec_manager_get_stream_time();

        // This TimeRec's value in seconds
        gint64 timer_secs = tr->val[0]*3600.0 + tr->val[1]*60.0 +  tr->val[2];

#if defined(DEBUG_TIMER) || defined(DEBUG_ALL)
        guint hh = -1;
        guint mm = -1;
        guint ss = -1;
        // Split value to hours, minutes and seconds
        seconds_to_h_m_s(recording_time_secs, &hh, &mm, &ss);

        gint64 diff = timer_secs - recording_time_secs;

        LOG_TIMER("Test time period (for sTop and Pause): current rec.time:%02d:%02d:%02d  timer setting:%02.0f:%02.0f:%02.0f  diff:%ld secs.\n", 
                  hh, mm, ss, tr->val[0], tr->val[1], tr->val[2], (long)diff);

#endif

        if (recording_time_secs >= timer_secs) {
            // Execute
            action = tr->action;
        }

        // Action is 'S' (Start) recording?
        // Eg. start after 1 min 20 sec (execute "start after..." command only once during timer's life time)
    } else {

        // Execute only once pr. timer's life time!
        if (tr->done) goto LBL_1;

        // Get start time for this timer (when lines were parsed)
        struct tm start_time = timer_get_start_time();
        gint64 start_time_secs = start_time.tm_hour*3600.0 + start_time.tm_min*60.0 + start_time.tm_sec;

        // Get current, local date & time
        time_t t = time(NULL);
        struct tm *tmp;
        tmp = localtime(&t);
        gint64 curr_time_secs = tmp->tm_hour*3600.0 + tmp->tm_min*60.0 + tmp->tm_sec;

        // This TimerRec's value in seconds
        gint64 timer_secs = tr->val[0]*3600.0 + tr->val[1]*60.0 +  tr->val[2];

        gint64 diff = timer_secs - (curr_time_secs - start_time_secs);
        (void) diff; // Avoid unused var message


        LOG_TIMER("Test time period (for Start): clock time:%02d:%02d:%02d timer thread started:%02d:%02d:%02d setting:%02.0f:%02.0f:%02.0f  diff:%ld secs.\n",
          tmp->tm_hour, tmp->tm_min, tmp->tm_sec, start_time.tm_hour, start_time.tm_min, start_time.tm_sec,
          tr->val[0], tr->val[1], tr->val[2], (long)diff);

        if ((curr_time_secs - start_time_secs) >= timer_secs ) {
            // Execute command
            action = tr->action;
        }

LBL_1:
        ;
    }

    return action;
}

void timer_evaluate_triggers(GstClockTimeDiff time_diff, gdouble rms) {
    // This is called from gst-vad.c.
    // Evaluate VAD related timer commands.
    G_LOCK(g_t_list);

    GList *item = g_list_first(g_t_list);
    while (item) {
        TimerRec *tr = (TimerRec*)item->data;

        if (!g_strcmp0(tr->label, "silence")) {

            test_silence(tr, time_diff, rms);

        } else if (!g_strcmp0(tr->label, "voice") ||
                   !g_strcmp0(tr->label, "sound") ||
                   !g_strcmp0(tr->label, "audio")) {

            test_sound(tr, time_diff, rms);
        }

        // Next item
        item = g_list_next(item);
    }

    G_UNLOCK(g_t_list);
}

static void test_silence(TimerRec *tr, GstClockTimeDiff time_diff, gdouble rms) {
    // stop if silence
    // stop if silence 5s
    // stop if silence 5s 0.4
    // stop if silence 5s 40%

    // pause if silence
    // pause if silence 5s 0.3
    // pause if silence 5s 30%
    // pause if silence 5s -24dB
    gchar action = '\0';

    gdouble seconds = tr->norm_secs;

#if defined(DEBUG_TIMER) || defined(DEBUG_ALL)
    // Get recording state (for debugging)
    gint state = -1;
    gint pending = -1;
    rec_manager_get_state(&state, &pending);

    // Name of state
    const gchar *state_name = rec_manager_get_state_name(state);

    LOG_TIMER("Silence test. timer value:%3.1f sec, count seconds:%3.1f sec, *RMS:%3.2f, threshold:%3.1f%s (%3.2f), state:%s\n",
        seconds, tr->time_below, rms, tr->threshold, (tr->threshold_unit ? tr->threshold_unit : ""), tr->norm_threshold, state_name);
#endif

    // RMS > tr->threshold?
    if (rms > tr->norm_threshold + 0.001) { // 0.001=noise
        // Reset time teller
        tr->time_below = 0.0;

        if (tr->action == 'P') { // Pause
            // Resume (continue) recording after pause
            action = 'c'; 
            goto LBL_1;
        }
        return;
    }

    // Add time_diff to tr->time_below, convert to seconds
    tr->time_below += ((gdouble)time_diff / GST_SECOND);

    // tr->time_below < seconds?
    if (tr->time_below < seconds) {
        // Wait more
        return;
    }

    // Avoid overflow (no reason to keep this growing)
    if (tr->time_below > seconds + 140000) {
        tr->time_below = seconds + 140000;
    }

    // If here: RMS has been <= tr->threshold in seconds time.
    // Execute timer command.

    if (tr->action == 'T') { // sTop
        // stop if silence
        // stop if silence 0.3 4s
        action = 'T';

    } else if (tr->action == 'P') { // Pause
        // pause if silence 3s 0.2
        action = 'P';
    }

    LOG_TIMER("Condition %3.2f <= %3.2f (%3.2f%s) is TRUE in %3.1f seconds time. Execute command:%s.\n",
              rms, tr->norm_threshold, tr->threshold, (tr->threshold_unit ? tr->threshold_unit : ""),
              seconds, parser_get_action_name(action));

  LBL_1:
    // Exceute action 
    execute_action(tr, action);
}

static void test_sound(TimerRec *tr, GstClockTimeDiff time_diff, gdouble rms) {
    // start if sound
    // start if sound 0.3
    // start if voice 30%
    // start if voice 0.3
    // start if audio -20dB
    gchar action = '\0';

    gdouble seconds = tr->norm_secs;

    gint state = -1;
    gint pending = -1;
    rec_manager_get_state(&state, &pending);

#if defined(DEBUG_TIMER) || defined(DEBUG_ALL)
    // Name of state
    const gchar *state_name = rec_manager_get_state_name(state);

    LOG_TIMER("Sound/Voice/Audio test. timer value:%3.1f sec, count seconds:%3.1f sec, *RMS:%3.2f, threshold:%3.1f%s (%3.2f), state:%s\n",
        seconds, tr->time_above, rms, tr->threshold, (tr->threshold_unit ? tr->threshold_unit : ""), tr->norm_threshold, state_name);
#endif

    // rms over threshold?
    if (rms > tr->norm_threshold + 0.001) { // 0.001=noise

        // Paused temporarily?
        if (state == GST_STATE_PAUSED) {
            // Resume/continue recording immediately
            action = 'c';
            tr->time_above = 0.0;
            tr->time_below = 0.0;
            goto LBL_1;
        }
        
        // Add time_diff to tr->time_above, convert to seconds
        tr->time_above += ((gdouble)time_diff / GST_SECOND);

        // tr->time_above < seconds?
        if (tr->time_above < seconds) {
            // Wait more
            return;
        }

        // Avoid overflow (no reason to keep this growing)
        if (tr->time_above > seconds + 140000) {
            tr->time_above = seconds + 140000;
        }

        tr->time_below = 0.0;

        // If here: RMS has been > tr->threshold in seconds time.
        // Execute timer command.
        action = tr->action;

        LOG_TIMER("Condition %3.2f > %3.2f (%3.2f%s) is TRUE in %3.1f seconds time. Execute command:%s.\n",
                  rms, tr->norm_threshold, tr->threshold, (tr->threshold_unit ? tr->threshold_unit : ""),
                  seconds, parser_get_action_name(action));

        goto LBL_1;
    }

    // Here: rms < tr->norm_threshold.

    // Count seconds to pause
    tr->time_below += ((gdouble)time_diff / GST_SECOND);

    if (tr->time_below < 4.0) {
        // Wait more
        return;
    }

    // Pause recording temporarily
    action = 'p';
    tr->time_above = 0.0;
    tr->time_below = 0.0;

  LBL_1:
    // Excecute action 
    execute_action(tr, action);

}

void execute_action(TimerRec *tr, gchar action) {
    // Execute timer command

    // Get recording state (do not stress the command queue unnecessarily)
    gint state = -1;
    gint pending = -1;
    rec_manager_get_state(&state, &pending);

    switch (action) {
    case 'S': // Start recording
        tr->done = TRUE;
        if (state != GST_STATE_PLAYING)
            rec_manager_start_recording();
        break;

    case 'T': // Stop recording
        tr->done = TRUE;
        if (state != GST_STATE_NULL)
            rec_manager_stop_recording();
        break;

    case 'P': // Pause recording
        tr->done = TRUE;
        if (state == GST_STATE_PLAYING)
            rec_manager_pause_recording();
        break;

    case 'p': // Pause recording
        tr->done = TRUE;
        if (state == GST_STATE_PLAYING)
            rec_manager_pause_recording();
        break;

    case 'c': // Continue/resume (if was paused). Does not restart if recording is off.
        if (state != GST_STATE_PLAYING)
            rec_manager_continue_recording();
        break;

    case 0: // Do nothing
        break;

    default:
        LOG_ERROR("Unknown timer action <%c>.\n", action);
    }
}