~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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
/*
 * Copyright (c) 2002 Iain Holmes.
 * Copyright (c) 2011- Osmo Antero.
 *
 * 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 3 of the License (GPL3), or 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 3 for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License 3 along with this program; if not, see /usr/share/common-licenses/GPL file
 * or <http://www.gnu.org/licenses/>.
*/
#include <math.h>
#include "gst-recorder.h"
#include "rec-manager.h"
#include "media-profiles.h"
#include "log.h"
#include "support.h"
#include "dconf.h"
#include "utility.h"
#include "audio-sources.h"

#include "timer.h"

#include "gst-pipeline.h"

#include <gst/pbutils/missing-plugins.h>

#define AUDIO_RECORDER 101
#define AUDIO_RECORDER_ERR1 -1

// GStreamer pipeline
static GstElement *g_pipeline = NULL;

static gboolean rec_level_message_cb(GstBus *bus, GstMessage *message, void *user_data);

GstElement *rec_create_pipeline(PipelineParms *parms, GError **error);

void rec_set_state_to_null();

static gchar *rec_create_filename(gchar *track_title, gchar *artist, gchar *album);

//static gchar *rec_generate_datetime_filename();
static gchar *check_audio_folder(gchar *audio_folder);
static gchar *rec_get_profile_id();

void rec_module_init() {
    LOG_DEBUG("Init gst-recorder.c.\n");

    g_pipeline = NULL;
}

void rec_module_exit() {
    LOG_DEBUG("Clean up gst-recorder.c.\n");

    // Stop evt. recording
    rec_stop_recording(FALSE);
}

void rec_set_state_to_null() {
    // Copyright notice:
    // I have copied this function from gnome-media-2.30.0/grecord.

    LOG_DEBUG("\n--------- rec_set_state_to_null() ----------\n");

    // Set state of pipeline to GST_STATE_NULL.
    GstMessage *msg;
    GstState cur_state, pending;
    GstBus *bus;

    if (!GST_IS_PIPELINE(g_pipeline)) return;

    gst_element_get_state(g_pipeline, &cur_state, &pending, 0);

    if (cur_state == GST_STATE_NULL && pending == GST_STATE_VOID_PENDING)
        return;

    if (cur_state == GST_STATE_NULL && pending != GST_STATE_VOID_PENDING) {
        gst_element_set_state (g_pipeline, GST_STATE_NULL);
        return;
    }

    gst_element_set_state(g_pipeline, GST_STATE_READY);
    gst_element_get_state(g_pipeline, NULL, NULL, -1);

    bus = gst_element_get_bus(g_pipeline);
    if (GST_IS_BUS(bus)) {
        while ((msg = gst_bus_pop(bus))) {
            gst_bus_async_signal_func(bus, msg, NULL);

            if (msg) {
                gst_message_unref(msg);
            }
        }
        gst_object_unref(bus);
    }

    gst_element_set_state(g_pipeline, GST_STATE_NULL);
}

void rec_pause_recording()  {
    // Valid pipeline?
    if (!GST_IS_PIPELINE(g_pipeline)) return;

    // Get recording state
    gint state = -1;
    gint pending = -1;
    rec_get_state(&state, &pending);

    // Already paused?
    if (state == GST_STATE_PAUSED) return;

    LOG_DEBUG("\n--------- rec_pause_recording() ----------\n");

    // Reset timer
    timer_module_reset(GST_STATE_PAUSED);

    // Pause the stream
    gst_element_set_state(g_pipeline, GST_STATE_PAUSED);
}

void rec_continue_recording()  {
    // Valid pipeline?
    if (!GST_IS_PIPELINE(g_pipeline)) return;

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

    // Already playing?
    //if (state == GST_STATE_PLAYING) return;

    LOG_DEBUG("\n--------- rec_continue_recording() ----------\n");

    // Reset timer
    timer_module_reset(GST_STATE_PLAYING);

    // Continue recording
    gst_element_set_state(g_pipeline, GST_STATE_PLAYING);

}

const gchar *rec_get_state_name(gint state) {
    // Return name of the recording state, state of pipeline.

    switch (state) {
    case GST_STATE_PAUSED:
        return "RECORDING PAUSED";

    case GST_STATE_VOID_PENDING:
        return "PENDING, STATE SHIFT";

    case GST_STATE_PLAYING:
        return "RECORDING ON";

    case GST_STATE_READY:
        return "IN READY STATE";

    case GST_STATE_NULL:
        return "RECORDING OFF, NULL STATE";

    default:
        return "UNKNOWN STATE";
    }
}


