File: csmodule.c

package info (click to toggle)
csound 1%3A6.18.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 63,220 kB
  • sloc: ansic: 192,643; cpp: 14,149; javascript: 9,654; objc: 9,181; python: 3,376; java: 3,337; sh: 1,840; yacc: 1,255; xml: 985; perl: 635; lisp: 411; tcl: 341; lex: 217; makefile: 128
file content (1328 lines) | stat: -rw-r--r-- 48,101 bytes parent folder | download | duplicates (3)
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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
/*
    csmodule.c:

    Copyright (C) 2005 Istvan Varga
    based on dl_opcodes.c, Copyright (C) 2002 John ffitch

    This file is part of Csound.

    The Csound Library is free software; you can redistribute it
    and/or modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    Csound 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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with Csound; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
    02110-1301 USA
*/

/******************************************************************************
 * NEW PLUGIN INTERFACE                                                       *
 * ====================                                                       *
 *                                                                            *
 * Plugin libraries are loaded from the directory defined by the environment  *
 * variable OPCODE6DIR (or the current directory if OPCODE6DIR is unset) by   *
 * csoundPreCompile() while initialising a Csound instance, and are unloaded  *
 * at the end of performance by csoundReset().                                *
 * A library may export any of the following five interface functions,        *
 * however, the presence of csoundModuleCreate() is required for identifying  *
 * the file as a Csound plugin module.                                        *
 *                                                                            *
 * int csoundModuleCreate(CSOUND *csound)       (required)                    *
 * --------------------------------------                                     *
 *                                                                            *
 * Pre-initialisation function, called by csoundPreCompile().                 *
 *                                                                            *
 * int csoundModuleInit(CSOUND *csound)         (optional)                    *
 * ------------------------------------                                       *
 *                                                                            *
 * Called by Csound instances before orchestra translation. One possible use  *
 * of csoundModuleInit() is adding new opcodes with csoundAppendOpcode().     *
 *                                                                            *
 * int csoundModuleDestroy(CSOUND *csound)      (optional)                    *
 * ---------------------------------------                                    *
 *                                                                            *
 * Destructor function for Csound instance 'csound', called at the end of     *
 * performance, after closing audio output.                                   *
 *                                                                            *
 * const char *csoundModuleErrorCodeToString(int errcode)   (optional)        *
 * ------------------------------------------------------                     *
 *                                                                            *
 * Converts error codes returned by any of the initialisation or destructor   *
 * functions to a string message.                                             *
 *                                                                            *
 * int csoundModuleInfo(void)                   (optional)                    *
 * --------------------------                                                 *
 *                                                                            *
 * Returns information that can be used to determine if the plugin was built  *
 * for a compatible version of libcsound. The return value may be the sum of  *
 * any of the following two values:                                           *
 *                                                                            *
 *   ((CS_APIVERSION << 16) + (CS_APISUBVER << 8))      API version           *
 *   (int) sizeof(MYFLT)                                MYFLT type            *
 *                                                                            *
 ******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if !(defined (__wasi__))
#include <setjmp.h>
#include <errno.h>
#endif

#include "csoundCore.h"
#include "csmodule.h"

#if defined(__MACH__)
#include <TargetConditionals.h>
#if (TARGET_OS_IPHONE == 0) && (TARGET_IPHONE_SIMULATOR == 0)
#if defined(MAC_OS_X_VERSION_10_6) && \
    (MAC_OS_X_VERSION_MIN_REQUIRED>=MAC_OS_X_VERSION_10_6)
#define NEW_MACH_CODE
#endif
#endif
#endif

#if !(defined (NACL)) && !(defined (__wasi__))
#if defined(LINUX) || defined(NEW_MACH_CODE) || defined(__HAIKU__)
#include <dlfcn.h>
#elif defined(WIN32)
#include <windows.h>
#endif
#endif


#if defined(HAVE_DIRENT_H)
#  include <dirent.h>
#  if 0 && defined(__MACH__)
typedef void*   DIR;
DIR             opendir(const char *);
struct dirent   *readdir(DIR*);
int             closedir(DIR*);
#  endif
#endif

#if defined(WIN32) && !defined(__CYGWIN__)
#  include <io.h>
#  include <direct.h>
#endif

extern  int     allocgen(CSOUND *, char *, int (*)(FGDATA *, FUNC *));

#if defined(INIT_STATIC_MODULES)
extern int init_static_modules(CSOUND *);
#endif

/* module interface function names */

static  const   char    *opcode_init_Name =   "csound_opcode_init";
static  const   char    *fgen_init_Name =     "csound_fgen_init";

static  const   char    *PreInitFunc_Name =   "csoundModuleCreate";
static  const   char    *InitFunc_Name =      "csoundModuleInit";
static  const   char    *DestFunc_Name =      "csoundModuleDestroy";
static  const   char    *ErrCodeToStr_Name =  "csoundModuleErrorCodeToString";

static  const   char    *InfoFunc_Name =      "csoundModuleInfo";

/* environment variable storing path to plugin libraries */
static  const   char    *plugindir_envvar =   "OPCODE6DIR";
static  const   char    *plugindir64_envvar = "OPCODE6DIR64";

/* default directory to load plugins from if environment variable is not set */
#if !(defined (NACL)) && !(defined (__wasi__))
#ifdef __HAIKU__
# ifndef USE_DOUBLE
   static char haikudirs[] = "/boot/system/lib/csound6/plugins:"
        "/boot/home/config/lib/csound6/plugins:"
        "/boot/system/non-packaged/lib/csound6/plugins:"
        "/boot/home/config/non-packaged/lib/csound6/plugins";
# else
   static char haikudirs[] = "/boot/system/lib/csound6/plugins64:"
        "/boot/home/config/lib/csound6/plugins64:"
        "/boot/system/non-packaged/lib/csound6/plugins64:"
        "/boot/home/config/non-packaged/lib/csound6/plugins64";
# endif
# define CS_DEFAULT_PLUGINDIR  haikudirs
#elif !(defined(_CSOUND_RELEASE_) && (defined(LINUX) || defined(__MACH__)))
#  define ENABLE_OPCODEDIR_WARNINGS 1
#  ifdef CS_DEFAULT_PLUGINDIR
#    undef CS_DEFAULT_PLUGINDIR
#  endif
#  define CS_DEFAULT_PLUGINDIR      "."
#else
#  define ENABLE_OPCODEDIR_WARNINGS 0
#  ifndef CS_DEFAULT_PLUGINDIR
#    ifndef USE_DOUBLE
#      define CS_DEFAULT_PLUGINDIR  "/usr/local/lib/csound/plugins"
#    else
#      define CS_DEFAULT_PLUGINDIR  "/usr/local/lib/csound/plugins64"
#    endif
#  endif
#endif
#endif

