forked from Taiko2k/Tauon
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphazor.c
More file actions
3707 lines (3034 loc) · 88.7 KB
/
phazor.c
File metadata and controls
3707 lines (3034 loc) · 88.7 KB
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
// PHAzOR - Audio playback module for Tauon Music Box
//
// Copyright © 2020, Taiko2k captain(dot)gxj(at)gmail.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#if __STDC_VERSION__ < 201710L
#pragma message("Current __STDC_VERSION__ value: " TOSTRING(__STDC_VERSION__))
#error "Phazor requires C17 or later."
#endif
#if __STDC_VERSION__ < 202311L
#pragma message("Note: C23 not supported! Current __STDC_VERSION__ value: " TOSTRING(__STDC_VERSION__))
// #error "Phazor requires C23 or later."
#endif
#define MINI
#ifdef WIN64
#include <windows.h>
#ifndef __MINGW64__
#define usleep(usec) Sleep((usec) / 1000) // Convert microseconds to milliseconds
#endif
#else
#include <unistd.h>
#endif
#ifdef PIPE
#undef MINI
#endif
//#define MINI
#ifdef PIPE
#include <pipewire/pipewire.h>
#include <spa/param/audio/format-utils.h>
#include <spa/pod/builder.h>
#include <spa/utils/result.h>
#endif
#define _GNU_SOURCE
// C23 has it by default
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#include <time.h>
#ifdef MINI
#define MINIAUDIO_IMPLEMENTATION
#define MA_NO_GENERATION
#define MA_NO_DECODING
#define MA_NO_ENCODING
#define MA_ENABLE_ONLY_SPECIFIC_BACKENDS
#define MA_ENABLE_WASAPI
#define MA_ENABLE_PULSEAUDIO
#define MA_ENABLE_COREAUDIO
#define MA_ENABLE_OSS
#define MA_ENABLE_SNDIO
#define MA_ENABLE_AUDIO4
//#define MA_DEBUG_OUTPUT
#include "miniaudio/miniaudio.h"
#endif
#include <FLAC/stream_decoder.h>
#include <mpg123.h>
#include "vorbis/codec.h"
#include "vorbis/vorbisfile.h"
#include "opus/opusfile.h"
#include <sys/stat.h>
#include <samplerate.h>
#include <libopenmpt/libopenmpt.h>
#include <libopenmpt/libopenmpt_stream_callbacks_file.h>
#include "kissfft/kiss_fftr.h"
#include "wavpack/wavpack.h"
#include "gme/gme.h"
#include <Python.h>
// Module method definitions (if any)
static PyMethodDef PhazorMethods[] = {
{NULL, NULL, 0, NULL} // Sentinel
};
// Module definition
static struct PyModuleDef phazor_module = {
PyModuleDef_HEAD_INIT,
"phazor", // Module name
NULL, // Module documentation (may be NULL)
-1, // Size of per-interpreter state of the module
PhazorMethods // Methods table
};
#ifdef WIN64
__declspec(dllexport)
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
enum logtypes {LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_CRITICAL, LOG_DEBUG};
static void log_msg(int type, const char *fmt, ...) {
PyGILState_STATE gstate = PyGILState_Ensure();
static PyObject *logging = NULL;
// import logging module on demand
if (logging == NULL){
logging = PyImport_ImportModule("logging");
if (logging == NULL) {
PyErr_SetString(
PyExc_ImportError,
"Could not import module 'logging'"
);
PyGILState_Release(gstate);
return;
}
}
/* format message */
char buffer[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, args);
va_end(args);
PyObject *py_msg = PyUnicode_FromString(buffer);
const char *method = NULL;
switch (type) {
case LOG_INFO: method = "info"; break;
case LOG_WARNING: method = "warning"; break;
case LOG_ERROR: method = "error"; break;
case LOG_CRITICAL: method = "critical"; break;
case LOG_DEBUG: method = "debug"; break;
default: method = "info"; break;
}
PyObject_CallMethod(logging, method, "O", py_msg);
Py_DECREF(py_msg);
PyGILState_Release(gstate);
}
// Entry point for the module
PyMODINIT_FUNC PyInit_phazor(void) {
return PyModule_Create(&phazor_module);
}
#define BUFF_SIZE 240000 // Decoded data buffer size
#define BUFF_SAFE 100000 // Ensure there is this much space free in the buffer
#define VIS_SIDE_MAX 10000
float vis_side_buffer[VIS_SIDE_MAX];
int vis_side_fill = 0;
double t_start, t_end;
bool out_thread_running = false;
bool called_to_stop_device = false;
bool device_stopped = false;
bool signaled_device_unavailable = false;
bool pulse_connected = false;
static volatile bool pw_need_restart = false;
static volatile bool pw_running = false;
float fadefl[BUFF_SIZE];
float fadefr[BUFF_SIZE];
int16_t temp16l[BUFF_SIZE];
int16_t temp16r[BUFF_SIZE];
float re_in[BUFF_SIZE * 2];
float re_out[BUFF_SIZE * 2];
int fade_fill = 0;
bool fade_lockout = false;
float fade_mini = 0.0;
int fade_position = 0;
int fade_2_flag = 0;
pthread_mutex_t buffer_mutex;
pthread_mutex_t fade_mutex;
//pthread_mutex_t pulse_mutex;
float out_buff[2048 * 2];
//#ifdef AO
// char out_buffc[2048 * 4];
// int32_t temp32 = 0;
//#endif
int position_count = 0;
int current_length_count = 0;
int sample_rate_out = 44100;
int sample_rate_src = 0;
int src_channels = 2;
int current_sample_rate = 0;
int want_sample_rate = 0;
int sample_change_byte = 0;
bool reset_set = false;
int reset_set_value = 0;
int reset_set_byte = 0;
int rg_byte = 0;
float rg_value_want = 0.0;
char load_target_file[4096]; // 4069 bytes for max linux filepath
char loaded_target_file[4096] = ""; // 4069 bytes for max linux filepath
unsigned int load_target_seek = 0;
unsigned int next_ready = 0;
unsigned int seek_request_ms = 0;
int subtrack = 0;
float volume_want = 1.0;
float volume_on = 1.0;
float volume_ramp_speed = 750; // ms for 1 to 0
/* int active_latency = 0; */
int codec = 0;
int error = 0;
float peak_l = 0.;
float peak_roll_l = 0.;
float peak_r = 0.;
float peak_roll_r = 0.;
float gate = 1.0; // Used for ramping
int config_fast_seek = 0;
int config_dev_buffer = 80;
int config_fade_jump = 1;
char config_output_sink[256]; // 256 just a conservative guess
int config_fade_duration = 700;
int config_resample_quality = 2;
int config_resample = 1;
int config_always_ffmpeg = 0;
int config_volume_power = 2;
int config_feed_samplerate = 48000;
int config_min_buffer = 30000;
#define EQ_BAND_COUNT 10
#define EQ_AUTO_HEADROOM_MARGIN_DB 1.0f
#define LIMITER_THRESHOLD 0.89125093813f // -1 dBFS
#define LIMITER_ATTACK_MS 1.5f
#define LIMITER_RELEASE_MS 120.0f
typedef struct {
float b0;
float b1;
float b2;
float a1;
float a2;
float z1_l;
float z2_l;
float z1_r;
float z2_r;
} eq_biquad_t;
static const float eq_band_freqs[EQ_BAND_COUNT] = {
31.25f, 62.5f, 125.0f, 250.0f, 500.0f, 1000.0f, 2000.0f, 4000.0f, 8000.0f, 16000.0f
};
eq_biquad_t eq_bands[EQ_BAND_COUNT];
float eq_band_gain_db[EQ_BAND_COUNT] = {0};
int eq_enabled = 0;
int eq_active = 0;
int eq_coeff_sample_rate = 0;
bool eq_dirty = true;
float eq_headroom_db = 0.0f;
float eq_headroom_gain = 1.0f;
float limiter_gain = 1.0f;
float limiter_attack_coeff = 0.0f;
float limiter_release_coeff = 0.0f;
int limiter_coeff_sample_rate = 0;
unsigned int test1 = 0;
enum status {
PLAYING,
PAUSED,
STOPPED,
RAMP_DOWN,
ENDING,
};
enum command_status {
NONE,
START,
LOAD, // used internally only
SEEK,
STOP,
PAUSE,
RESUME,
EXIT,
};
enum decoder_types {
UNKNOWN,
FLAC,
MPG,
VORBIS,
OPUS,
FFMPEG,
WAVE,
MPT,
FEED,
WAVPACK,
GME,
};
enum result_status_enum {
WAITING,
SUCCESS,
FAILURE
};
int result_status = WAITING;
int mode = STOPPED;
int command = NONE;
int decoder_allocated = 0;
int buffering = 0;
int flac_got_rate = 0;
FILE *d_file;
#ifdef MINI
ma_context_config c_config;
ma_device_config config;
ma_device device;
#endif
#ifdef PIPE
pthread_t pw_thread;
pthread_mutex_t pipe_devices_mutex;
struct pw_main_loop *loop;
struct pw_context *context;
struct pw_core *core;
struct pw_registry *registry;
struct spa_hook registry_listener;
struct spa_hook core_listener;
struct pw_stream *global_stream;
int enum_done = 0;
int pipe_set_samplerate = 48000;
#define MAX_DEVICES 64
#define POD_BUFFER_SIZE 2048
struct device_info {
uint32_t id;
char name[256];
char description[256];
};
struct pipe_devices_struct {
struct device_info devices[MAX_DEVICES];
int device_count;
};
struct pipe_devices_struct pipe_devices = {0};
static void registry_event_remove_global(void *data, uint32_t id) {
bool removed_active_sink = false;
uint32_t stream_node_id = PW_ID_ANY;
/* Determine the node ID currently used by the stream */
if (global_stream) {
stream_node_id = pw_stream_get_node_id(global_stream);
}
pthread_mutex_lock(&pipe_devices_mutex);
for (size_t i = 0; i < pipe_devices.device_count; i++) {
if (pipe_devices.devices[i].id == id) { // Assuming each device has a unique ID
/* Check if THIS is the active sink */
log_msg(LOG_INFO, "Removed device with ID: %u (%s)", id, pipe_devices.devices[i].description);
if (id == stream_node_id) {
log_msg(LOG_WARNING, "Active sink removed!");
removed_active_sink = true;
}
// Shift remaining devices to fill the gap
for (size_t j = i; j < pipe_devices.device_count - 1; j++) {
pipe_devices.devices[j] = pipe_devices.devices[j + 1];
}
pipe_devices.device_count--;
break;
}
}
pthread_mutex_unlock(&pipe_devices_mutex);
/* IMPORTANT: handle stream loss OUTSIDE the mutex */
if (removed_active_sink && global_stream) {
log_msg(LOG_ERROR, "Active sink removed — disconnecting PipeWire stream");
pw_stream_disconnect(global_stream);
/* Mark output as dead so start_out() will reconnect */
pulse_connected = false;
}
}
static void registry_event_global(
void *data, uint32_t id,
uint32_t permissions, const char *type, uint32_t version,
const struct spa_dict *props)
{
if (props == NULL || type == NULL || !spa_streq(type, PW_TYPE_INTERFACE_Node))
return;
//log_msg(LOG_INFO, "object: id:%u type:%s/%d", id, type, version);
const char *media_class;
media_class = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS);
if (media_class == NULL)
return;
if (spa_streq(media_class, "Audio/Sink")) {
pthread_mutex_lock(&pipe_devices_mutex);
if (pipe_devices.device_count >= MAX_DEVICES) {
log_msg(LOG_ERROR, "Error: Max devices");
pthread_mutex_unlock(&pipe_devices_mutex);
return;
}
const char *name = spa_dict_lookup(props, PW_KEY_NODE_NAME);
const char *description = spa_dict_lookup(props, PW_KEY_NODE_DESCRIPTION);
if (!name || !description) {
log_msg(LOG_ERROR, "Error: Missing name or description for device");
pthread_mutex_unlock(&pipe_devices_mutex);
return;
}
// Check if already added
for (size_t i = 0; i < pipe_devices.device_count; i++) {
if (pipe_devices.devices[i].id == id) {
pthread_mutex_unlock(&pipe_devices_mutex);
return;
}
}
pipe_devices.devices[pipe_devices.device_count].id = id;
snprintf(pipe_devices.devices[pipe_devices.device_count].name, sizeof(pipe_devices.devices[pipe_devices.device_count].name), "%s", name);
snprintf(pipe_devices.devices[pipe_devices.device_count].description, sizeof(pipe_devices.devices[pipe_devices.device_count].description), "%s", description);
pipe_devices.device_count++;
log_msg(LOG_INFO, "Found audio sink: %s (%s)", name, description);
pthread_mutex_unlock(&pipe_devices_mutex);
}
}
static const struct pw_registry_events registry_events = {
PW_VERSION_REGISTRY_EVENTS,
.global = registry_event_global,
.global_remove = registry_event_remove_global,
};
static void on_core_done(void *userdata, uint32_t id, int seq) {
if (id == PW_ID_CORE) {
enum_done = 1;
}
}
static void on_core_error(void *data, uint32_t id, int seq, int res, const char *message) {
log_msg(LOG_ERROR,
"PipeWire core error: id=%u res=%d (%s) msg=%s",
id, res, spa_strerror(res), message ? message : "(null)");
// Mark disconnected so the app can attempt reconnect
pulse_connected = false;
if (res == -EPIPE || res == -ECONNRESET) {
pw_need_restart = true;
if (loop) pw_main_loop_quit(loop);
}
}
static const struct pw_core_events core_events = {
PW_VERSION_CORE_EVENTS,
.done = on_core_done,
.error = on_core_error,
};
#endif
float bfl[BUFF_SIZE];
float bfr[BUFF_SIZE];
int low = 0;
int high = 0;
int high_mark = BUFF_SIZE - BUFF_SAFE;
int watermark = BUFF_SIZE - BUFF_SAFE;
int get_buff_fill() {
if (low <= high) return high - low;
return (watermark - low) + high;
}
void buff_cycle() {
if (high > high_mark) {
watermark = high;
high = 0;
}
if (low >= watermark) low = 0;
}
void buff_reset() {
low = 0;
high = 0;
watermark = high_mark;
}
// Cross-compatibility -------------------------------------------
#ifdef WIN64
static wchar_t *loaded_target_wpath = NULL;
#include <wchar.h>
static wchar_t *utf8_to_wide_path(const char *utf8) {
if (!utf8) return NULL;
// 1) UTF-8 -> wide
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
if (wlen <= 0) return NULL;
wchar_t *wtmp = (wchar_t*)malloc(sizeof(wchar_t) * (size_t)wlen);
if (!wtmp) return NULL;
if (!MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wtmp, wlen)) {
free(wtmp);
return NULL;
}
// 2) Make absolute (required for \\?\)
DWORD abs_len = GetFullPathNameW(wtmp, 0, NULL, NULL);
if (abs_len == 0) {
free(wtmp);
return NULL;
}
wchar_t *abs_path = (wchar_t*)malloc(sizeof(wchar_t) * (size_t)abs_len);
if (!abs_path) {
free(wtmp);
return NULL;
}
DWORD abs_len2 = GetFullPathNameW(wtmp, abs_len, abs_path, NULL);
free(wtmp);
if (abs_len2 == 0 || abs_len2 >= abs_len) {
free(abs_path);
return NULL;
}
// Already prefixed?
if (wcsncmp(abs_path, L"\\\\?\\", 4) == 0) {
return abs_path;
}
// 3) Add long-path prefix only if needed
size_t abs_chars = wcslen(abs_path);
if (abs_chars < MAX_PATH) {
return abs_path;
}
// UNC path: \\server\share\...
if (wcsncmp(abs_path, L"\\\\", 2) == 0) {
// Build: \\?\UNC\ + (abs_path without leading \\)
const wchar_t *tail = abs_path + 2;
size_t tail_len = wcslen(tail);
wchar_t *out = (wchar_t*)malloc(sizeof(wchar_t) * (tail_len + 8 + 1)); // "\\?\UNC\" = 8 chars
if (!out) {
free(abs_path);
return NULL;
}
wcscpy(out, L"\\\\?\\UNC\\");
wcscat(out, tail);
free(abs_path);
return out;
}
// Drive path: C:\...
wchar_t *out = (wchar_t*)malloc(sizeof(wchar_t) * (abs_chars + 4 + 1));
if (!out) {
free(abs_path);
return NULL;
}
wcscpy(out, L"\\\\?\\");
wcscat(out, abs_path);
free(abs_path);
return out;
}
#endif
FILE *uni_fopen(char *ff) {
#ifdef WIN64
wchar_t *wpath = utf8_to_wide_path(ff);
if (!wpath) return NULL;
FILE *f = _wfopen(wpath, L"rb");
free(wpath);
return f;
#else
return fopen(ff, "rb");
#endif
}
#ifdef WIN64
static int uni_stat(const char *path, struct stat *st) {
if (!loaded_target_wpath) return -1;
struct _stat64 wst;
int r = _wstat64(loaded_target_wpath, &wst);
if (r != 0) return r;
st->st_size = (off_t)wst.st_size;
st->st_mtime = wst.st_mtime;
st->st_atime = wst.st_atime;
st->st_ctime = wst.st_ctime;
st->st_mode = wst.st_mode;
return 0;
}
#else
#define uni_stat stat
#endif
// Misc ----------------------------------------------------------
float ramp_step(int sample_rate, int milliseconds) {
return 1.0 / sample_rate / (milliseconds / 1000.0);
}
void fade_fx() {
//pthread_mutex_lock(&fade_mutex);
if (rg_value_want != 0.0 && rg_value_want != 1.0) {
bfr[high] *= rg_value_want;
bfl[high] *= rg_value_want;
if (bfl[high] > 1) bfl[high] = 1;
if (bfl[high] < -1) bfl[high] = -1;
if (bfr[high] > 1) bfr[high] = 1;
if (bfr[high] < -1) bfr[high] = -1;
}
if (fade_mini < 1.0) {
fade_mini += ramp_step(sample_rate_out, 10); // 10ms ramp
bfr[high] *= fade_mini;
bfl[high] *= fade_mini;
if (fade_mini > 1.0) fade_mini = 1.0;
}
if (fade_fill > 0) {
if (fade_fill == fade_position) {
fade_fill = 0;
fade_position = 0;
} else {
fade_lockout = true;
float cross = fade_position / (float) fade_fill;
float cross_i = 1.0 - cross;
bfl[high] *= cross;
bfl[high] += fadefl[fade_position] * cross_i;
bfr[high] *= cross;
bfr[high] += fadefr[fade_position] * cross_i;
fade_position++;
}
}
//pthread_mutex_unlock(&fade_mutex);
}
FILE *fptr;
struct stat st;
off_t load_file_size = 0;
int samples_decoded = 0;
// Secret Rabbit Code --------------------------------------------------
SRC_DATA src_data;
SRC_STATE *src;
// wavpack -----------------------------------
WavpackContext *wpc;
int wp_bit = 0;
int wp_float = 0;
// kiss fft -----------------------------------------------------------
kiss_fft_scalar * rbuf;
kiss_fft_cpx * cbuf;
kiss_fftr_cfg ffta;
// Vorbis related --------------------------------------------------------
OggVorbis_File vf;
vorbis_info vi;
// Opus related ----------------------------------------
OggOpusFile *opus_dec;
int16_t opus_buffer[2048 * 2];
// MP3 related ------------------------------------------------
mpg123_handle *mh;
char parse_buffer[2048 * 2];
// openMPT related ---------------
FILE* mod_file = 0;
openmpt_module* mod = 0;
// GME related -------------------
Music_Emu* emu;
// FFmpeg related -----------------------------------------------------
FILE *ffm;
char exe_string[4096];
char ffm_buffer[2048];
int (*ff_start)(char*, int, int);
int (*ff_read)(char*, int);
void (*ff_close)();
void (*on_device_unavailable)();
void start_ffmpeg(char uri[], int start_ms) {
int status = 0;
if (ff_start != NULL) status = ff_start(uri, start_ms, sample_rate_out);
else {
log_msg(LOG_ERROR, "pa: FFmpeg callback is NULL");
return;
}
if (status != 0) {
log_msg(LOG_ERROR, "pa: Error starting FFmpeg");
return;
}
decoder_allocated = 1;
sample_rate_src = sample_rate_out;
}
void stop_ffmpeg() {
if (ff_close != NULL) ff_close();
}
void resample_to_buffer(int in_frames) {
src_data.data_in = re_in;
src_data.data_out = re_out;
src_data.input_frames = in_frames;
src_data.output_frames = BUFF_SIZE - BUFF_SAFE;
src_data.src_ratio = (double) sample_rate_out / (double) sample_rate_src;
src_data.end_of_input = 0;
src_process(src, &src_data);
//log_msg(LOG_ERROR, "pa: SRC error code: %d", src_result);
//log_msg(LOG_ERROR, "pa: SRC output frames: %lu", src_data.output_frames_gen);
//log_msg(LOG_ERROR, "pa: SRC input frames used: %lu", src_data.input_frames_used);
int out_frames = src_data.output_frames_gen;
int i = 0;
while (i < out_frames) {
bfl[high] = re_out[i * 2];
bfr[high] = re_out[(i * 2) + 1];
fade_fx();
high += 1;
i++;
}
buff_cycle();
}
// WAV Decoder ----------------------------------------------------------------
FILE *wave_file;
int wave_channels = 2;
int wave_samplerate = 44100;
int wave_depth = 16;
int wave_size = 0;
int wave_start = 0;
int wave_error = 0;
int16_t wave_16 = 0;
int wave_open(char *filename) {
wave_file = uni_fopen(filename);
if (wave_file == NULL) {
log_msg(LOG_ERROR, "pa: Error opening WAVE file: %s", strerror(errno));
return 1;
}
char b[16];
int i;
b[15] = '\0';
fread(b, 4, 1, wave_file);
//log_msg(LOG_INFO, "pa: mark: %s", b)
fread(&i, 4, 1, wave_file);
//log_msg(LOG_INFO, "pa: size: %d", i);
wave_size = i - 44;
fread(b, 4, 1, wave_file);
//log_msg(LOG_INFO, "pa: head: %s", b);
if (memcmp(b, "WAVE", 4) == 1) {
log_msg(LOG_ERROR, "pa: Invalid WAVE file");
fclose(wave_file);
return 1;
}
while (true) {
// Read data block label
wave_error = fread(b, 4, 1, wave_file);
if (wave_error != 1) {
fclose(wave_file);
return 1;
}
// Read data block length
wave_error = fread(&i, 4, 1, wave_file);
if (wave_error != 1) {
fclose(wave_file);
return 1;
}
// Is audio data?
if (memcmp(b, "fmt ", 4) == 0) {
wave_start = ftell(wave_file);
wave_size = i;
break;
}
// Skip to next block
fseek(wave_file, i, SEEK_CUR);
}
//fread(b, 4, 1, wave_file);
//log_msg(LOG_INFO, "pa: fmt : %s", b);
//fread(&i, 4, 1, wave_file);
//log_msg(LOG_INFO, "pa: abov: %d", i);
//if (i != 16) {
// log_msg(LOG_ERROR, "pa: Unsupported WAVE file");
// return 1;
//}
fread(&i, 2, 1, wave_file);
//log_msg(LOG_INFO, "pa: type: %d", i);
if (i != 1) {
log_msg(LOG_ERROR, "pa: Unsupported WAVE file");
fclose(wave_file);
return 1;
}
fread(&i, 2, 1, wave_file);
//log_msg(LOG_INFO, "pa: chan: %d\n", i);
if (i != 1 && i != 2) {
log_msg(LOG_ERROR, "pa: Unsupported WAVE channels");
fclose(wave_file);
return 1;
}
wave_channels = i;
fread(&i, 4, 1, wave_file);
//log_msg(LOG_INFO, "pa: smpl: %d", i);
wave_samplerate = i;
sample_rate_src = i;
fseek(wave_file, 6, SEEK_CUR);
fread(&i, 2, 1, wave_file);
//log_msg(LOG_INFO, "pa: bitd: %d", i);
if (i != 16) {
log_msg(LOG_ERROR, "pa: Unsupported WAVE depth");
fclose(wave_file);
return 1;
}
wave_depth = i;
fseek(wave_file, wave_start + wave_size, SEEK_SET);
while (true) {
// Read data block label
wave_error = fread(b, 4, 1, wave_file);
if (wave_error != 1) {
fclose(wave_file);
return 1;
}
// Read data block length
wave_error = fread(&i, 4, 1, wave_file);
if (wave_error != 1) {
fclose(wave_file);
return 1;
}
// Is audio data?
//log_msg(LOG_INFO, "label %s", b);
if (memcmp(b, "data", 4) == 0) {
wave_start = ftell(wave_file);
wave_size = i;
break;
}
// Skip to next block
fseek(wave_file, i, SEEK_CUR);
}
return 0;
}
int wave_decode(int read_frames) {
int frames_read = 0;
bool end = false;
int i = 0;
while (i < read_frames) {
wave_error = fread(&wave_16, 2, 1, wave_file);
if (wave_error != 1) return 1;
re_in[i * 2] = wave_16 / 32768.0;
wave_error = fread(&wave_16, 2, 1, wave_file);
if (wave_error != 1) return 1;
re_in[i * 2 + 1] = wave_16 / 32768.0;
i++;
frames_read++;
if ((ftell(wave_file) - wave_start) > wave_size) {
log_msg(LOG_INFO, "pa: End of WAVE file data");
end = true;
break;
}
}
if (sample_rate_src != sample_rate_out) {
resample_to_buffer(frames_read);
} else {
i = 0;
while (i < frames_read) {
bfl[high] = re_in[i * 2];
bfr[high] = re_in[i * 2 + 1];
fade_fx();
//buff_filled++;
high++;
samples_decoded++;
i++;
}
buff_cycle();
}
if (end) return 1;
return 0;
}
int wave_seek(int frame_position) {
return fseek(wave_file, (frame_position * 4) + wave_start, SEEK_SET);
}
void wave_close() {
if (wave_file != NULL) fclose(wave_file);
}
void read_to_buffer_24in32_fs(int32_t src[], int n_samples) {
// full samples version
int i = 0;
int f = 0;
// Convert int16 to float
while (f < n_samples) {
re_in[f * 2] = (src[i]) / 8388608.0;
if (src_channels == 1) {
re_in[(f * 2) + 1] = re_in[f * 2];