void rec_update_gui() {
    // Recording state has changed (PLAYING, PAUSED, STOPPED/NULL).

    // Set widgets and GUI.
    rec_manager_update_gui();
}

gboolean rec_start_recording() {
    LOG_DEBUG("\n--------- rec_start_recording() ----------\n");

    // Get actual recording state now!
    gint state = -1;
    gint pending = -1;
    rec_get_state(&state, &pending);

    // Already recording?
    if (state == GST_STATE_PLAYING) {
        // TODO: FIXME.
        // Some players do not send STOP message when they change a track.
        // Audio-recorder simply continues to record to the same file.
        //
        LOG_DEBUG("gst-recorder.c, rec_start_recording()  FIX THIS??.\n");
        return TRUE;

        // Is it paused?
    } else if (state == GST_STATE_PAUSED) {
        // Continue recording
        rec_continue_recording();
        return TRUE;
    }

    // Get data from Gsettings (this data is saved by rec-manager.c !) 

    gchar *track_title = NULL;
    gchar *artist_name = NULL;
    gchar *album_name = NULL;
    gchar *url = NULL;

    gchar *profile_id = NULL;

    // Track-title sent from media players, Skype 
    conf_get_string_value("track/track-title", &track_title);
    str_trim(track_title);

    //Start recording to a new file. track-title=Streaming Data, artist=http:  www radiocity fi oulu, album=Radio City Oulu
    // xesam:artist': <['http://www.radiocity.fi/oulu']>

    // Artist sent from media players
    conf_get_string_value("track/artist-name", &artist_name);
    str_trim(artist_name);

    // Album sent from media players
    conf_get_string_value("track/album-name", &album_name);
    str_trim(album_name);

    // Url for a web or radio stream or local file.
    // Local files begin with file:///
    // Web urls might begin with http://,  https://, wwww., or event something else
    conf_get_string_value("track/url", &url);
    str_trim(url);

#if 0 
    g_print("\n");
    g_print("Got track-title:%s\n", track_title);
    g_print("Got artist:%s\n", artist_name);
    g_print("Got album:%s\n", album_name);
    g_print("Got url:%s\n", url);
    g_print("\n");
#endif


    // Some media players copy stream url to both title and url
    // Metdata key "xesam:title" has type:s and value:'http://yleuni-f.akamaihd.net/i/yleliveradiohd_5@113882/index_64_a-p.m3u8?sd=10&rebase=on'
    // Metdata key "xesam:url" has type:s and value:'http://yleuni-f.akamaihd.net/i/yleliveradiohd_5@113882/index_64_a-p.m3u8?sd=10&rebase=on'
    if (g_strrstr0(track_title, url)) {
        g_free(track_title);
        track_title = g_strdup("");
    }

    purify_filename(track_title, TRUE/*purify_all*/);
    purify_filename(artist_name, TRUE/*purify_all*/);
    purify_filename(album_name, TRUE/*purify_all*/);

    LOG_DEBUG("Start recording. Got track-title=%s, artist=%s, album=%s, url=%s\n", track_title, artist_name, album_name, url);

    // Get last (saved, recorded) filename with full path
    gchar *last_file_name = NULL;
    conf_get_string_value("track/last-file-name", &last_file_name);
    str_trim(last_file_name);

    // Stop current activity
    rec_stop_recording(FALSE);

    // Reset timer (prepare for GST_STATE_PLAYING state)
    timer_module_reset(GST_STATE_PLAYING);

    // Create a new GStreamer pipeline and start recording.

    // Clear static variables; call with NULLs
    rec_level_message_cb(NULL, NULL, NULL);

    // Variables
    gboolean ret = FALSE;

    // Parms to construct a Gstreamer pipeline
    PipelineParms *parms = g_malloc0(sizeof(PipelineParms));

    // Append to file?
    conf_get_boolean_value("append-to-file", &parms->append);

    if (parms->append && g_file_test(last_file_name, G_FILE_TEST_IS_REGULAR)) {
        // Record to an existing file
        parms->filename = g_strdup(last_file_name);
        
        goto LBL_2;
    }

    // Some players send "Unknown" text instead of empty string
    if (artist_name && g_ascii_strncasecmp(artist_name, "Unknown", 7) == 0) {
        *artist_name = '\0';
    }

    // url start with file:///? (file:/// means a local file)
    if ((str_length(url, NAME_MAX) > 4)  && (!str_startwith(url, "file://", TRUE))) {
        // Examples of other urls are:
        //  http://
        //  https://
        //  www.
        //  magnatune://
        //  somafm://
        
        // Create unique filename based on track_title + artist
        parms->filename = rec_create_filename(track_title, artist_name, album_name);

    }

    // Did we generated a filename with success?
    if (str_length(parms->filename, NAME_MAX) < 3) {

        g_free(parms->filename);

        // Simply generate a new, unique filename from a datetime (eg. YYYY-MM-DD HH:MM) pattern
        parms->filename = rec_create_filename("", "", "");

    }

LBL_2:

    // Purify the final filename, remove illegal characters. Edit in place.
    purify_filename(parms->filename, FALSE);

    // Can we write to path/filename?
    if (!is_file_writable(parms->filename)) {
        gchar *msg = g_strdup_printf(_("Cannot write to file \"%s\".\n"), parms->filename);

        // Show error text
        LOG_DEBUG("Cannot write to file \"%s\".\n", parms->filename);

        rec_manager_set_error_text(msg);
        g_free(msg);

        goto LBL_1;
    }

    // Save the last file name (so we can continue from it later on (if append==TRUE in the GUI))
    conf_save_string_value("track/last-file-name", parms->filename);

    // Get the saved media profile id (aac, mp3, cdlossless, cdlossy, etc).
    profile_id = rec_get_profile_id();

    // Get partial pipline for this profile_id
    parms->profile_str = profiles_get_pipeline(profile_id);
    parms->file_ext = profiles_get_extension(profile_id);


#if 0
    // Debugging:
    gchar *device_id = NULL;
    conf_get_string_value("audio-device-id", &device_id);

    gchar *device_name = NULL;
    conf_get_string_value("audio-device-name", &device_name);

    gint device_type = -1;
    conf_get_int_value("audio-device-type", &device_type);

    LOG_DEBUG("audio-device-id=%s\n", audio_device_id);
    LOG_DEBUG("audio-device-name=%s\n", audio_device_name);
    LOG_DEBUG("audio-device-type=%d\n", audio_device_type);

    g_free(device_name);
    g_free(device_id);
#endif

    // Show filename in the GUI
    rec_manager_set_filename_label(parms->filename);

    // Get audio source and device list
    gchar *audio_source = NULL;
    parms->dev_list = audio_sources_get_device_NEW(&audio_source);
    parms->source = audio_source;


    // Test if the pipeline will be valid.
    // Test if the appropriate GStreamer plugin has been installed.
    gchar *err_msg = NULL;
    gboolean test_OK = profiles_test_plugin(profile_id, &err_msg);

    if (!test_OK) {
        // Missing Gstreamer plugin!

        // Display error message in the GUI (set red label)
      	rec_manager_set_error_text(err_msg);

        LOG_ERROR(err_msg);

        g_free(err_msg);

        // Stop and reset everything
        rec_stop_and_reset();

        goto LBL_1;
    }

    // Now build a GStreamer pipeline with parms
    GError *error = NULL;
    g_pipeline = rec_create_pipeline(parms, &error);

    ret = TRUE;

    // Ok?
    if (error) {
        // Got errors.

        // Display error message in the GUI (set red label)
        rec_manager_set_error_text(error->message);

        // Stop and reset everything
        rec_stop_and_reset();

        g_error_free(error);

        ret = FALSE;
    } else {
        // Alles Ok. Clear error label in the GUI.
        rec_manager_set_error_text(NULL);
    }

    LOG_DEBUG("------------------------\n");

LBL_1:
    g_free(profile_id);

    g_free(track_title);
    g_free(artist_name);
    g_free(album_name);
    g_free(url);

    pipeline_free_parms(parms);
    parms = NULL;

    g_free(last_file_name);

    return ret;
}