#if (TARGET_OS_IPHONE != 0) && (TARGET_IPHONE_SIMULATOR != 0)
#  define ENABLE_OPCODEDIR_WARNINGS 0
#endif

typedef struct opcodeLibFunc_s {
    int64_t  (*opcode_init)(CSOUND *, OENTRY **);  /* list of opcode entries  */
    NGFENS  *(*fgen_init)(CSOUND *);        /* list of named GEN routines    */
    void    (*dummy)(void);                 /* unused                        */
} opcodeLibFunc_t;

typedef struct pluginLibFunc_s {
    int         (*InitFunc)(CSOUND *);      /* initialisation routine        */
    int         (*DestFunc)(CSOUND *);      /* destructor routine            */
    const char  *(*ErrCodeToStr)(int);      /* convert error code to string  */
} pluginLibFunc_t;

typedef struct csoundModule_s {
    struct csoundModule_s *nxt;             /* pointer to next link in chain */
    void        *h;                         /* library handle                */
    int         (*PreInitFunc)(CSOUND *);   /* pre-initialisation routine    */
                                            /*   (always NULL if opcode lib) */
    union {
      pluginLibFunc_t   p;                  /* generic plugin interface      */
      opcodeLibFunc_t   o;                  /* opcode library interface      */
    } fn;
    char        name[1];                    /* name of the module            */
} csoundModule_t;

static CS_NOINLINE void print_module_error(CSOUND *csound,
                                           const char *fmt, const char *fname,
                                           const csoundModule_t *m, int err)
{
    csoundMessageS(csound, CSOUNDMSG_ERROR, Str(fmt), fname);
    if (m != NULL && m->fn.p.ErrCodeToStr != NULL)
      csoundMessageS(csound, CSOUNDMSG_ERROR,
                       ": %s\n", Str(m->fn.p.ErrCodeToStr(err)));
    else
      csoundMessageS(csound, CSOUNDMSG_ERROR, "\n");
}

static int check_plugin_compatibility(CSOUND *csound, const char *fname, int n)
{
    int     myfltSize, minorVersion, majorVersion;

    myfltSize = n & 0xFF;
    if (UNLIKELY(myfltSize != 0 && myfltSize != (int) sizeof(MYFLT))) {
      csoundWarning(csound, Str("not loading '%s' (uses incompatible "
                                  "floating point type)"), fname);
      return -1;
    }
    if (UNLIKELY(n & (~0xFF))) {
      minorVersion = (n & 0xFF00) >> 8;
      majorVersion = (n & (~0xFFFF)) >> 16;
      if (majorVersion != (int) CS_APIVERSION ||
          (minorVersion > (int) CS_APISUBVER)) { /* NOTE **** REFACTOR *** */
        csoundWarning(csound, Str("not loading '%s' (incompatible "
                                    "with this version of Csound (%d.%d/%d.%d)"),
                        fname, majorVersion,minorVersion,
                        CS_APIVERSION,CS_APISUBVER);
        return -1;
      }
    }
    return 0;
}


/**
 * Initialise a single module.
 * Return value is CSOUND_SUCCESS if there was no error.
 */
static CS_NOINLINE int csoundInitModule(CSOUND *csound, csoundModule_t *m)
{
    int     i;

    if (m->PreInitFunc != NULL) {
      if (m->fn.p.InitFunc != NULL) {
        i = m->fn.p.InitFunc(csound);
        if (UNLIKELY(i != 0)) {
          print_module_error(csound, Str("Error starting module '%s'"),
                                     &(m->name[0]), m, i);
          return CSOUND_ERROR;
        }
      }
    }
    else {
      /* deal with fgens if there are any */
      if (m->fn.o.fgen_init != NULL) {
        NGFENS  *names = m->fn.o.fgen_init(csound);
        for (i = 0; names[i].name != NULL; i++)
          allocgen(csound, names[i].name, names[i].fn);
      }
      if (m->fn.o.opcode_init != NULL) {
        OENTRY  *opcodlst_n;
        int64_t    length;
        /* load opcodes */
        if (UNLIKELY((length = m->fn.o.opcode_init(csound, &opcodlst_n)) < 0L))
          return CSOUND_ERROR;
        else {
          length /= (long) sizeof(OENTRY);
          if (length) {
            if (UNLIKELY(csoundAppendOpcodes(csound, opcodlst_n,
                                               (int) length) != 0))
              return CSOUND_ERROR;
          }
        }
      }
    }
    return CSOUND_SUCCESS;
}


#ifdef __wasi__

__attribute__((used))
void csoundWasiLoadPlugin(CSOUND *csound, void *preInitFunc, void *initFunc, void *destFunc, void *errCodeToStr) {
    csoundModule_t *module = csound->Malloc(csound, sizeof(csoundModule_t) + 1);
    module->h = (void*) NULL;

    // The javascript host must assert that this is provided
    module->PreInitFunc = (int (*)(CSOUND *)) preInitFunc;
    if (initFunc) {
        module->fn.p.InitFunc = (int (*)(CSOUND *)) initFunc;
    }
    if (destFunc) {
        module->fn.p.DestFunc = (int (*)(CSOUND *)) destFunc;
    }
    if (errCodeToStr) {
        module->fn.p.ErrCodeToStr = (const char *(*)(int)) errCodeToStr;
    }

    module->nxt = (csoundModule_t*) csound->csmodule_db;
    csound->csmodule_db = module;

    module->PreInitFunc(csound);
}

__attribute__((used))
void csoundWasiLoadOpcodeLibrary(CSOUND *csound, void *fgenInitFunc, void *opcodeInitFunc) {
    csoundModule_t *module = csound->Malloc(csound, sizeof(csoundModule_t) + 1);
    module->h = (void*) NULL;

    if (fgenInitFunc) {
        module->fn.o.fgen_init = (NGFENS *(*)(CSOUND *)) fgenInitFunc;
    }

    if (opcodeInitFunc) {
        module->fn.o.opcode_init = (int64_t (*)(CSOUND *, OENTRY **)) opcodeInitFunc;
    }

    module->nxt = (csoundModule_t*) csound->csmodule_db;
    csound->csmodule_db = module;
}

