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
|
/*
DeaDBeeF - ultimate music player for GNU/Linux systems with X11
Copyright (C) 2009-2010 Alexey Yakovenko <waker@users.sourceforge.net>
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 2 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 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/>.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <samplerate.h>
#ifdef __linux__
#include <sys/prctl.h>
#endif
#include <sys/time.h>
#include "threading.h"
#include "playlist.h"
#include "common.h"
#include "streamer.h"
#include "playback.h"
#include "messagepump.h"
#include "conf.h"
#include "plugins.h"
#include "optmath.h"
#include "volume.h"
#include "vfs.h"
//#define trace(...) { fprintf(stderr, __VA_ARGS__); }
#define trace(fmt,...)
static intptr_t streamer_tid;
static int src_quality;
static SRC_STATE *src;
static SRC_DATA srcdata;
static int src_remaining; // number of input samples in SRC buffer
static int conf_replaygain_mode = 0;
static int conf_replaygain_scale = 1;
#define SRC_BUFFER 16000
static int src_in_remaining = 0;
//static int16_t g_src_in_buffer[SRC_BUFFER*2];
static float g_src_in_fbuffer[SRC_BUFFER*2];
static float g_src_out_fbuffer[SRC_BUFFER*2];
static int streaming_terminate;
// buffer up to 3 seconds at 44100Hz stereo
#define STREAM_BUFFER_SIZE 0x80000 // slightly more than 3 seconds of 44100 stereo
#define STREAM_BUFFER_MASK 0x7ffff
//#define STREAM_BUFFER_SIZE 0x10000 // slightly more than 3 seconds of 44100 stereo
//#define STREAM_BUFFER_MASK 0xffff
static int streambuffer_fill;
static int streambuffer_pos;
static int bytes_until_next_song = 0;
static char streambuffer[STREAM_BUFFER_SIZE];
static uintptr_t mutex;
static uintptr_t decodemutex;
static int nextsong = -1;
static int nextsong_pstate = -1;
static int badsong = -1;
static float seekpos = -1;
static float playpos = 0; // play position of current song
static int avg_bitrate = -1; // avg bitrate of current song
static int last_bitrate = -1; // last bitrate of current song
// copies of current playing and streaming tracks
playItem_t str_playing_song;
playItem_t str_streaming_song;
// remember pointers to original instances of playitems
static playItem_t *orig_playing_song;
static playItem_t *orig_streaming_song;
// current decoder
static DB_fileinfo_t *str_current_decoder;
static int streamer_buffering;
// to allow interruption of stall file requests
static DB_FILE *streamer_file;
playItem_t *
streamer_get_streaming_track (void) {
return orig_streaming_song;
}
playItem_t *
streamer_get_playing_track (void) {
return &str_playing_song;
}
// playlist must call that whenever item was removed
void
streamer_song_removed_notify (playItem_t *it) {
if (!mutex) {
return; // streamer is not running
}
plug_trigger_event (DB_EV_TRACKDELETED, (uintptr_t)it);
if (it == orig_playing_song) {
orig_playing_song = NULL;
}
if (it == orig_streaming_song) {
orig_streaming_song = NULL;
// queue new next song for streaming
if (bytes_until_next_song > 0) {
streambuffer_fill = bytes_until_next_song;
streamer_move_nextsong (0);
}
}
}
// that must be called after last sample from str_playing_song was done reading
static int
streamer_set_current (playItem_t *it) {
int from, to;
streamer_buffering = 1;
from = orig_playing_song ? pl_get_idx_of (orig_playing_song) : -1;
to = it ? pl_get_idx_of (it) : -1;
if (to != -1) {
messagepump_push (M_TRACKCHANGED, 0, to, 0);
}
#if 0
// this breaks redraw
if (!orig_playing_song || p_isstopped ()) {
orig_playing_song = it;
}
#endif
trace ("streamer_set_current %p, buns=%d\n", it);
if(str_current_decoder) {
str_current_decoder->plugin->free (str_current_decoder);
str_current_decoder = NULL;
pl_item_unref (&str_streaming_song);
}
orig_streaming_song = it;
if (!it) {
goto success;
}
DB_decoder_t *dec = NULL;
if (!it->decoder_id && it->filetype && !strcmp (it->filetype, "content")) {
// try to get content-type
DB_FILE *fp = streamer_file = vfs_fopen (it->fname);
const char *plug = NULL;
if (fp) {
const char *ct = vfs_get_content_type (fp);
if (ct) {
fprintf (stderr, "got content-type: %s\n", ct);
if (!strcmp (ct, "audio/mpeg")) {
plug = "stdmpg";
}
else if (!strcmp (ct, "application/ogg")) {
plug = "stdogg";
}
}
streamer_file = NULL;
vfs_fclose (fp);
}
if (plug) {
dec = plug_get_decoder_for_id (plug);
if (dec) {
it->decoder_id = plug_get_decoder_id (plug);
it->filetype = dec->filetypes[0];
}
}
}
else if (it->decoder_id) {
dec = plug_get_decoder_for_id (it->decoder_id);
}
if (dec) {
str_current_decoder = dec->init (DB_PLAYITEM (it));
trace ("str: acquired decoder ptr %p\n", str_current_decoder);
pl_item_copy (&str_streaming_song, it);
if (!str_current_decoder) {
trace ("decoder->init returned NULL\n");
trace ("orig_playing_song = %p\n", orig_playing_song);
if (orig_playing_song == it) {
orig_playing_song = NULL;
messagepump_push (M_TRACKCHANGED, 0, to, 0);
}
return -1;
}
else {
trace ("bps=%d, channels=%d, samplerate=%d\n", str_current_decoder->bps, str_current_decoder->channels, str_current_decoder->samplerate);
}
streamer_reset (0); // reset SRC
}
else {
streamer_buffering = 0;
if (to != -1) {
messagepump_push (M_TRACKCHANGED, 0, to, 0);
}
trace ("no decoder in playitem!\n");
orig_streaming_song = NULL;
return -1;
}
if (bytes_until_next_song == -1) {
bytes_until_next_song = 0;
}
success:
messagepump_push (M_TRACKCHANGED, 0, to, 0);
return 0;
}
float
streamer_get_playpos (void) {
return playpos;
}
void
streamer_set_bitrate (int bitrate) {
if (bytes_until_next_song <= 0) { // prevent next track from resetting current playback bitrate
last_bitrate = bitrate;
}
}
int
streamer_get_apx_bitrate (void) {
return avg_bitrate;
}
void
streamer_set_nextsong (int song, int pstate) {
trace ("streamer_set_nextsong %d %d\n", song, pstate);
plug_trigger_event (DB_EV_ABORTREAD, 0);
nextsong = song;
nextsong_pstate = pstate;
if (p_isstopped ()) {
// no sense to wait until end of previous song, reset buffer
bytes_until_next_song = 0;
playpos = 0;
}
}
void
streamer_set_seek (float pos) {
seekpos = pos;
}
static int
streamer_read_async (char *bytes, int size);
void
streamer_thread (void *ctx) {
#ifdef __linux__
prctl (PR_SET_NAME, "deadbeef-stream", 0, 0, 0, 0);
#endif
src_remaining = 0;
while (!streaming_terminate) {
struct timeval tm1;
gettimeofday (&tm1, NULL);
if (nextsong >= 0) { // start streaming next song
trace ("nextsong=%d\n", nextsong);
int sng = nextsong;
int pstate = nextsong_pstate;
nextsong = -1;
src_remaining = 0;
if (badsong == sng) {
trace ("looped to bad file. stopping...\n");
streamer_set_nextsong (-2, 1);
badsong = -1;
continue;
}
playItem_t *try = pl_get_for_idx (sng);
if (!try) { // track is not in playlist
trace ("track #%d is not in playlist; stopping playback\n", sng);
p_stop ();
pl_item_unref (&str_playing_song);
pl_item_unref (&str_streaming_song);
orig_playing_song = NULL;
orig_streaming_song = NULL;
messagepump_push (M_SONGCHANGED, 0, -1, -1);
continue;
}
int ret = streamer_set_current (try);
if (ret < 0) {
trace ("failed to play track %s, skipping...\n", try->fname);
// remember bad song number in case of looping
if (badsong == -1) {
badsong = sng;
}
// try jump to next song
streamer_move_nextsong (0);
trace ("streamer_move_nextsong switched to track %d\n", nextsong);
usleep (50000);
continue;
}
badsong = -1;
if (pstate == 0) {
p_stop ();
}
else if (pstate == 1) {
last_bitrate = -1;
avg_bitrate = -1;
if (p_state () != OUTPUT_STATE_PLAYING) {
if (p_play () < 0) {
fprintf (stderr, "streamer: failed to start playback; output plugin doesn't work\n");
streamer_set_nextsong (-2, 0);
}
}
}
else if (pstate == 2) {
p_pause ();
}
}
else if (nextsong == -2 && (nextsong_pstate==0 || bytes_until_next_song == 0)) {
int from = orig_playing_song ? pl_get_idx_of (orig_playing_song) : -1;
bytes_until_next_song = -1;
trace ("nextsong=-2\n");
nextsong = -1;
p_stop ();
if (str_current_decoder) {
trace ("sending songfinished to plugins [1]\n");
plug_trigger_event (DB_EV_SONGFINISHED, 0);
}
streamer_set_current (NULL);
pl_item_unref (&str_playing_song);
orig_playing_song = NULL;
messagepump_push (M_SONGCHANGED, 0, from, -1);
continue;
}
else if (p_isstopped ()) {
usleep (50000);
continue;
}
if (bytes_until_next_song == 0) {
if (!str_streaming_song.fname) {
// means last song was deleted during final drain
nextsong = -1;
p_stop ();
streamer_set_current (NULL);
continue;
}
trace ("bytes_until_next_song=0, starting playback of new song\n");
int from = orig_playing_song ? pl_get_idx_of (orig_playing_song) : -1;
int to = orig_streaming_song ? pl_get_idx_of (orig_streaming_song) : -1;
trace ("from=%d, to=%d\n", from, to);
trace ("sending songchanged\n");
messagepump_push (M_SONGCHANGED, 0, from, to);
bytes_until_next_song = -1;
// plugin will get pointer to str_playing_song
if (str_current_decoder) {
trace ("sending songfinished to plugins [2]\n");
plug_trigger_event (DB_EV_SONGFINISHED, 0);
}
// free old copy of playing
pl_item_unref (&str_playing_song);
// copy streaming into playing
pl_item_copy (&str_playing_song, &str_streaming_song);
last_bitrate = -1;
avg_bitrate = -1;
orig_playing_song = orig_streaming_song;
if (orig_playing_song) {
orig_playing_song->played = 1;
orig_playing_song->started_timestamp = time (NULL);
str_playing_song.started_timestamp = time (NULL);
}
// that is needed for playlist drawing
// plugin will get pointer to new str_playing_song
trace ("sending songstarted to plugins\ncurrent playtrack: %s\n", str_playing_song.fname);
plug_trigger_event (DB_EV_SONGSTARTED, 0);
playpos = 0;
// try to switch samplerate to the closest supported by output plugin
if (conf_get_int ("playback.dynsamplerate", 0)) {
// don't switch if unchanged
int prevtrack_samplerate = p_get_rate ();
if (prevtrack_samplerate != str_current_decoder->samplerate) {
int newrate = plug_get_output ()->change_rate (str_current_decoder->samplerate);
if (newrate != prevtrack_samplerate) {
// restart streaming of current track
trace ("streamer: output samplerate changed from %d to %d; restarting track\n", prevtrack_samplerate, newrate);
str_current_decoder->plugin->seek (str_current_decoder, 0);
bytes_until_next_song = -1;
streamer_buffering = 1;
streamer_reset (1);
prevtrack_samplerate = str_current_decoder->samplerate;
}
}
// output plugin may stop playback before switching samplerate
if (p_state () != OUTPUT_STATE_PLAYING) {
if (p_play () < 0) {
fprintf (stderr, "streamer: failed to start playback after samplerate change; output plugin doesn't work\n");
streamer_set_nextsong (-2, 0);
continue;
}
}
}
}
if (seekpos >= 0) {
trace ("seeking to %f\n", seekpos);
float pos = seekpos;
seekpos = -1;
if (orig_playing_song != orig_streaming_song) {
trace ("streamer already switched to next track\n");
// restart playing from new position
if(str_current_decoder) {
str_current_decoder->plugin->free (str_current_decoder);
str_current_decoder = NULL;
pl_item_unref (&str_streaming_song);
}
orig_streaming_song = orig_playing_song;
pl_item_copy (&str_streaming_song, orig_streaming_song);
bytes_until_next_song = -1;
streamer_buffering = 1;
int trk = pl_get_idx_of (orig_streaming_song);
if (trk != -1) {
messagepump_push (M_TRACKCHANGED, 0, trk, 0);
}
DB_decoder_t *plug = plug_get_decoder_for_id (orig_streaming_song->decoder_id);
if (plug) {
str_current_decoder = plug->init (DB_PLAYITEM (orig_streaming_song));
}
if (!plug || !str_current_decoder) {
streamer_buffering = 0;
if (trk != -1) {
messagepump_push (M_TRACKCHANGED, 0, trk, 0);
}
trace ("failed to restart prev track on seek, trying to jump to next track\n");
streamer_move_nextsong (0);
trace ("streamer_move_nextsong switched to track %d\n", nextsong);
usleep (50000);
continue;
}
}
streamer_buffering = 1;
int trk = pl_get_idx_of (orig_streaming_song);
if (trk != -1) {
messagepump_push (M_TRACKCHANGED, 0, trk, 0);
}
if (str_current_decoder && str_playing_song._duration > 0) {
streamer_lock ();
streambuffer_fill = 0;
streambuffer_pos = 0;
src_remaining = 0;
if (str_current_decoder->plugin->seek (str_current_decoder, pos) >= 0) {
playpos = str_current_decoder->readpos;
}
last_bitrate = -1;
avg_bitrate = -1;
streamer_unlock();
}
}
// read ahead at 384K per second
// that means 10ms per 4k block, or 40ms per 16k block
int alloc_time = 1000 / (96000 * 4 / 4096);
streamer_lock ();
if (streambuffer_fill < (STREAM_BUFFER_SIZE-4096)/* && bytes_until_next_song == 0*/) {
int sz = STREAM_BUFFER_SIZE - streambuffer_fill;
int minsize = 4096;
if (streambuffer_fill < 16384) {
minsize = 16384;
alloc_time *= 4;
}
sz = min (minsize, sz);
assert ((sz&3) == 0);
char buf[sz];
streamer_unlock ();
int bytesread = streamer_read_async (buf,sz);
streamer_lock ();
memcpy (streambuffer+streambuffer_fill, buf, sz);
streambuffer_fill += bytesread;
}
streamer_unlock ();
if (streambuffer_fill > 128000 && streamer_buffering || !orig_streaming_song) {
streamer_buffering = 0;
if (orig_streaming_song) {
int trk = pl_get_idx_of (orig_streaming_song);
if (trk != -1) {
messagepump_push (M_TRACKCHANGED, 0, trk, 0);
}
}
}
struct timeval tm2;
gettimeofday (&tm2, NULL);
int ms = (tm2.tv_sec*1000+tm2.tv_usec/1000) - (tm1.tv_sec*1000+tm1.tv_usec/1000);
alloc_time -= ms;
if (alloc_time > 0) {
usleep (alloc_time * 1000);
// usleep (1000);
}
// trace ("fill: %d/%d\n", streambuffer_fill, STREAM_BUFFER_SIZE);
}
// stop streaming song
if(str_current_decoder) {
str_current_decoder->plugin->free (str_current_decoder);
str_current_decoder = NULL;
}
pl_item_unref (&str_streaming_song);
pl_item_unref (&str_playing_song);
if (src) {
src_delete (src);
src = NULL;
}
}
int
streamer_init (void) {
mutex = mutex_create ();
decodemutex = mutex_create ();
src_quality = conf_get_int ("src_quality", 2);
src = src_new (src_quality, 2, NULL);
conf_replaygain_mode = conf_get_int ("replaygain_mode", 0);
conf_replaygain_scale = conf_get_int ("replaygain_scale", 1);
if (!src) {
return -1;
}
streamer_tid = thread_start (streamer_thread, NULL);
return 0;
}
void
streamer_free (void) {
streaming_terminate = 1;
thread_join (streamer_tid);
mutex_free (decodemutex);
decodemutex = 0;
mutex_free (mutex);
mutex = 0;
}
void
streamer_reset (int full) { // must be called when current song changes by external reasons
src_remaining = 0;
if (full) {
streambuffer_pos = 0;
streambuffer_fill = 0;
}
src_reset (src);
}
int replaygain = 1;
int replaygain_scale = 1;
static void
apply_replay_gain_int16 (playItem_t *it, char *bytes, int size) {
if (!replaygain || !conf_replaygain_mode) {
return;
}
int vol = 1000;
if (conf_replaygain_mode == 1) {
if (it->replaygain_track_gain == 0) {
return;
}
if (conf_replaygain_scale && replaygain_scale) {
vol = db_to_amp (str_streaming_song.replaygain_track_gain)/str_streaming_song.replaygain_track_peak * 1000;
}
else {
vol = db_to_amp (str_streaming_song.replaygain_track_gain) * 1000;
}
}
else if (conf_replaygain_mode == 2) {
if (it->replaygain_album_gain == 0) {
return;
}
if (conf_replaygain_scale && replaygain_scale) {
vol = db_to_amp (str_streaming_song.replaygain_album_gain)/str_streaming_song.replaygain_album_peak * 1000;
}
else {
vol = db_to_amp (str_streaming_song.replaygain_album_gain) * 1000;
}
}
int16_t *s = (int16_t*)bytes;
for (int j = 0; j < size/2; j++) {
int32_t sample = ((int32_t)(*s)) * vol / 1000;
if (sample > 0x7fff) {
sample = 0x7fff;
}
else if (sample < -0x8000) {
sample = -0x8000;
}
*s = (int16_t)sample;
s++;
}
}
static void
apply_replay_gain_float32 (playItem_t *it, char *bytes, int size) {
if (!replaygain || !conf_replaygain_mode) {
return;
}
float vol = 1.f;
if (conf_replaygain_mode == 1) {
if (it->replaygain_track_gain == 0) {
return;
}
if (conf_replaygain_scale && replaygain_scale) {
vol = db_to_amp (it->replaygain_track_gain)/it->replaygain_track_peak;
}
else {
vol = db_to_amp (it->replaygain_track_gain);
}
}
else if (conf_replaygain_mode == 2) {
if (it->replaygain_album_gain == 0) {
return;
}
if (conf_replaygain_scale && replaygain_scale) {
vol = db_to_amp (it->replaygain_album_gain)/it->replaygain_album_peak;
}
else {
vol = db_to_amp (it->replaygain_album_gain);
}
}
float *s = (float*)bytes;
for (int j = 0; j < size/4; j++) {
float sample = ((float)*s) * vol;
if (sample > 1.f) {
sample = 1.f;
}
else if (sample < -1.f) {
sample = -1.f;
}
*s = sample;
s++;
}
}
static void
mono_int16_to_stereo_int16 (int16_t *in, int16_t *out, int nsamples) {
while (nsamples > 0) {
int16_t sample = *in++;
*out++ = sample;
*out++ = sample;
nsamples--;
}
}
static void
int16_to_float32 (int16_t *in, float *out, int nsamples) {
while (nsamples > 0) {
*out++ = (*in++)/(float)0x7fff;
nsamples--;
}
}
static void
mono_int16_to_stereo_float32 (int16_t *in, float *out, int nsamples) {
while (nsamples > 0) {
float sample = (*in++)/(float)0x7fff;
*out++ = sample;
*out++ = sample;
nsamples--;
}
}
static void
mono_float32_to_stereo_float32 (float *in, float *out, int nsamples) {
while (nsamples > 0) {
float sample = *in++;
*out++ = sample;
*out++ = sample;
nsamples--;
}
}
static void
float32_to_int16 (float *in, int16_t *out, int nsamples) {
fpu_control ctl;
fpu_setround (&ctl);
while (nsamples > 0) {
float sample = *in++;
if (sample > 1) {
sample = 1;
}
else if (sample < -1) {
sample = -1;
}
*out++ = (int16_t)ftoi (sample*0x7fff);
nsamples--;
}
fpu_restore (ctl);
}
/*
src algorithm
initsize = size;
while (size > 0) {
need_frames = SRC_BUFFER - src_remaining
read_samples (need_frames)
src_process (output_frames)
convert_to_int16 (bytes, size)
// handle errors
}
return initsize-size;
*/
static int
streamer_read_data_for_src (int16_t *buffer, int frames) {
DB_decoder_t *decoder = str_current_decoder->plugin;
int channels = str_current_decoder->channels;
if (channels > 2) {
channels = 2;
}
int bytesread = decoder->read_int16 (str_current_decoder, (uint8_t*)buffer, frames * sizeof (int16_t) * channels);
if (channels == 1) {
// convert to stereo
int n = frames-1;
while (n >= 0) {
buffer[n*2+0] = buffer[n];
buffer[n*2+1] = buffer[n];
}
}
return bytesread / (sizeof (int16_t) * channels);
}
static int
streamer_read_data_for_src_float (float *buffer, int frames) {
DB_decoder_t *decoder = str_current_decoder->plugin;
int channels = str_current_decoder->channels;
if (channels > 2) {
channels = 2;
}
if (decoder->read_float32) {
// trace ("call read_float32 (%d frames -> %d bytes)\n", frames, frames * sizeof (float) * channels);
int bytesread = decoder->read_float32 (str_current_decoder, (uint8_t*)buffer, frames * sizeof (float) * channels);
// trace ("got %d bytes -> %d frames\n", bytesread, bytesread / (sizeof (float) * channels));
if (channels == 1) {
// convert to stereo
int n = frames-1;
while (n >= 0) {
buffer[n*2+0] = buffer[n];
buffer[n*2+1] = buffer[n];
}
bytesread *= 2;
}
return bytesread / (sizeof (float) * channels);
}
// trace ("read_float32 not impl\n");
int16_t intbuffer[frames*2];
int res = streamer_read_data_for_src (intbuffer, frames);
for (int i = 0; i < res; i++) {
buffer[i*2+0] = intbuffer[i*2+0]/(float)0x7fff;
buffer[i*2+1] = intbuffer[i*2+1]/(float)0x7fff;
}
return res;
}
static int
streamer_decode_src_libsamplerate (uint8_t *bytes, int size) {
int initsize = size;
int16_t *out = (int16_t *)bytes;
DB_decoder_t *decoder = str_current_decoder->plugin;
int samplerate = str_current_decoder->samplerate;
float ratio = (float)p_get_rate ()/samplerate;
while (size > 0) {
int n_output_frames = size / sizeof (int16_t) / 2;
int n_input_frames = n_output_frames * samplerate / p_get_rate () + 100;
// read data from decoder
if (n_input_frames > SRC_BUFFER - src_remaining ) {
n_input_frames = SRC_BUFFER - src_remaining;
}
int nread = streamer_read_data_for_src_float (&g_src_in_fbuffer[src_remaining*2], n_input_frames);
src_remaining += nread;
// resample
srcdata.data_in = g_src_in_fbuffer;
srcdata.data_out = g_src_out_fbuffer;
srcdata.input_frames = src_remaining;
srcdata.output_frames = size/4;
srcdata.src_ratio = ratio;
// trace ("SRC from %d to %d\n", samplerate, p_get_rate ());
srcdata.end_of_input = (nread == n_input_frames) ? 0 : 1;
src_process (src, &srcdata);
// convert back to s16 format
// trace ("out frames: %d\n", srcdata.output_frames_gen);
int genbytes = srcdata.output_frames_gen * 4;
int bytesread = min(size, genbytes);
// trace ("bytesread: %d\n", bytesread);
float32_to_int16 ((float*)g_src_out_fbuffer, (int16_t*)bytes, bytesread>>1);
size -= bytesread;
// trace ("size: %d\n", size);
bytes += bytesread;
// calculate how many unused input samples left
src_remaining -= srcdata.input_frames_used;
// copy spare samples for next update
if (src_remaining > 0) {
memmove (g_src_in_fbuffer, &g_src_in_fbuffer[srcdata.input_frames_used*2], src_remaining * sizeof (float) * 2);
}
if (nread != n_input_frames) {
trace ("nread=%d, n_input_frames=%d, mismatch!\n", nread, n_input_frames);
break;
}
}
return initsize-size;
}
#if 0
static int
streamer_decode_src (uint8_t *bytes, int size) {
int initsize = size;
int16_t *out = (int16_t *)bytes;
DB_decoder_t *decoder = str_streaming_song.decoder;
int samplerate = decoder->info.samplerate;
float ratio = (float)samplerate / p_get_rate ();
while (size > 0) {
int n_output_frames = size / sizeof (int16_t) / 2;
int n_input_frames = n_output_frames * samplerate / p_get_rate () + 100;
// read data from decoder
if (n_input_frames > SRC_BUFFER - src_remaining ) {
n_input_frames = SRC_BUFFER - src_remaining;
}
int nread = streamer_read_data_for_src (&g_src_in_buffer[src_remaining*2], n_input_frames);
src_remaining += nread;
// resample
float idx = 0;
int i = 0;
while (i < n_output_frames && idx < src_remaining) {
int k = (int)idx;
out[0] = g_src_in_buffer[k*2+0];
out[1] = g_src_in_buffer[k*2+1];
i++;
idx += ratio;
out += 2;
}
size -= i*4;
src_remaining -= idx;
if (src_remaining < 0) {
src_remaining = 0;
}
else if (src_remaining > 0) {
memmove (g_src_in_buffer, &g_src_in_buffer[(SRC_BUFFER-src_remaining)*2], src_remaining*2*sizeof (int16_t));
}
if (nread != n_input_frames) {
break;
}
}
return initsize-size;
}
#endif
// returns number of bytes been read
static int
streamer_read_async (char *bytes, int size) {
int initsize = size;
for (;;) {
int bytesread = 0;
if (!str_current_decoder) {
// means there's nothing left to stream, so just do nothing
break;
}
if (str_current_decoder->samplerate != -1) {
int nchannels = str_current_decoder->channels;
if (nchannels > 2) {
nchannels = 2;
}
int samplerate = str_current_decoder->samplerate;
if (str_current_decoder->samplerate == p_get_rate () && str_current_decoder->plugin->read_int16) {
// samplerate match
if (nchannels == 2) {
bytesread = str_current_decoder->plugin->read_int16 (str_current_decoder, bytes, size);
apply_replay_gain_int16 (&str_streaming_song, bytes, size);
}
else {
uint8_t buffer[size>>1];
bytesread = str_current_decoder->plugin->read_int16 (str_current_decoder, buffer, size>>1);
apply_replay_gain_int16 (&str_streaming_song, buffer, size>>1);
mono_int16_to_stereo_int16 ((int16_t*)buffer, (int16_t*)bytes, size>>2);
bytesread *= 2;
}
}
else if (src_is_valid_ratio (p_get_rate ()/(double)samplerate)) {
bytesread = streamer_decode_src_libsamplerate (bytes, size);
}
else {
fprintf (stderr, "invalid ratio! %d / %d = %f", p_get_rate (), samplerate, p_get_rate ()/(float)samplerate);
}
}
else {
}
bytes += bytesread;
size -= bytesread;
if (size == 0) {
return initsize;
}
else {
// that means EOF
if (bytes_until_next_song < 0) {
trace ("finished streaming song, queueing next\n");
bytes_until_next_song = streambuffer_fill;
if (conf_get_int ("playlist.stop_after_current", 0)) {
conf_set_int ("playlist.stop_after_current", 0);
plug_trigger_event (DB_EV_CONFIGCHANGED, 0);
streamer_set_nextsong (-2, 1);
}
else {
streamer_move_nextsong (0);
}
}
break;
}
}
return initsize - size;
}
void
streamer_lock (void) {
mutex_lock (mutex);
}
void
streamer_unlock (void) {
mutex_unlock (mutex);
}
int
streamer_read (char *bytes, int size) {
#if 0
struct timeval tm1;
gettimeofday (&tm1, NULL);
#endif
streamer_lock ();
int sz = min (size, streambuffer_fill);
if (sz) {
memcpy (bytes, streambuffer, sz);
memmove (streambuffer, streambuffer+sz, streambuffer_fill-sz);
streambuffer_fill -= sz;
playpos += (float)sz/p_get_rate ()/4.f;
str_playing_song.playtime += (float)sz/p_get_rate ()/4.f;
if (orig_playing_song) {
str_playing_song.filetype = orig_playing_song->filetype;
orig_playing_song->playtime = str_playing_song.playtime;
}
if (bytes_until_next_song > 0) {
bytes_until_next_song -= sz;
if (bytes_until_next_song < 0) {
bytes_until_next_song = 0;
}
}
}
streamer_unlock ();
// approximate bitrate
if (last_bitrate != -1) {
if (avg_bitrate == -1) {
avg_bitrate = last_bitrate;
}
else {
if (avg_bitrate < last_bitrate) {
avg_bitrate += 5;
if (avg_bitrate > last_bitrate) {
avg_bitrate = last_bitrate;
}
}
else if (avg_bitrate > last_bitrate) {
avg_bitrate -= 5;
if (avg_bitrate < last_bitrate) {
avg_bitrate = last_bitrate;
}
}
}
// printf ("apx bitrate: %d (last %d)\n", avg_bitrate, last_bitrate);
}
else {
avg_bitrate = -1;
}
#if 0
struct timeval tm2;
gettimeofday (&tm2, NULL);
int ms = (tm2.tv_sec*1000+tm2.tv_usec/1000) - (tm1.tv_sec*1000+tm1.tv_usec/1000);
printf ("streamer_read took %d ms\n", ms);
#endif
return sz;
}
int
streamer_get_fill (void) {
return streambuffer_fill;
}
int
streamer_ok_to_read (int len) {
if (len >= 0 && (bytes_until_next_song > 0 || streambuffer_fill >= (len*2))) {
return 1;
}
else {
return 1-streamer_buffering;
}
return 0;
}
int
streamer_is_buffering (void) {
if (streambuffer_fill < 16384) {
return 1;
}
else {
return 0;
}
}
void
streamer_configchanged (void) {
conf_replaygain_mode = conf_get_int ("replaygain_mode", 0);
conf_replaygain_scale = conf_get_int ("replaygain_scale", 1);
int q = conf_get_int ("src_quality", 2);
if (q != src_quality && q >= SRC_SINC_BEST_QUALITY && q <= SRC_LINEAR) {
mutex_lock (decodemutex);
fprintf (stderr, "changing src_quality from %d to %d\n", src_quality, q);
src_quality = q;
if (src) {
src_delete (src);
src = NULL;
}
memset (&srcdata, 0, sizeof (srcdata));
src = src_new (src_quality, 2, NULL);
mutex_unlock (decodemutex);
}
}
void
streamer_play_current_track (void) {
playlist_t *plt = plt_get_curr_ptr ();
if (p_ispaused ()) {
// unpause currently paused track
p_unpause ();
plug_trigger_event_paused (0);
}
else if (plt->current_row[PL_MAIN] != -1) {
// play currently selected track
p_stop ();
// get next song in queue
int idx = -1;
playItem_t *next = pl_playqueue_getnext ();
if (next) {
idx = pl_get_idx_of (next);
pl_playqueue_pop ();
}
else {
idx = plt->current_row[PL_MAIN];
}
streamer_set_nextsong (idx, 1);
}
else {
// restart currently playing track
p_stop ();
streamer_set_nextsong (0, 1);
}
}
int
streamer_move_prevsong (void) {
playlist_t *plt = plt_get_curr_ptr ();
pl_playqueue_clear ();
if (!plt->head[PL_MAIN]) {
streamer_set_nextsong (-2, 1);
return 0;
}
int pl_order = conf_get_int ("playback.order", 0);
int pl_loop_mode = conf_get_int ("playback.loop", 0);
if (pl_order == PLAYBACK_ORDER_SHUFFLE) { // shuffle
if (!orig_playing_song) {
return streamer_move_nextsong (1);
}
else {
orig_playing_song->played = 0;
// find already played song with maximum shuffle rating below prev song
int rating = orig_playing_song->shufflerating;
playItem_t *pmax = NULL; // played maximum
playItem_t *amax = NULL; // absolute maximum
for (playItem_t *i = plt->head[PL_MAIN]; i; i = i->next[PL_MAIN]) {
if (i != orig_playing_song && i->played && (!amax || i->shufflerating > amax->shufflerating)) {
amax = i;
}
if (i == orig_playing_song || i->shufflerating > rating || !i->played) {
continue;
}
if (!pmax || i->shufflerating > pmax->shufflerating) {
pmax = i;
}
}
playItem_t *it = pmax;
if (!it) {
// that means 1st in playlist, take amax
if (pl_loop_mode == PLAYBACK_MODE_LOOP_ALL) {
if (!amax) {
pl_reshuffle (NULL, &amax);
}
it = amax;
}
}
if (!it) {
return -1;
}
int r = pl_get_idx_of (it);
streamer_set_nextsong (r, 1);
return 0;
}
}
else if (pl_order == PLAYBACK_ORDER_LINEAR) { // linear
playItem_t *it = NULL;
if (orig_playing_song) {
it = orig_playing_song->prev[PL_MAIN];
}
if (!it) {
if (pl_loop_mode == PLAYBACK_MODE_LOOP_ALL) {
it = plt->tail[PL_MAIN];
}
}
if (!it) {
return -1;
}
int r = pl_get_idx_of (it);
streamer_set_nextsong (r, 1);
return 0;
}
else if (pl_order == PLAYBACK_ORDER_RANDOM) { // random
streamer_move_randomsong ();
}
return -1;
}
int
streamer_move_nextsong (int reason) {
playlist_t *plt = plt_get_curr_ptr ();
playItem_t *it = pl_playqueue_getnext ();
if (it) {
pl_playqueue_pop ();
int r = pl_get_idx_of (it);
streamer_set_nextsong (r, 1);
return 0;
}
playItem_t *curr = streamer_get_streaming_track ();
if (!plt->head[PL_MAIN]) {
streamer_set_nextsong (-2, 1);
return 0;
}
int pl_order = conf_get_int ("playback.order", 0);
int pl_loop_mode = conf_get_int ("playback.loop", 0);
if (pl_order == PLAYBACK_ORDER_SHUFFLE) { // shuffle
if (!curr) {
// find minimal notplayed
playItem_t *pmin = NULL; // notplayed minimum
for (playItem_t *i = plt->head[PL_MAIN]; i; i = i->next[PL_MAIN]) {
if (i->played) {
continue;
}
if (!pmin || i->shufflerating < pmin->shufflerating) {
pmin = i;
}
}
playItem_t *it = pmin;
if (!it) {
// all songs played, reshuffle and try again
if (pl_loop_mode == PLAYBACK_MODE_LOOP_ALL) { // loop
pl_reshuffle (&it, NULL);
}
}
if (!it) {
return -1;
}
int r = pl_get_idx_of (it);
streamer_set_nextsong (r, 1);
return 0;
}
else {
trace ("pl_next_song: reason=%d, loop=%d\n", reason, pl_loop_mode);
if (reason == 0 && pl_loop_mode == PLAYBACK_MODE_LOOP_SINGLE) { // song finished, loop mode is "loop 1 track"
int r = pl_get_idx_of (curr);
streamer_set_nextsong (r, 1);
return 0;
}
// find minimal notplayed above current
int rating = curr->shufflerating;
playItem_t *pmin = NULL; // notplayed minimum
for (playItem_t *i = plt->head[PL_MAIN]; i; i = i->next[PL_MAIN]) {
if (i->played || i->shufflerating < rating) {
continue;
}
if (!pmin || i->shufflerating < pmin->shufflerating) {
pmin = i;
}
}
playItem_t *it = pmin;
if (!it) {
trace ("all songs played! reshuffle\n");
// all songs played, reshuffle and try again
if (pl_loop_mode == PLAYBACK_MODE_LOOP_ALL) { // loop
pl_reshuffle (&it, NULL);
}
}
if (!it) {
return -1;
}
int r = pl_get_idx_of (it);
streamer_set_nextsong (r, 1);
return 0;
}
}
else if (pl_order == PLAYBACK_ORDER_LINEAR) { // linear
playItem_t *it = NULL;
if (curr) {
if (reason == 0 && pl_loop_mode == PLAYBACK_MODE_LOOP_SINGLE) { // loop same track
int r = pl_get_idx_of (curr);
streamer_set_nextsong (r, 1);
return 0;
}
it = curr->next[PL_MAIN];
}
if (!it) {
trace ("streamer_move_nextsong: was last track\n");
if (pl_loop_mode == PLAYBACK_MODE_LOOP_ALL) {
it = plt->head[PL_MAIN];
}
else {
streamer_set_nextsong (-2, 1);
return 0;
}
}
if (!it) {
return -1;
}
int r = pl_get_idx_of (it);
streamer_set_nextsong (r, 1);
return 0;
}
else if (pl_order == PLAYBACK_ORDER_RANDOM) { // random
if (reason == 0 && pl_loop_mode == PLAYBACK_MODE_LOOP_SINGLE && curr) {
int r = pl_get_idx_of (curr);
streamer_set_nextsong (r, 1);
return 0;
}
return streamer_move_randomsong ();
}
return -1;
}
int
streamer_move_randomsong (void) {
int cnt = pl_getcount (PL_MAIN);
if (!cnt) {
return -1;
}
int r = rand () / (float)RAND_MAX * cnt;
streamer_set_nextsong (r, 1);
return 0;
}
playItem_t *
streamer_get_current (void) {
return orig_playing_song;
}
struct DB_fileinfo_s *
streamer_get_current_decoder (void) {
return str_current_decoder;
}
|