gint64 rec_get_stream_time() {
    // Return current recording time in seconds

    GstFormat format = GST_FORMAT_TIME;
    gint64 val = -1;
    gint secs = 0L;

    // Valid pipeline?
    if (!GST_IS_ELEMENT(g_pipeline)) return 0L;

    // Stream/recording time
    // Ref: https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/GstElement.html#gst-element-query-position
    if (gst_element_query_position(g_pipeline, format, &val) && val != -1) {
        secs = val / GST_SECOND;
    }
    return secs;
}

void rec_stop_recording(gboolean delete_file) {
    // Stop recording, terminate pipeline

    if (!GST_IS_PIPELINE(g_pipeline)) return;

    // Get recording state
    gint state = -1;
    gint pending = -1;
    rec_get_state(&state, &pending);

    // Already stopped?
    if (state != GST_STATE_NULL) {
        // Reset timer
        timer_module_reset(GST_STATE_NULL);
    }

    LOG_DEBUG("rec_stop_recording(%s)\n", (delete_file ? "delete_file=TRUE" : "delete_file=FALSE"));

    // Notes:
    // The gst_element_send_event() with EOS has been commented out earlier because this app started freeze.

    // 25.Jan.2021 Osmo
    // I have enable the line again because .m4a files are useless without it. 

    // Send EOS message. 
    // This will terminate the stream/file properly. This is very important for ACC (.m4a) files.
    // Same as:
    // $ gst-launch-1.0 -e
    //   
    gst_element_send_event(g_pipeline, gst_event_new_eos());
    g_usleep(GST_USECOND * 5);

    // Set pipeline state to NULL
    rec_set_state_to_null();

    // Shutdown the entire pipeline
    gst_element_set_state(g_pipeline, GST_STATE_NULL);

    // Destroy it
    if (GST_IS_OBJECT(g_pipeline))
        gst_object_unref(GST_OBJECT(g_pipeline));

    g_pipeline = NULL;

    LOG_DEBUG("--------- Pipeline closed and destroyed ----------\n\n");

    // Delete the recorded file?
    if (delete_file) {
        // Get last saved file name
        gchar *filename = NULL;
        conf_get_string_value("track/last-file-name", &filename);

        LOG_DEBUG("Deleted file:\"%s\"\n", filename);

        // Remove it
        g_remove(filename);
        g_free(filename);

        // Erase last saved file name
        conf_save_string_value("track/last-file-name", "");

        // Update filename in the GUI
        rec_manager_set_filename_label("");
    }

    // Notice:
    // The rec_state_changed_cb() function will reset the GUI by calling rec_manager_update_gui();
}