__attribute__((used))
int csoundDestroyModules(CSOUND *csound) {
    csoundModule_t  *m;
    int i;
    int retval = CSOUND_SUCCESS;

    while (csound->csmodule_db != NULL) {
      m = (csoundModule_t*) csound->csmodule_db;
      /* call destructor functions */
      if (m->PreInitFunc != NULL && m->fn.p.DestFunc != NULL) {
        i = m->fn.p.DestFunc(csound);
        if (UNLIKELY(i != 0)) {
          print_module_error(csound, Str("Error de-initialising module '%s'"),
                                     &(m->name[0]), m, i);
          retval = CSOUND_ERROR;
        }
      }
      csound->csmodule_db = (void*) m->nxt;
      /* free memory used by database */
      csound->Free(csound, (void*) m);
    }
    /* return with error code */
    return retval;
}

__attribute__((used))
int csoundInitModules(CSOUND *csound) {
    csoundModule_t  *m;
    int i, retval = CSOUND_SUCCESS;
    for (m = (csoundModule_t*) csound->csmodule_db; m != NULL; m = m->nxt) {
      i = csoundInitModule(csound, m);
      if (UNLIKELY(i != CSOUND_SUCCESS && i < retval))
        retval = i;
    }
    /* return with error code */
    return retval;
}

// In browser-wasi, this function is replaced
// by the js-host.
__attribute__((used))
extern int csoundLoadModules(CSOUND *csound);

int csoundLoadExternals(CSOUND *csound) {
    return 0;
}

int csoundLoadAndInitModules(CSOUND *csound, const char *opdir) {
    return 0;
}

#else /* __wasi__ */


/* load a single plugin library, and run csoundModuleCreate() if present */
/* returns zero on success */

static CS_NOINLINE int csoundLoadExternal(CSOUND *csound,
                                          const char *libraryPath)
{
    csoundModule_t  m;
    volatile jmp_buf tmpExitJmp;
    csoundModule_t  *mp;
    char            *fname;
    void            *h, *p;
    int             (*infoFunc)(void);
    int             err;

    /* check for a valid name */
    if (UNLIKELY(libraryPath == NULL || libraryPath[0] == '\0'))
      return CSOUND_ERROR;
    /* remove leading directory components from name */
    fname = (char*) libraryPath + (int) strlen(libraryPath);
    for ( ; fname[0] != DIRSEP && fname != (char*) libraryPath; fname--)
      ;
    if (fname[0] == DIRSEP)
      fname++;
    if (UNLIKELY(fname[0] == '\0'))
      return CSOUND_ERROR;
    /* load library */
/*  #if defined(LINUX) */
    //printf("About to open library '%s'\n", libraryPath);
/* #endif */
    err = csoundOpenLibrary(&h, libraryPath);
    if (UNLIKELY(err)) {
      char ERRSTR[256];
 #if !(defined(NACL)) && (defined(LINUX) || defined(__HAIKU__))
      snprintf(ERRSTR, 256, Str("could not open library '%s' (%s)"),
               libraryPath, dlerror());
 #else
      snprintf(ERRSTR, 256, Str("could not open library '%s' (%d)"),
               libraryPath, err);
 #endif
      if (csound->delayederrormessages == NULL) {
        csound->delayederrormessages = csound->Malloc(csound, strlen(ERRSTR)+1);
        strcpy(csound->delayederrormessages, ERRSTR);
      }
      else {
        char *new =
          csound->ReAlloc(csound, csound->delayederrormessages,
                          strlen(csound->delayederrormessages)+strlen(ERRSTR)+11);
        if (UNLIKELY(new==NULL)) {
          csound->Free(csound, csound->delayederrormessages);
          return CSOUND_ERROR;
        }
        csound->delayederrormessages = new;
        strcat(csound->delayederrormessages, "\nWARNING: ");
        strcat(csound->delayederrormessages, ERRSTR);
      }
      return CSOUND_ERROR;
    }
    /* check if the library is compatible with this version of Csound */
    infoFunc = (int (*)(void)) csoundGetLibrarySymbol(h, InfoFunc_Name);
    if (infoFunc != NULL) {
      if (UNLIKELY(check_plugin_compatibility(csound, fname, infoFunc()) != 0)) {
        csoundCloseLibrary(h);
        return CSOUND_ERROR;
      }
    }
    /* was this plugin already loaded ? */
    for (mp = (csoundModule_t*) csound->csmodule_db; mp != NULL; mp = mp->nxt) {
      if (UNLIKELY(mp->h == h)) {
        csoundCloseLibrary(h);
        return CSOUND_SUCCESS;
      }
    }
    /* find out if it is a Csound plugin */
    memset(&m, 0, sizeof(csoundModule_t));
    m.h = h;
    m.PreInitFunc =
        (int (*)(CSOUND *)) csoundGetLibrarySymbol(h, PreInitFunc_Name);
    if (m.PreInitFunc != NULL) {
      /* generic plugin library */
      m.fn.p.InitFunc =
          (int (*)(CSOUND *)) csoundGetLibrarySymbol(h, InitFunc_Name);
      m.fn.p.DestFunc =
          (int (*)(CSOUND *)) csoundGetLibrarySymbol(h, DestFunc_Name);
      m.fn.p.ErrCodeToStr =
          (const char *(*)(int)) csoundGetLibrarySymbol(h, ErrCodeToStr_Name);
    }
    else {
      /* opcode library */
      m.fn.o.opcode_init =
          (int64_t (*)(CSOUND *, OENTRY **))
              csoundGetLibrarySymbol(h, opcode_init_Name);
      m.fn.o.fgen_init =
          (NGFENS *(*)(CSOUND *)) csoundGetLibrarySymbol(h, fgen_init_Name);
      if (UNLIKELY(m.fn.o.opcode_init == NULL && m.fn.o.fgen_init == NULL)) {
        /* must have csound_opcode_init() or csound_fgen_init() */
        csoundCloseLibrary(h);
        if (UNLIKELY(csound->oparms->msglevel & 0x400))
          csound->Warning(csound, Str("'%s' is not a Csound plugin library"),
                          libraryPath);
        return CSOUND_ERROR;
      }
    }
    /* set up module info structure */
    /* (note: space for NUL character is already included in size of struct) */
    p = (void*) csound->Malloc(csound,
                               sizeof(csoundModule_t) + (size_t) strlen(fname));
    if (UNLIKELY(p == NULL)) {
      csoundCloseLibrary(h);
      csound->ErrorMsg(csound,
                       Str("csoundLoadExternal(): memory allocation failure"));
      return CSOUND_MEMORY;
    }
    mp = (csoundModule_t*) p;
    memcpy(mp, &m, sizeof(csoundModule_t));
    strcpy(&(mp->name[0]), fname);
    /* link into database */
    mp->nxt = (csoundModule_t*) csound->csmodule_db;
    csound->csmodule_db = (void*) mp;
    /* call csoundModuleCreate() if available */
    if (m.PreInitFunc != NULL) {
      memcpy((void*) &tmpExitJmp, (void*) &csound->exitjmp, sizeof(jmp_buf));
      if ((err = setjmp(csound->exitjmp)) != 0) {
        memcpy((void*) &csound->exitjmp, (void*) &tmpExitJmp, sizeof(jmp_buf));
        print_module_error(csound, Str("Error in pre-initialisation function "
                                       "of module '%s'"), fname, NULL, 0);
        return (err == (CSOUND_EXITJMP_SUCCESS + CSOUND_MEMORY) ?
                CSOUND_MEMORY : CSOUND_INITIALIZATION);
      }
      err = m.PreInitFunc(csound);
      memcpy((void*) &csound->exitjmp, (void*) &tmpExitJmp, sizeof(jmp_buf));
      if (UNLIKELY(err != 0)) {
        print_module_error(csound, Str("Error in pre-initialisation function "
                                       "of module '%s'"), fname, &m, err);
        return CSOUND_INITIALIZATION;
      }
    }
    /* plugin was loaded successfully */
    return CSOUND_SUCCESS;
}

static int csoundCheckOpcodeDeny(CSOUND * csound, const char *fname)
{
    /* Check to see if the fname is on the do-not-load list */
    char buff[256];
    char *th;
    char *p, *deny;
    char *list = getenv("CS_OMIT_LIBS");
    /* printf("DEBUG %s(%d): check fname=%s\n", __FILE__, __LINE__, fname); */
    /* printf("DEBUG %s(%d): list %s\n", __FILE__, __LINE__, list); */
    if (list==NULL) return 0;
    strNcpy(buff, fname, 255); //buff[255]='\0';
    strrchr(buff, '.')[0] = '\0'; /* Remove .so etc */
    p = cs_strdup(csound, list);
    deny = cs_strtok_r(p, ",", &th);
    /* printf("DEBUG %s(%d): check buff=%s\n", __FILE__, __LINE__, deny); */
    while (deny) {
      /* printf("DEBUG %s(%d): deny=%s\n", __FILE__, __LINE__, deny); */
      if (strcmp(deny, buff)==0) {
        csound->Free(csound, p);
        /* printf("DEBUG %s(%d): found\n", __FILE__, __LINE__); */
        return 1;
      }
      deny = cs_strtok_r(NULL, ",", &th);
    }
    csound->Free(csound, p);
    /* printf("DEBUG %s(%d): not found\n", __FILE__, __LINE__); */
    return 0;
}


static int _dir_exists(char *path) {
    // returns 1 if path is a directory and it exists
    struct stat s;
    int err = stat(path, &s);
    return (err == 0 && S_ISDIR(s.st_mode)) ? 1 : 0;
}


/**
 * Load plugin libraries for Csound instance 'csound', and call
 * pre-initialisation functions.
 * Return value is CSOUND_SUCCESS if there was no error, CSOUND_ERROR if
 * some modules could not be loaded or initialised, and CSOUND_MEMORY
 * if a memory allocation failure has occured.
 */
int csoundLoadModules(CSOUND *csound)
{
#if (defined(HAVE_DIRENT_H) && (TARGET_OS_IPHONE == 0))
    DIR *dir;
    struct dirent *f;
    const char *dname, *fname;
    enum { searchpath_buflen = 2048, buflen = 1024 };
    char buf[buflen];
    int i, n, len, err = CSOUND_SUCCESS;
    char *dname1, *end;
    int read_directory = 1;
    char searchpath_buf[searchpath_buflen];
    char sep =
#ifdef WIN32
    ';';
#else
    ':';
#endif
#ifdef __HAIKU__
        int dfltdir = 0;
#endif

    if (UNLIKELY(csound->csmodule_db != NULL))
      return CSOUND_ERROR;

    /* open plugin directory */
    dname = csoundGetEnv(csound, (sizeof(MYFLT) == sizeof(float) ?
                                  plugindir_envvar : plugindir64_envvar));
    if (dname == NULL) {
#if ENABLE_OPCODEDIR_WARNINGS
      csound->opcodedirWasOK = 0;
#  ifdef USE_DOUBLE
      dname = csoundGetEnv(csound, plugindir_envvar);
      if (dname == NULL)
#  endif
#endif
#ifdef  CS_DEFAULT_PLUGINDIR
        dname = CS_DEFAULT_PLUGINDIR;
  #ifdef __HAIKU__
        dfltdir = 1;
  #endif
#else
      dname = "";
#endif
    }

    /* opcodedir GLOBAL override **experimental** */
    if (csound->opcodedir != NULL) {
      dname = csound->opcodedir;
      csound->Message(csound, "OPCODEDIR overridden to %s \n", dname);
    }
    size_t pos = strlen(dname);
    char *userplugindir = getenv("CS_USER_PLUGINDIR");
    // The user set a search path for plugins via an env variable. Paths here
    // should be absolute and should not need variable expansion
    if(userplugindir != NULL) {
      snprintf(searchpath_buf, searchpath_buflen, "%s%c%s", dname, sep, userplugindir);
      dname = searchpath_buf;
    } else {
#ifdef CS_DEFAULT_USER_PLUGINDIR
      // Use default user path
      // In this case, userplugindir is a relative path to a prefix wich needs
      // to be expanded
      userplugindir = CS_DEFAULT_USER_PLUGINDIR;

#if defined(LINUX) || defined(__MACH__)
      char *prefix = getenv("HOME");
#elif defined(WIN32)
      char *prefix = getenv("LOCALAPPDATA");
#endif
      // VL: need to check so we don't get a segfault with NULL strings
      size_t prefixlen = prefix ? strlen(prefix) : 0;
      size_t userplugindirlen = userplugindir ? strlen(userplugindir) : 0;

      if(pos + prefixlen + 2 > searchpath_buflen - 1) {
        csound->ErrorMsg(csound, Str("Plugins search path too long\n"));
      } else if(userplugindirlen + prefixlen + 1 >= buflen) {
        csound->ErrorMsg(csound, Str("User plugin dir too long\n"));
      } else {
      
        snprintf(buf, buflen, "%s/%s", prefix, userplugindir);
        if(_dir_exists(buf)) {
          snprintf(searchpath_buf, searchpath_buflen, "%s%c%s", dname, sep, buf);
          dname = searchpath_buf;
        }
      }
#endif
    }
 
    if(UNLIKELY(csound->oparms->odebug))
      csound->Message(csound, Str("Plugins search path: %s\n"), dname);

    /* We now loop through the directory list */
    while(read_directory) {
      /* find separator */
    if((end = strchr(dname, sep)) != NULL) {
      *end = '\0';
      /* copy directory name */
      dname1 = cs_strdup(csound, (char *) dname);

      *end = sep;  /* restore for re-execution */
      /* move to next directory name */
      dname = end + 1;

    } else {
      /* copy last directory name) */
      dname1 = cs_strdup(csound, (char *) dname);
      read_directory = 0;
    }

    /* protect for the case where there is an
       extra separator at the end */
    if(*dname1 == '\0') {
      csound->Free(csound, dname1);
      break;
    }
    dir = opendir(dname1);
    if (UNLIKELY(dir == (DIR*) NULL)) {
 #if defined(__HAIKU__)
        if(!dfltdir)
 #endif
      csound->Warning(csound, Str("Error opening plugin directory '%s': %s"),
                               dname1, strerror(errno));
      csound->Free(csound, dname1);
      continue;
    }
    if(UNLIKELY(csound->oparms->odebug))
      csound->Message(csound, "Opening plugin directory: %s\n", dname1);
    /* load database for deferred plugin loading */
/*     n = csoundLoadOpcodeDB(csound, dname); */
/*     if (n != 0) */
/*       return n; */
    /* scan all files in directory */
    while ((f = readdir(dir)) != NULL) {
      fname = &(f->d_name[0]);
      if (UNLIKELY(fname[0]=='_')) continue;
      n = len = (int) strlen(fname);
      if (UNLIKELY(fname[0]=='_')) continue;
#if defined(WIN32)
      strcpy(buf, "dll");
      n -= 4;
#elif defined(__MACH__)
      strcpy(buf, "dylib");
      n -= 6;
#else
      strcpy(buf, "so");
      n -= 3;
#endif
      if (n <= 0 || fname[n] != '.')
        continue;
      i = 0;
      do {
        if (UNLIKELY((fname[++n] | (char) 0x20) != buf[i]))
          break;
      } while (buf[++i] != '\0');
      if (buf[i] != '\0')
        continue;
      /* found a dynamic library, attempt to open it */
      if (UNLIKELY(((int) strlen(dname) + len + 2) > 1024)) {
        csound->Warning(csound, Str("path name too long, skipping '%s'"),
                                fname);
        continue;
      }
      /* printf("DEBUG %s(%d): possibly deny %s\n", __FILE__, __LINE__,fname); */
      if (UNLIKELY(csoundCheckOpcodeDeny(csound, fname))) {
        csoundWarning(csound, Str("Library %s omitted\n"), fname);
        continue;
      }

      snprintf(buf, 1024, "%s%c%s", dname1, DIRSEP, fname);

      if (UNLIKELY(csound->oparms->odebug)) {
        csoundMessage(csound, Str("Loading '%s'\n"), buf);
       }
      n = csoundLoadExternal(csound, buf);
      if (UNLIKELY(UNLIKELY(n == CSOUND_ERROR)))
        continue;               /* ignore non-plugin files */
      if (UNLIKELY(n < err))
        err = n;                /* record serious errors */
    }
    closedir(dir);
    csound->Free(csound, dname1);
    }
    return (err == CSOUND_INITIALIZATION ? CSOUND_ERROR : err);
#else
    return CSOUND_SUCCESS;
#endif  /* HAVE_DIRENT_H */
}