void rec_stop_and_reset() {
    // Stop recording
    rec_stop_recording(FALSE);

    // Reset window and its widgets
    rec_manager_update_gui();
}

void rec_get_state(gint *state, gint *pending) {
    /*
    state:
     GST_STATE_VOID_PENDING
     GST_STATE_NULL
     GST_STATE_READY
     GST_STATE_PAUSED
     GST_STATE_PLAYING
    */
    *state = GST_STATE_NULL;
    *pending = GST_STATE_NULL;

    // The pipeline has been created?
    if (!GST_IS_ELEMENT(g_pipeline)) return;

    // The state is?
    // Ref: https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/GstElement.html#gst-element-get-state
    gst_element_get_state(g_pipeline, (GstState*)state, (GstState*)pending, 0);
}

gboolean rec_is_recording() {
    // Get recording state
    gint state = -1;
    gint pending = -1;
    rec_get_state(&state, &pending);

    gboolean ret = FALSE;

    // Is playing?
    switch (state) {
    case GST_STATE_PLAYING:
        ret = TRUE;
        break;
    }
    return ret;
}

gboolean rec_is_paused() {
    // Get recording state
    gint state = -1;
    gint pending = -1;
    rec_get_state(&state, &pending);

    gboolean ret = FALSE;

    // Is paused?
    switch (state) {
    case GST_STATE_PAUSED:
        ret = TRUE;
        break;
    }
    return ret;
}