static int cmp_func(const void *p1, const void *p2)
{
    return (strcmp(*((const char**) p1), *((const char**) p2)));
}

int csoundLoadExternals(CSOUND *csound)
{
    char    *s, **lst;
    int     i, cnt, err;

    s = csound->dl_opcodes_oplibs;
    if (UNLIKELY(s == NULL || s[0] == '\0'))
      return 0;
    /* IV - Feb 19 2005 */
    csound->dl_opcodes_oplibs = NULL;
    csoundMessage(csound, Str("Loading command-line libraries:\n"));
    cnt = 1;
    i = 0;
    do {
      if (s[i] == ',')
        cnt++;
    } while (s[++i] != '\0');
    lst = (char**) csound->Malloc(csound, sizeof(char*) * cnt);
    i = cnt = 0;
    lst[cnt++] = s;
    do {
      if (s[i] == ',') {
        lst[cnt++] = &(s[i + 1]);
        s[i] = '\0';
      }
    } while (s[++i] != '\0');
    qsort((void*) lst, (size_t) cnt, sizeof(char*), cmp_func);
    i = 0;
    do {
      char  *fname = lst[i];
      if (fname[0] != '\0' && !(i && strcmp(fname, lst[i - 1]) == 0)) {
        err = csoundLoadExternal(csound, fname);
        if (UNLIKELY(err == CSOUND_INITIALIZATION || err == CSOUND_MEMORY))
          csoundDie(csound, Str(" *** error loading '%s'"), fname);
        else if (!err)
          csoundMessage(csound, "  %s\n", fname);
      }
    } while (++i < cnt);
    /* file list is no longer needed */
    csound->Free(csound, lst);
    csound->Free(csound, s);
    return 0;
}

/**
 * Call initialisation functions of all loaded modules that have a
 * csoundModuleInit symbol, for Csound instance 'csound'.
 * Return value is CSOUND_SUCCESS if there was no error, and CSOUND_ERROR if
 * some modules could not be initialised.
 */

int csoundInitModules(CSOUND *csound)
{
    csoundModule_t  *m;
    int             i, retval = CSOUND_SUCCESS;
    /* For regular Csound, init_static_modules is not compiled or called.
     * For some builds of Csound, e.g. for PNaCl, init_static_modules is
     * compiled and called to initialize statically linked opcodes and other
     * plugins that are dynamically loaded on other platforms.
     */
#if defined(INIT_STATIC_MODULES)
    retval = init_static_modules(csound);
#endif
    /* call init functions */
    for (m = (csoundModule_t*) csound->csmodule_db; m != NULL; m = m->nxt) {
      i = csoundInitModule(csound, m);
      if (UNLIKELY(i != CSOUND_SUCCESS && i < retval))
        retval = i;
    }
    /* return with error code */
    return retval;
}

/* load a plugin library and also initialise it */
/* called on deferred loading of opcode plugins */

int csoundLoadAndInitModule(CSOUND *csound, const char *fname)
{
    volatile jmp_buf  tmpExitJmp;
    volatile int      err;

    err = csoundLoadExternal(csound, fname);
    if (UNLIKELY(err != 0))
      return err;
    memcpy((void*) &tmpExitJmp, (void*) &csound->exitjmp, sizeof(jmp_buf));
    if (UNLIKELY((err = setjmp(csound->exitjmp)) != 0)) {
      memcpy((void*) &csound->exitjmp, (void*) &tmpExitJmp, sizeof(jmp_buf));
      return (err == (CSOUND_EXITJMP_SUCCESS + CSOUND_MEMORY) ?
              CSOUND_MEMORY : CSOUND_INITIALIZATION);
    }
    /* NOTE: this depends on csound->csmodule_db being the most recently */
    /* loaded plugin library */

    err = csoundInitModule(csound, (csoundModule_t*) csound->csmodule_db);
    memcpy((void*) &csound->exitjmp, (void*) &tmpExitJmp, sizeof(jmp_buf));

    return err;
}

int csoundLoadAndInitModules(CSOUND *csound, const char *opdir)
{
#if (defined(HAVE_DIRENT_H) && (TARGET_OS_IPHONE == 0))
    DIR             *dir;
    struct dirent   *f;
    const char      *dname, *fname;
    char            buf[1024];
    int             i, n, len, err = CSOUND_SUCCESS;
    char            *dname1, *end;
    int             read_directory = 1;
    char sep =
#ifdef WIN32
    ';';
#else
    ':';
#endif
#ifdef __HAIKU__
        int dfltdir = 0;
#endif
        // VL: check is not wanted
        //if (UNLIKELY(csound->csmodule_db != NULL))
        ///return CSOUND_ERROR;

    /* open plugin directory */
    // EM'2021: This seems to be dead code since opdir will never be NULL and
    // the value of dname will be discarded, see "dname = opdir" later
    dname = csoundGetEnv(csound, (sizeof(MYFLT) == sizeof(float) ?
                                  plugindir_envvar : plugindir64_envvar));
    if (dname == NULL) {
#if ENABLE_OPCODEDIR_WARNINGS
      csound->opcodedirWasOK = 0;
#  ifdef USE_DOUBLE
      dname = csoundGetEnv(csound, plugindir_envvar);
      if (dname == NULL)
#  endif
#endif
#ifdef  CS_DEFAULT_PLUGINDIR
        dname = CS_DEFAULT_PLUGINDIR;
 #ifdef __HAIKU__
                dfltdir = 1;
 #endif
#else
      dname = "";
#endif
    }

    if (opdir != NULL) {
      dname = opdir;
    }

    /* We now loop through the directory list */
    while(read_directory) {
      /* find separator */
    if((end = strchr(dname, sep)) != NULL) {
      *end = '\0';
      /* copy directory name */
      dname1 = cs_strdup(csound, (char *) dname);
      *end = sep;  /* restore for re-execution */
      /* move to next directory name */
      dname = end + 1;
    } else {
      /* copy last directory name) */
      dname1 = cs_strdup(csound, (char *) dname);
      read_directory = 0;
    }

    /* protect for the case where there is an
       extra separator at the end */
    if(*dname1 == '\0') {
      csound->Free(csound, dname1);
      break;
    }

    dir = opendir(dname1);
    if (UNLIKELY(dir == (DIR*) NULL)) {
 #if defined(__HAIKU__)
        if(!dfltdir)
 #endif
      csound->Warning(csound, Str("Error opening plugin directory '%s': %s"),
                               dname1, strerror(errno));
      csound->Free(csound, dname1);
      continue;
    }

    if(UNLIKELY(csound->oparms->odebug))
      csound->Message(csound, "Opening plugin directory: %s\n", dname1);
    /* load database for deferred plugin loading */
/*     n = csoundLoadOpcodeDB(csound, dname); */
/*     if (n != 0) */
/*       return n; */
    /* scan all files in directory */
    while ((f = readdir(dir)) != NULL) {
      fname = &(f->d_name[0]);
      if (UNLIKELY(fname[0]=='_')) continue;
      n = len = (int) strlen(fname);
      if (UNLIKELY(fname[0]=='_')) continue;
#if defined(WIN32)
      strcpy(buf, "dll");
      n -= 4;
#elif defined(__MACH__)
      strcpy(buf, "dylib");
      n -= 6;
#else
      strcpy(buf, "so");
      n -= 3;
#endif
      if (n <= 0 || fname[n] != '.')
        continue;
      i = 0;
      do {
        if (UNLIKELY((fname[++n] | (char) 0x20) != buf[i]))
          break;
      } while (buf[++i] != '\0');
      if (buf[i] != '\0')
        continue;
      /* found a dynamic library, attempt to open it */
      if (UNLIKELY(((int) strlen(dname) + len + 2) > 1024)) {
        csound->Warning(csound, Str("path name too long, skipping '%s'"),
                                fname);
        continue;
      }
      /* printf("DEBUG %s(%d): possibly deny %s\n", __FILE__, __LINE__,fname); */
      if (UNLIKELY(csoundCheckOpcodeDeny(csound, fname))) {
        csoundWarning(csound, Str("Library %s omitted\n"), fname);
        continue;
      }
      snprintf(buf, 1024, "%s%c%s", dname1, DIRSEP, fname);
      if (UNLIKELY(csound->oparms->odebug)) {
        csoundMessage(csound, Str("Loading '%s'\n"), buf);
       }
      n = csoundLoadAndInitModule(csound, buf);
      if (UNLIKELY(UNLIKELY(n == CSOUND_ERROR)))
        continue;               /* ignore non-plugin files */
      if (UNLIKELY(n < err))
        err = n;                /* record serious errors */
    }
    closedir(dir);
    csound->Free(csound, dname1);
    }
    return (err == CSOUND_INITIALIZATION ? CSOUND_ERROR : err);
#else
    return CSOUND_SUCCESS;
#endif  /* HAVE_DIRENT_H */
}

/**
 * Call destructor functions of all loaded modules that have a
 * csoundModuleDestroy symbol, for Csound instance 'csound'.
 * Return value is CSOUND_SUCCESS if there was no error, and
 * CSOUND_ERROR if some modules could not be de-initialised.
 */
extern int sfont_ModuleDestroy(CSOUND *csound);
int csoundDestroyModules(CSOUND *csound)
{
    csoundModule_t  *m;
    int             i, retval;

    retval = CSOUND_SUCCESS;
    while (csound->csmodule_db != NULL) {

      m = (csoundModule_t*) csound->csmodule_db;
      /* call destructor functions */
      if (m->PreInitFunc != NULL && m->fn.p.DestFunc != NULL) {
        i = m->fn.p.DestFunc(csound);
        if (UNLIKELY(i != 0)) {
          print_module_error(csound, Str("Error de-initialising module '%s'"),
                                     &(m->name[0]), m, i);
          retval = CSOUND_ERROR;
        }
      }
      /* unload library */
      csoundCloseLibrary(m->h);
      csound->csmodule_db = (void*) m->nxt;
      /* free memory used by database */
      csound->Free(csound, (void*) m);

    }
    sfont_ModuleDestroy(csound);
    /* return with error code */
    return retval;
}