static gboolean rec_level_message_cb(GstBus *bus, GstMessage *msg, void *user_data) {

    static guint64 last_stream_time_t = 0L;
    static guint64 last_stream_time_fz = 0L;

    // Calling with NULL arguments?
    // This will reset the static variables, then exit.
    if (!msg) {
        last_stream_time_t = 0L;
        last_stream_time_fz = 0L;
        return TRUE;
    }

    guint64 stream_time = 0L;

    if (msg->type == GST_MESSAGE_ELEMENT) {
        const GstStructure *s = gst_message_get_structure(msg);
        const gchar *name = gst_structure_get_name(s);

#if 0 
         // Print all field names:
         gint n = gst_structure_n_fields(s);
         gint i = 0;
         for (i=0; i < n; i++) {
             const gchar *fn = gst_structure_nth_field_name(s, i);
             GType t = gst_structure_get_field_type(s, "rms");
             g_print("%s field:%s (%s)\n", name, fn, g_type_name(t));
         }

#endif

        if (g_str_equal(name, "level")) {
            // Ref: https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-good-plugins/html/gst-plugins-good-plugins-level.html

            //Field names:
            //level field:endtime (GValueArray)
            //level field:timestamp (GValueArray)
            //level field:stream-time (GValueArray)
            //level field:running-time (GValueArray)
            //level field:duration (GValueArray)
            //level field:rms (GValueArray)
            //level field:peak (GValueArray)
            //level field:decay (GValueArray)

            GstClockTime endtime;
            if (!gst_structure_get_clock_time(s, "endtime", &endtime)) {
                LOG_ERROR("rec_level_message_cb: Cannot read endtime.\n");
            } else {
                stream_time = GST_TIME_AS_SECONDS(endtime);
            }

            gdouble rms_dB = 0;
            gdouble rms_norm = 0;

            gdouble peak_dB = 0;
            gdouble peak_norm = 0;

            const GValue *value = gst_structure_get_value(s, "rms");
            GValueArray *rms_arr = (GValueArray*)g_value_get_boxed(value);

            guint channels = rms_arr->n_values;
            if (channels < 1) goto LBL_1;

            value = gst_structure_get_value(s, "peak");
            GValueArray *peak_arr = (GValueArray*)g_value_get_boxed(value);

            guint i = 0;
            for (i = 0; i < channels; ++i) {
                // Read RMS (decibel) value
                value = rms_arr->values + i;
                rms_dB = rms_dB + g_value_get_double(value);

                // Read pulse peak (decibel) value
                value = peak_arr->values + i;
                peak_dB = peak_dB + g_value_get_double(value);
            }

            // Take average for all channels
            rms_dB = rms_dB / channels; 
            peak_dB = peak_dB / channels; 

            // Normalize, convert dB to [0 - 1.0]
            rms_norm = rms_norm + exp(rms_dB / 20);
            if (rms_norm > 1.0) rms_norm = 1.0;

            peak_norm = peak_norm + exp(peak_dB / 20);
            if (peak_norm > 1.0) peak_norm = 1.0;

            #if 0 
                    // Test & debug:
                    gint channels;
                    gdouble rms_dB, peak_dB, decay_dB;
                    gdouble rms;
                    const GValue *array_val;
                    const GValue *value;
                    GValueArray *rms_arr, *peak_arr, *decay_arr;
                    gint i;

                    array_val = gst_structure_get_value (s, "rms");
                    rms_arr = (GValueArray *) g_value_get_boxed (array_val);

                    array_val = gst_structure_get_value (s, "peak");
                    peak_arr = (GValueArray *) g_value_get_boxed (array_val);

                    array_val = gst_structure_get_value (s, "decay");
                    decay_arr = (GValueArray *) g_value_get_boxed (array_val);

                    channels = rms_arr->n_values;

                    g_print ("endtime: %" GST_TIME_FORMAT ", channels: %d\n", GST_TIME_ARGS (endtime), channels);

                    for (i = 0; i < channels; ++i) {
                        g_print ("channel %d\n", i);

                        value = rms_arr->values + i;
                        rms_dB = g_value_get_double (value);

                        value = peak_arr->values + i;
                        peak_dB = g_value_get_double (value);

                        value = decay_arr->values + i;
                        decay_dB = g_value_get_double (value);

                        rms = pow(10, rms_dB / 20);
                        //gdouble norm_rms = exp(rms_dB / 20);

                        gdouble norm_P = pow(10, peak_dB / 20);	

                        g_print ("channel %d,    RMS: %f dB, peak: %f dB, decay: %f dB, norm RMS %3.3f, norm Peak %3.3f\n", i, rms_dB, peak_dB, decay_dB, rms, norm_P);
                        g_print ("normalized rms value: %f\n", rms);
                    }

            #endif

            // Update level bar
            rec_manager_update_level_bar(rms_norm, peak_norm); 

            // Update time label in the GUI.
            if (stream_time - last_stream_time_t >= 1/*seconds*/) {
                guint hours = (guint)(stream_time / 3600);
                stream_time = stream_time - (hours*3600);

                // Count only to 23 hours
                // if (hours > 99) hours = 23;

                guint minutes = (guint)(stream_time / 60);
                guint seconds = stream_time - (minutes*60);

                // Show stream time
                gchar *time_txt = g_strdup_printf("%02d:%02d:%02d", hours, minutes, seconds);
                rec_manager_set_time_label(time_txt);
                g_free(time_txt);

                // Save last stream_time
                last_stream_time_t = stream_time;
            }


            // Update file size in the GUI.
            if (stream_time < 10 || (stream_time - last_stream_time_fz > 3/*seconds*/)) {
                // Update more frequently if stream_time < 10 seconds, after that, update each 3.rd second.

                gchar *filename = rec_manager_get_output_filename();
                gchar *size_txt = NULL;

                // Get file size.
                // Ref: https://developer.gnome.org/glib/2.34/glib-File-Utilities.html#g-stat
                GStatBuf fstat;
                if (g_stat(filename, &fstat))
                    LOG_ERROR("Cannot get file information of %s.\n", filename);
                else
                    size_txt = format_file_size(fstat.st_size);

                // Show file size
                rec_manager_set_size_label(size_txt);

                g_free(filename);
                g_free(size_txt);

                // Save last stream_time
                last_stream_time_fz = stream_time;
            }
        }
    }

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

static void rec_state_changed_cb(GstBus *bus, GstMessage *msg, void *userdata) {
    if (!GST_IS_MESSAGE(msg)) return;

    // We are only interested in the top-level pipeline.
    if (GST_MESSAGE_SRC(msg) != GST_OBJECT(g_pipeline)) return;

    GstState old_state, new_state;
    gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);

    GstState state, pending;
    gst_element_get_state(g_pipeline, &state, &pending, 0);
    LOG_DEBUG("Pipeline state changed from %s to: %s  (stat=%s pending=%s).\n",
              gst_element_state_get_name(old_state), gst_element_state_get_name(new_state),
              gst_element_state_get_name(state), gst_element_state_get_name(pending));

    // Pipeline state changed from PAUSED to: READY  (stat=READY pending=VOID_PENDING).

    switch (new_state) {

    case GST_STATE_PLAYING:
        // We are playing. Inform the GUI.
        rec_manager_update_gui();
        break;

    case GST_STATE_READY:
        // Recording may have stopped. Inform the GUI.
        rec_manager_update_gui();
        break;

    case GST_STATE_PAUSED:
        // Goes from GST_STATE_PLAYING to GST_STATE_PAUSED state?
        if (old_state == GST_STATE_PLAYING) {

            // Recording has paused. Inform the GUI.
            rec_manager_update_gui();

        }
        break;

    case GST_STATE_NULL:
        // Recording has stopped. Inform the GUI.
        rec_manager_update_gui();
        break;

    default:
        break;
    }
}