#endif /* __wasi__ */

 /* ------------------------------------------------------------------------ */

#if defined(WIN32)

PUBLIC int csoundOpenLibrary(void **library, const char *libraryPath)
{
    *library = (void*) LoadLibrary(libraryPath);
    return (*library != NULL ? 0 : -1);
}

PUBLIC int csoundCloseLibrary(void *library)
{
    return (int) (FreeLibrary((HMODULE) library) == FALSE ? -1 : 0);
}

PUBLIC void *csoundGetLibrarySymbol(void *library, const char *procedureName)
{
    return (void*) GetProcAddress((HMODULE) library, procedureName);
}

#elif !(defined(NACL)) && !(defined(__wasi__)) && (defined(LINUX) || defined(NEW_MACH_CODE) || defined(__HAIKU__))

PUBLIC int csoundOpenLibrary(void **library, const char *libraryPath)
{
    int flg = RTLD_NOW;
    if (libraryPath != NULL) {
      int len = (int) strlen(libraryPath);
      /* ugly hack to fix importing modules in Python opcodes */
      if (len >= 9 && strcmp(&(libraryPath[len - 9]), "/libpy.so") == 0)
        flg |= RTLD_GLOBAL;
      if (len >= 12 && strcmp(&(libraryPath[len - 12]), "/libpy.dylib") == 0)
        flg |= RTLD_GLOBAL;
    }
    *library = (void*) dlopen(libraryPath, flg);
    return (*library != NULL ? 0 : -1);
}

PUBLIC int csoundCloseLibrary(void *library)
{
    return (int) dlclose(library);
}

PUBLIC void *csoundGetLibrarySymbol(void *library, const char *procedureName)
{
    return (void*) dlsym(library, procedureName);
}

#else /* case for platforms without shared libraries -- added 062404, akozar */

int csoundOpenLibrary(void **library, const char *libraryPath)
{
    *library = NULL;
    return -1;
}

int csoundCloseLibrary(void *library)
{
    return 0;
}

void *csoundGetLibrarySymbol(void *library, const char *procedureName)
{
    return NULL;
}

#endif

#if ENABLE_OPCODEDIR_WARNINGS
static const char *opcodedirWarnMsg[] = {
    "################################################################",
#ifndef USE_DOUBLE
    "#               WARNING: OPCODE6DIR IS NOT SET !               #",
#else
    "#              WARNING: OPCODE6DIR64 IS NOT SET !              #",
#endif
    "# Csound requires this environment variable to be set to find  #",
    "# its plugin libraries. If it is not set, you may experience   #",
    "# missing opcodes, audio/MIDI drivers, or utilities.           #",
    "################################################################",
    NULL
};
#endif

void print_opcodedir_warning(CSOUND *p)
{
#if ENABLE_OPCODEDIR_WARNINGS
    if (!p->opcodedirWasOK) {
      const char  **sp;
      for (sp = &(opcodedirWarnMsg[0]); *sp != NULL; sp++)
        p->MessageS(p, CSOUNDMSG_WARNING, "        %s\n", Str(*sp));
    }
#else
    (void) p;
#endif
}

/**
 Builtin linkage for C opcodes - Instructions:
 - use csoundCore.h instead of csdl.h.
 - name the OENTRY array <name>, where <name> is any arbitrary name.
 - add the macro LINKAGE_BUILTIN(<name>) to the end of the file.
 - append the init function prototype below
   extern int64_t <name>_init(CSOUND *, void *);
 - append the init function name <name>_init to the
   staticmodules[] array initialisation.
 - insert source code to libcsound_SRCS in../CMakeLists.txt
*/

typedef int32_t (*INITFN)(CSOUND *, void *);

extern int32_t babo_localops_init(CSOUND *, void *);
extern int32_t bilbar_localops_init(CSOUND *, void *);
extern int32_t compress_localops_init(CSOUND *, void *);
extern int32_t pvsbuffer_localops_init(CSOUND *, void *);
extern int32_t vosim_localops_init(CSOUND *, void *);
extern int32_t eqfil_localops_init(CSOUND *, void *);
extern int32_t modal4_localops_init(CSOUND *, void *);
extern int32_t scoreline_localops_init(CSOUND *, void *);
extern int32_t physmod_localops_init(CSOUND *, void *);
extern int32_t modmatrix_localops_init(CSOUND *, void *);
extern int32_t spectra_localops_init(CSOUND *, void *);
extern int32_t ambicode1_localops_init(CSOUND *, void *);
extern int32_t grain4_localops_init(CSOUND *, void *);
extern int32_t hrtferX_localops_init(CSOUND *, void *);
extern int32_t loscilx_localops_init(CSOUND *, void *);
extern int32_t pan2_localops_init(CSOUND *, void *);
extern int32_t arrayvars_localops_init(CSOUND *, void *);
extern int32_t phisem_localops_init(CSOUND *, void *);
extern int32_t pvoc_localops_init(CSOUND *, void *);
extern int32_t hrtfopcodes_localops_init(CSOUND *, void *);
extern int32_t hrtfreverb_localops_init(CSOUND *, void *);
extern int32_t hrtfearly_localops_init(CSOUND *, void *);
extern int32_t minmax_localops_init(CSOUND *, void *);
extern int32_t gendy_localops_init(CSOUND *, void *);
extern int32_t vbap_localops_init(CSOUND *, void *);
extern int32_t vaops_localops_init(CSOUND *, void*);
extern int32_t ugakbari_localops_init(CSOUND *, void *);
extern int32_t harmon_localops_init(CSOUND *, void *);
extern int32_t pitchtrack_localops_init(CSOUND *, void *);
extern int32_t squinewave_localops_init(CSOUND *, void *);