static void rec_pipeline_error_cb(GstBus *bus, GstMessage *msg, void *userdata) {
    if (!GST_IS_MESSAGE(msg)) return;

    GError *error = NULL;
    gchar *dbg = NULL;

    gst_message_parse_error(msg, &error, &dbg);
    g_return_if_fail(error != NULL);

    LOG_DEBUG("\nGot pipeline error: %s.\n", error->message);

    if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_ELEMENT) {
        ;
    }

    if (dbg) {
        g_free(dbg);
    }

    if (error->code == GST_RESOURCE_ERROR_BUSY) {
        g_error_free(error);
        return;
    }

    if (error) {
        g_error_free(error);
    }
}

static void rec_eos_msg_cb(GstBus *bus, GstMessage *msg, void *userdata) {
    LOG_DEBUG("Got End Of Stream (EOS) message. Recording ended.\n");
}

GstElement *rec_create_pipeline(PipelineParms *parms, GError **error) {
    // Create a GStreamer pipeline for audio recording.
    gchar *err_msg = NULL;

    // Print debug info
    LOG_DEBUG("----------------------------\n");
    LOG_DEBUG("rec_create_pipeline, The parameters are:\n");
    LOG_DEBUG("audio source=%s\n", parms->source);
    LOG_DEBUG("device list is:\n");

    GList *n = g_list_first(parms->dev_list);
    while (n) {
        gchar *device = (gchar*)n->data;
        (void)device; // Avoid unused var message

        LOG_DEBUG("\t%s\n", device);
        n = g_list_next(n);
    }

    LOG_DEBUG("profile from GSettings=%s\n",parms->profile_str);
    LOG_DEBUG("filename=%s\n", parms->filename);
    LOG_DEBUG("append to file=%s\n", (parms->append ? "TRUE" : "FALSE"));

    // Create pipeline from the parms
    GstElement *pipeline = pipeline_create(parms, &err_msg);

    // Errors?
    if (!GST_IS_PIPELINE(pipeline) || err_msg) {
        goto LBL_1;
    }

    // Get "filesink" and set location (file name) and append mode
    GstElement *filesink = gst_bin_get_by_name(GST_BIN(pipeline), "filesink");

    if (!GST_IS_ELEMENT(filesink)) {
        err_msg = g_strdup_printf(_("Cannot find audio element %s.\n"), "filesink");
        goto LBL_1;
    }

    g_object_set(G_OBJECT(filesink), "location", parms->filename, NULL);
    g_object_set(G_OBJECT(filesink), "append", parms->append, NULL);
    g_object_unref(filesink);

    // Add a message handler
    GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));

    // gst_bus_add_watch (bus, bus_info_cb, NULL);
    gst_bus_add_signal_watch(bus);

    // Detect state changes
    g_signal_connect(bus, "message::state-changed", G_CALLBACK(rec_state_changed_cb), NULL);

    // Monitor sound level/amplitude
    g_signal_connect(bus, "message::element", G_CALLBACK(rec_level_message_cb), NULL);

    // Catch error messages
    g_signal_connect(bus, "message::error", G_CALLBACK(rec_pipeline_error_cb), NULL);

    // End of stream
    g_signal_connect(bus, "message::eos", G_CALLBACK(rec_eos_msg_cb), NULL);

    gst_object_unref(bus);

    // Assume all is OK
    gboolean ret = TRUE;

    // Set the pipeline to "playing" state
    gst_element_set_state(pipeline, GST_STATE_PAUSED);

    if (gst_element_set_state(pipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
        err_msg = g_strdup(_("Cannot start reading from the stream/pipeline.\n"));
        ret = FALSE;
    } else {
        LOG_DEBUG("Pipeline is OK. Starting recording to %s.\n", parms->filename);
    }

    // Are we finally ok?
    if (ret) {
        return pipeline;
    }

    // Error occured
LBL_1:
    // Set the error object
    if (!err_msg)
        err_msg = g_strdup_printf(_("Cannot create audio pipeline. %s.\n"), "");

    LOG_ERROR(err_msg);

    // Destroy pipeline
    if (G_IS_OBJECT(pipeline)) {
        gst_element_set_state(pipeline, GST_STATE_NULL);
        gst_object_unref(GST_OBJECT(pipeline));
    }

    // Set error
    g_set_error(error,
                AUDIO_RECORDER,      /* Error domain */
                AUDIO_RECORDER_ERR1, /* Error code */
                err_msg, "");

    g_free(err_msg);

    // Return NULL
    return NULL;
}

gchar *rec_get_output_filename() {
    // Return current output filename

    // Valid pipeline?
    if (!GST_IS_ELEMENT(g_pipeline)) return NULL;

    // Get the "filesink" element (by name)
    GstElement *filesink = gst_bin_get_by_name(GST_BIN(g_pipeline), "filesink");

    // Got filesink?
    if (!GST_IS_ELEMENT(filesink)) return NULL;

    gchar *filename = NULL;
    g_object_get(G_OBJECT(filesink), "location", &filename, NULL);
    g_object_unref(filesink);

    // The caller should g_free() the value
    return filename;
}

// ------------------------------------------------------------
// Support functions
// ------------------------------------------------------------

static gchar *rec_get_profile_id() {
    // Return saved media profile id.
    gchar *id = NULL;
    conf_get_string_value("media-format", &id);

    // Is this id real?
    gboolean is_OK = profiles_check_id(id);

    if (!is_OK) {
        g_free(id);
        ProfileRec *rec = profiles_find_for_ext("ogg");
        if (rec) {
            id = g_strdup(rec->id);
        }
    }

    // The caller should g_free() this value
    return id;
}

static gchar *check_audio_folder(gchar *audio_folder) {
    // Create the folder with all sub-paths, this may fail.
    // 0755 = "rwxr-xr-x";
    g_mkdir_with_parents(audio_folder, 0755);

    // Directory exists?
    if (!g_file_test(audio_folder, G_FILE_TEST_IS_DIR)) {
        // Replace the old audio_folder
        g_free(audio_folder);

        // Set it to $HOME
        audio_folder = get_home_dir();
    }

    return audio_folder;
}