extern int32_t partikkel_localops_init(CSOUND *, void *);
extern int32_t shape_localops_init(CSOUND *, void *);
extern int32_t tabaudio_localops_init(CSOUND *, void *);
extern int32_t tabsum_localops_init(CSOUND *, void *);
extern int32_t crossfm_localops_init(CSOUND *, void *);
extern int32_t pvlock_localops_init(CSOUND *, void *);
extern int32_t fareyseq_localops_init(CSOUND *, void *);
extern int32_t cpumeter_localops_init(CSOUND *, void *);
extern int32_t scnoise_localops_init(CSOUND *, void *);
extern int32_t socksend_localops_init(CSOUND *, void *);
extern int32_t mp3in_localops_init(CSOUND *, void *);
extern int32_t sockrecv_localops_init(CSOUND *, void *);
extern int32_t afilts_localops_init(CSOUND *, void *);
extern int32_t pinker_localops_init(CSOUND *, void *);
extern int32_t paulstretch_localops_init(CSOUND *, void *);
extern int32_t wpfilters_localops_init(CSOUND *, void *);
extern int32_t zak_localops_init(CSOUND *, void *);
extern int32_t lufs_localops_init(CSOUND *, void *);
extern int32_t sterrain_localops_init(CSOUND *, void *);
extern int32_t date_localops_init(CSOUND *, void *);
extern int32_t system_localops_init(CSOUND *, void *);
extern int32_t liveconv_localops_init(CSOUND *, void *);
extern int32_t gamma_localops_init(CSOUND *, void *);
extern int32_t quadbezier_localops_init(CSOUND *, void *);
extern int32_t framebuffer_localops_init(CSOUND *, void *);
extern int32_t cell_localops_init(CSOUND *, void *);
extern int32_t exciter_localops_init(CSOUND *, void *);
extern int32_t buchla_localops_init(CSOUND *, void *);
extern int32_t select_localops_init(CSOUND *, void *);
extern int32_t serial_localops_init(CSOUND *, void *);
extern int32_t counter_localops_init(CSOUND *, void *);
extern int32_t platerev_localops_init(CSOUND *, void *);
extern int32_t sequencer_localops_init(CSOUND *, void *);
extern int32_t pvsgendy_localops_init(CSOUND *, void *);
extern int32_t scugens_localops_init(CSOUND *, void *);
extern int32_t emugens_localops_init(CSOUND *, void *);

extern int32_t stdopc_ModuleInit(CSOUND *csound);
extern int32_t pvsopc_ModuleInit(CSOUND *csound);
extern int32_t sfont_ModuleInit(CSOUND *csound);
extern int32_t sfont_ModuleCreate(CSOUND *csound);
extern int32_t newgabopc_ModuleInit(CSOUND *csound);

const INITFN staticmodules[] = { hrtfopcodes_localops_init, babo_localops_init,
                                 bilbar_localops_init, vosim_localops_init,
                                 compress_localops_init, pvsbuffer_localops_init,
                                 eqfil_localops_init, modal4_localops_init,
                                 scoreline_localops_init, physmod_localops_init,
                                 modmatrix_localops_init, spectra_localops_init,
                                 ambicode1_localops_init, grain4_localops_init,
                                 hrtferX_localops_init, loscilx_localops_init,
                                 pan2_localops_init, arrayvars_localops_init,
                                 phisem_localops_init, pvoc_localops_init,
                                 vbap_localops_init,
                                 ugakbari_localops_init, harmon_localops_init,
                                 pitchtrack_localops_init, partikkel_localops_init,
                                 shape_localops_init, tabsum_localops_init,
                                 crossfm_localops_init, pvlock_localops_init,
                                 fareyseq_localops_init, hrtfearly_localops_init,
                                 hrtfreverb_localops_init, minmax_localops_init,
                                 vaops_localops_init, paulstretch_localops_init,
                                 squinewave_localops_init, tabaudio_localops_init,
#ifdef LINUX
                                 cpumeter_localops_init,
#endif

#if !(defined(NACL)) && !(defined(__wasi__))
                                 counter_localops_init,
                                 sockrecv_localops_init,
                                 socksend_localops_init,
                                 system_localops_init,
                                 serial_localops_init,
                                 mp3in_localops_init,
#endif
                                 scnoise_localops_init, afilts_localops_init,
                                 pinker_localops_init, gendy_localops_init,
                                 wpfilters_localops_init, zak_localops_init,
                                 lufs_localops_init, sterrain_localops_init,
                                 date_localops_init,
                                 liveconv_localops_init, gamma_localops_init,
                                 framebuffer_localops_init, cell_localops_init,
                                 exciter_localops_init, buchla_localops_init,
                                 select_localops_init,
                                 platerev_localops_init,
                                 pvsgendy_localops_init, scugens_localops_init,
                                 emugens_localops_init, sequencer_localops_init,
                                 NULL };

/**
 Builtin linkage for C fgens - Instructions:
 - use csoundCore.h instead of csdl.h.
 - name the NGFENS array <name>, where <name> is any arbitrary name.
 - add the macro FLINKAGE_BUILTIN(<name>) to the end of the file.
 - append the init function prototype below
   NGFENS* <name>_init(CSOUND *);
 - append the init function name <name>_init to the
   ftgenab[] array initialisation.
 - insert source code to libcsound_SRCS in../CMakeLists.txt
*/
typedef NGFENS* (*FGINITFN)(CSOUND *);

NGFENS *ftest_fgens_init(CSOUND *);
NGFENS *farey_fgens_init(CSOUND *);

const FGINITFN fgentab[] = {  ftest_fgens_init, farey_fgens_init, NULL };

CS_NOINLINE int csoundInitStaticModules(CSOUND *csound)
{
    int     i;
    OENTRY  *opcodlst_n;
    int32_t length;

    for (i=0; staticmodules[i]!=NULL; i++) {
      length = (staticmodules[i])(csound, &opcodlst_n);

      if (UNLIKELY(length <= 0L)) return CSOUND_ERROR;
      length /= (int32_t) sizeof(OENTRY);
      if (length) {
        if (UNLIKELY(csoundAppendOpcodes(csound, opcodlst_n, length) != 0))
          return CSOUND_ERROR;
      }
    }
    /* stdopc module */
    if (UNLIKELY(stdopc_ModuleInit(csound))) return CSOUND_ERROR;

    /* pvs module */
    if (UNLIKELY(pvsopc_ModuleInit(csound))) return CSOUND_ERROR;

    /* sfont module */
    sfont_ModuleCreate(csound);
    if (UNLIKELY(sfont_ModuleInit(csound))) return CSOUND_ERROR;

    /* newgabopc */
    if (UNLIKELY(newgabopc_ModuleInit(csound))) return CSOUND_ERROR;

    /* modules were initialised successfully */
    /* Now fgens */
    for (i = 0; fgentab[i]!=NULL; i++) {
      int j;
      NGFENS  *names = (fgentab[i])(csound);
      for (j = 0; names[j].name != NULL; j++)
        allocgen(csound, names[j].name, names[j].fn);
    }
    return CSOUND_SUCCESS;
}