static gchar *rec_create_filename(gchar *track_title, gchar *artist, gchar *album) {
    // Create filename based on track title and artist (and maybe album)

    // Typical filenames:
    // 2019-01-20-09:10:58.mp3                : if track_title == NULL   
    // Love-you-sooo.mp3                      : if track_title != NULL  (try this first)      
    // Love-you-sooo-2019-01-20-09:10:58.mp3  : if track_title != NULL  (try this next, if was duplicate filename )   

    // Add artist (or album) to the path
    // Add also audio_folder to the path

    gchar *file_name = NULL;

    // Get the saved media profile id (aac, mp3, cdlossless, cdlossy, etc).
    gchar *profile_id = rec_get_profile_id();

    // Take the file extension from media-profile_id; .ogg, .mp3, etc.
    gchar *file_ext = profiles_get_extension(profile_id);

    // Get Audio/ folder
    gchar *audio_folder = get_audio_folder();
    audio_folder = check_audio_folder(audio_folder);

   // Pattern to generate a unique filename
    gchar *filename_pattern = get_filename_pattern();

    gchar *basename = substitute_time_and_date_pattern(filename_pattern);

    gchar *path = NULL;

    // Do we have artist name?
    if (str_length(artist, NAME_MAX) > 3) {
        // Build path: audio_folder / artist
        // Eg. "/home/moma/Audio/Salomon Burke/" or from Skype "/home/moma/Audio/Skype recordings/"
        path = g_build_filename(audio_folder, artist, NULL);

        // Create directory
        if (g_mkdir_with_parents(path, 0755) == -1) {
            // Ref: https://developer.gnome.org/glib/unstable/glib-File-Utilities.html#g-mkdir-with-parents
            LOG_ERROR("Cannot create path \"%s\"\n", path);
            g_free(path);
            path = NULL;
        }
    }

#define MAX_SLEN1 35
#define MAX_SLEN2 23

    // 2 loops
    for (guint i = 0; i < 2; i++) { 

        g_free(file_name);
        file_name = NULL;

        gchar *fname = NULL;
        gchar *str_tmp = g_strdup(track_title); 

        // --------------------------------------
        // i == 0  (try track-title + file_ext)
        // --------------------------------------
        if (i == 0) {

            // Do we have track_title?
            if (str_length0(str_tmp) < 3) {
                g_free(str_tmp); 
                str_tmp = NULL;              
                continue;
            }

            // Cut track title to MAX_SLEN1 characters
            if (str_length0(str_tmp) > MAX_SLEN1) {
                *(str_tmp + MAX_SLEN1) = '\0';
                str_trim(str_tmp);
            }

            // Try track_title + file extension
            fname = g_strdup_printf("%s.%s", str_tmp, (file_ext ? file_ext : "xxx"));

        // ----------------------------------------------------------
        // i == 1  (try track-title + YYYY-MM-DD HH:MM:SS + file_ext)
        // ----------------------------------------------------------
        } else {

            // Cut track title to MAX_SLEN2 characters
            if (str_length0(str_tmp) > MAX_SLEN2) {
                *(str_tmp + MAX_SLEN2) = '\0';
                str_trim(str_tmp);
            }

            // Do we have track_title?
            if (str_length0(str_tmp) < 3) {            
                // Try basename + file extension
                fname = g_strdup_printf("%s.%s", basename, (file_ext ? file_ext : "xxx"));

            } else {
                // Try track_title + basename + file extension
                fname = g_strdup_printf("%s-%s.%s", str_tmp, basename, (file_ext ? file_ext : "xxx"));
            }

        }

        // Add path

        if (path) {
            // audio_folder / artist + track_title.ext
            file_name = g_build_filename(path, fname, NULL);
        } else {
            // audio_folder + track_title.ext
            file_name = g_build_filename(audio_folder, fname, NULL);
        }

        g_free(fname);
        fname = NULL;

        g_free(str_tmp);
        str_tmp = NULL;

        // file_name is available?
        gboolean done = (!g_file_test(file_name, G_FILE_TEST_IS_REGULAR));

        if (done) break;  // exit loop?
    }


    LOG_DEBUG("Generated filename=%s\n", file_name);

    g_free(path);

    g_free(profile_id);
    g_free(file_ext);
    g_free(audio_folder);

    g_free(filename_pattern);
    g_free(basename);

    // The caller should g_free() this value
    return file_name;
}