-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpi0-oled-mp3.c
1587 lines (1485 loc) · 46.3 KB
/
rpi0-oled-mp3.c
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
#define _GNU_SOURCE
/*
* rpi0-oled-mp3
*
* John Wiggins (jcwiggi@gmail.com)
*
* NOTE: I have changed from Makefile to cmake. In order to make this, run the following:
cmake -H. -Bbuild
and then run:
cmake --build build --
* mp3 player for Raspberry Pi 0 with output to a 128x64 OLED display for song information
*
*
* Portions of this code were borrowed from MANY other projects including (but not limited to)
*
* - wiringPi example code for lcd.c http://wiringpi.com/
* - Many thanks to Gordon for making the wiringPi library.
*
* - The rotary encoder and volume control was borrowed from the MPD player found here:
* - http://theatticlight.net/posts/My-Embedded-Music-Player-and-Sound-Server
*
* - The oled library used can be found here:
* (NOTE: I know this has been depreciated but it worked better for me than the newer one)
* - https://github.com/bitbank2/oled_96
*
* - http://hzqtc.github.io/2012/05/play-mp3-with-libmpg123-and-libao.html
*
* - http://www.arduino.cc/en/Tutorial/Debounce
*
* - Many thanks to those who helped me out at StackExchange
* (http://raspberrypi.stackexchange.com/)
*
* Known issues:
*
* - The MP3 decoding part I use for some reason always gives me an error on STDERR and I haven't the
* time to go through the lib sources to try to find out what's going on; so I always just run the
* program with 2>/dev/null (e.g. ./rpi0-oled-mp3 2>/dev/null)
*
* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*
* Requires:
* - Program must be run as root or type "sudo chmod +s [executable]"
* - Libraries:
* pthread
* libao-dev
* libmpg123-dev
* libasound2
*
* (all the above are available via apt-get if using raspbian)
*
* wiringPi (available via: git clone git://git.drogon.net/wiringPi )
*
* For OLED, I used oled96 available from github:
* (and yes, I know this has been depreciated but the newer one doesn't work ootb in linux)
* liboled96.a (oled lib from https://github.com/bitbank2/oled_96)
*
* - System setup:
* - A directory /MUSIC needs to be created.
* (optional as the program will attempt to mount the flash)
* - In the file, /etc/fstab, the following entry needs to be added so the usb flash will be mounted:
*
* /dev/sda1 /MUSIC vfat defaults 0 2
*
* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*
* NOTE: Changelog is now in its own file, 'ChangeLog'
*
* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <libgen.h>
#include <signal.h>
// For volume control
#include <math.h>
#include <alsa/asoundlib.h>
// For mounting
#include <sys/mount.h>
#include <dirent.h>
// For subdirectory searching
#include <limits.h>
#include <sys/types.h>
// For wiringPi
#include <wiringPi.h>
#include "rpi0-oled-mp3.h"
// For rotary encoder for volume
#include "rotaryencoder.h"
#include "oled96.h"
#define exp10(x) (exp((x) * log(10)))
// --------- BEGIN USER MODIFIABLE VARS ---------
// Rotary encoder
#define encoderPinB 28 // GPIO 28, BCM 20
#define encoderPinA 29 // GPIO 29, BCM 21
#define quitButtonPin 24 // GPIO 24, BCM 19
// Bar graph
#define CE 1
const int extraLedPins[] = { 29, 28 }; // for bar graph leds 9 and 10
const int rot_enc_A = 23;
const int rot_enc_B = 27;
unsigned int lastMillis = 0;
unsigned char data[1] = { 0x0 };
unsigned char backup_data[1] = { 0x0 };
#define BTN_DELAY 30
//#define DEBUG 0
// --------- END USER MODIFIABLE VARS ---------
/*
* Debounce tracking stuff
*/
int quitButtonState;
int lastQuitButtonState;
long lastQuitDebounceTime;
long debounceDelay = 50;
// More global variables
static int Index = 0;
static playlist_t Tmp_Playlist;
static char card[64] = "hw:0";
snd_mixer_t *handle = NULL;
snd_mixer_elem_t *elem = NULL;
/*
* System stuff
*/
// Error stuff
int printErr(char *msg, char *f, int l)
{
fprintf(stderr, "[%s - %d]: %s\n", f, l, msg);
return 0;
}
char *printFlag(int boo) { return (boo == TRUE ? "TRUE" : "FALSE"); }
// For signal catching
static void die(int sig)
{
// Insert any GPIO cleaning here.
Off(); // Turn off the 10 bar LED
oledShutdown();
if (sig == SIGINT)
{
printf("SIGINT recieved\n");
if (handle != NULL)
snd_mixer_close(handle);
exit(1);
}
if (sig != 0 && sig != 2)
(void)fprintf(stderr, "caught signal %d\n", sig);
if (sig == 2)
{
(void)fprintf(stderr, "Exiting due to Ctrl + C\n");
if (handle != NULL)
snd_mixer_close(handle);
}
exit(1);
}
// Message everyone that system is shutting down
/*
void wall(char *msg)
{
char message[80];
sprintf(message, "echo %s | wall", msg);
system(message);
}
*/
// Print usage
int usage(const char *progName)
{
//"-pins (shows what pins to use for buttons) \n"
fprintf(stderr, "Usage: %s [OPTION] \n"
"-dir [dir] \n"
"-songs [MP3 files]\n"
"-usb (this reads in any music found in /MUSIC)\n"
"\t-halt (part of -usb\n"
" allows the program to halt the system after\n"
" the 'quit' button was pressed.)\n"
"\t-shuffle (part of -usb; shuffles playlist)\n",
progName);
return EXIT_FAILURE;
}
#if 0
void showPins()
{
printf("Pins for buttons:\n"
"Function\twiringPi\tBCM\tNormal Function\n"
"--------\t--------\t--\t------\n"
"Quit \t 7 \t 4\tGPIO 7\n"
"Rotary A\t"
"Rotary B\t"
);
}
#endif
/*
* 10 LED bar graph for volume
*/
void bitWrite(int n, int b) { if (n <= 7 && n >= 0) data[0] ^= (-b ^ data[0]) & (1 << n); }
void bitClear(int n) { if (n <= 7 && n >= 0) data[0] ^= (0 ^ data[0]) & (1 << n); }
void bitSet(int n) { if (n <= 7 && n >= 0) data[0] ^= (-1 ^ data[0]) & (1 << n); }
// TODO merge Off and On into a single function
void Off()
{
data[0] = 0x0;
backup_data[0] = data[0];
wiringPiSPIDataRW(CE, data, 1);
data[0] = backup_data[0];
digitalWrite(extraLedPins[0], LOW);
digitalWrite(extraLedPins[1], LOW);
}
void On()
{
data[0] = 0b11111111;
backup_data[0] = data[0];
wiringPiSPIDataRW(CE, data, 1);
data[0] = backup_data[0];
digitalWrite(extraLedPins[0], HIGH);
digitalWrite(extraLedPins[1], HIGH);
}
void doGraph(int num)
{
int thisLed, lednum;
_Bool toggle;
if (num < 0 || num > 10) return;
if (num == 0) Off();
else if (num == 10) On();
else
{
for (thisLed = 0; thisLed < 10; thisLed++)
{
lednum = thisLed;
toggle = (thisLed < num);
if (thisLed < 8)
{
lednum = 7 - lednum;
bitWrite(lednum, toggle);
backup_data[0] = data[0];
wiringPiSPIDataRW(CE, data, 1);
data[0] = backup_data[0];
}
else
{
lednum -= 8;
digitalWrite(extraLedPins[lednum], toggle);
}
}
}
}
/*
* Volume control
*
* The following code is borrowed from the MPD project.
* Info can be found here: http://theatticlight.net/posts/My-Embedded-Music-Player-and-Sound-Server
*/
double get_normalized_volume(snd_mixer_elem_t *elem)
{
long max, min, value;
int err;
err = snd_mixer_selem_get_playback_dB_range(elem, &min, &max);
if (err < 0)
{
printErr("Error getting volume", __FILE__, __LINE__);
return 0;
}
err = snd_mixer_selem_get_playback_dB(elem, 0, &value);
if (err < 0)
{
printErr("Error getting volume", __FILE__, __LINE__);
return 0;
}
// Perceived 'loudness' does not scale linearly with the actual decible level
// it scales logarithmically
return exp10((value - max) / 6000.0);
}
// Set the volume from a floating point number 0..1
void set_normalized_volume(snd_mixer_elem_t *elem, double volume)
{
long min, max, value;
int err;
if (volume < 0.017170)
volume = 0.017170;
else if (volume > 1.0)
volume = 1.0;
err = snd_mixer_selem_get_playback_dB_range(elem, &min, &max);
if (err < 0)
{
printErr("Error setting volume", __FILE__, __LINE__);
return;
}
// Perceived 'loudness' does not scale linearly with the actual decible level
// it scales logarithmically
value = lrint(6000.0 * log10(volume)) + max;
snd_mixer_selem_set_playback_dB(elem, 0, value, 0);
}
double map(float x, float x0, float x1, float y0, float y1)
{
float y = y0 + ((y1 - y0) * ((x - x0) / (x1 - x0)));
double z = (double)y;
return z;
}
/*
void print_vol_num(snd_mixer_elem_t *elem)
{
int volbar_length = rint(get_normalized_volume(elem) * (double)CO-1);
int cur_vol = 0;
cur_vol = map(volbar_length, -1, CO - 1, 0, 99);
// lcdPosition(lcdHandle, 14, 1); // XXX
// lcdPrintf(lcdHandle, "%2d", cur_vol); // XXX
}
*/
/*
* OLED setup
*/
int setupOled(int addr, int oType)
{
int iOLEDAddr = 0x3c; // typical address; it can also be 0x3d
int iOLEDType = OLED_128x64; // Change this for your specific display
int bFlip = 0;
int bInvert = 0;
int iChannel = 1;
return oledInit(iChannel, iOLEDAddr, iOLEDType, bFlip, bInvert);
}
/*
* File stuff
*/
// Get the extension
const char *get_filename_ext(const char *filename)
{
const char *dot = strrchr(filename, '.');
if (!dot || dot == filename)
return "";
return dot + 1;
}
// Check to see if the USB flash was mounted or not.
// Mount (if cmd == 1, do not attempt to unmount)
int checkMount()
{
if (mount("/dev/sda1", "/MUSIC", "vfat", MS_RDONLY | MS_SILENT, "") == -1)
{
if (errno == EBUSY) // EBUSY means the filesystem is already mounted so just return OK
return FILES_OK;
else
return MOUNT_ERROR;
}
else
return FILES_OK;
}
/*
* Linked list / playlist functions
*
*/
//int playlist_init(playlist_t *playlistptr)
void playlist_init(playlist_t *playlistptr)
{
*playlistptr = NULL;
// return 1;
}
//int playlist_add_song(int index, void *songptr, playlist_t *playlistptr)
void playlist_add_song(int index, void *songptr, playlist_t *playlistptr)
{
playlist_node_t *cur, *prev, *new;
int found = FALSE;
for (cur = prev = *playlistptr; cur != NULL; prev = cur, cur = cur->nextptr)
{
if (cur->index == index)
{
free(cur->songptr);
cur->songptr = songptr;
found = TRUE;
break;
}
else if (cur->index > index)
break;
}
if (!found)
{
new = (playlist_node_t *)malloc(sizeof(playlist_node_t));
new->index = index;
new->songptr = songptr;
new->nextptr = cur;
if (cur == *playlistptr)
*playlistptr = new;
else
prev->nextptr = new;
}
//return 1;
}
// Get song name from playlist with index
//int playlist_get_song(int index, void **songptr, playlist_t *playlistptr)
void playlist_get_song(int index, void **songptr, playlist_t *playlistptr)
{
playlist_node_t *cur, *prev;
// Initialize to "not found"
*songptr = NULL;
// Look through index for our entry
for (cur = prev = *playlistptr; cur != NULL; prev = cur, cur = cur->nextptr)
{
if (cur->index == index)
{
*songptr = cur->songptr;
break;
}
else if (cur->index > index)
break;
}
//return 1;
}
/*
* Creates playlist
*/
// NOTE: Brand new! Now we read in sub directories!!
// Recursive function to enter sub directories
void list_dir(const char *dir_name)
{
DIR *d;
char *basec, *bname;
char *string;
d = opendir(dir_name);
if (!d)
{
fprintf(stderr, "[%s - %d]: Cannot open directory '%s': %s\n", __FILE__, __LINE__, dir_name, strerror(errno));
exit(EXIT_FAILURE);
}
while (1)
{
struct dirent *dir;
const char *d_name;
dir = readdir(d);
// There are no more entries in this directory, so break out of the while loop.
if (!dir)
break;
d_name = dir->d_name;
// 8 = normal file; non-directory
if (dir->d_type == 8)
{
string = malloc(MAXDATALEN);
if (string == NULL)
perror("malloc: reReadPlaylist");
strcpy(string, dir_name);
strcat(string, "/");
strcat(string, d_name);
// Get just the filename, strip the path info
basec = strdup(string);
bname = basename(basec);
// Make sure we only add mp3 files
if (strcasecmp(get_filename_ext(bname), "mp3") == 0)
playlist_add_song(Index++, string, &Tmp_Playlist); // FIXME I REALLY hate having to use global variables...
}
if (dir->d_type & DT_DIR)
{
// Check that the directory is not "d" or d's parent.
if (strcmp(d_name, "..") != 0 && strcmp(d_name, ".") != 0)
{
int path_length;
char path[PATH_MAX];
path_length = snprintf(path, PATH_MAX, "%s/%s", dir_name, d_name);
if (path_length >= PATH_MAX)
{
fprintf(stderr, "[%s - %d]: Path length has become too long.\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
list_dir(path); // Recursively call "list_dir" with the new path.
}
} // end if dir
} // end while
if (closedir(d))
{
fprintf(stderr, "[%s - %d]: Could not close '%s': %s\n", __FILE__, __LINE__, dir_name, strerror(errno));
exit(EXIT_FAILURE);
}
}
// Create the playlist; NOTE Now we read in sub directories...
// Tmp_Playlist and Index are global vars...
playlist_t reReadPlaylist(char *dir_name)
{
playlist_t new_playlist;
playlist_init(&new_playlist);
playlist_init(&Tmp_Playlist);
Index = 0;
list_dir(dir_name);
new_playlist = Tmp_Playlist;
playlist_init(&Tmp_Playlist);
pthread_mutex_lock(&cur_song.pauseMutex);
num_songs = Index - 1;
pthread_mutex_unlock(&cur_song.pauseMutex);
return new_playlist;
}
// Convert linked list into array so it can be shuffled
void ll2array(playlist_t *playlistptr, char **arr)
{
int i;
playlist_node_t *cur;
for (i = 0, cur = *playlistptr; cur != NULL; i++, cur = cur->nextptr)
{
if (cur->songptr != NULL)
arr[i] = cur->songptr;
}
}
// Shuffle / randomize playlist
playlist_t randomize(playlist_t cur_playlist)
{
char *tmp[MAXDATALEN];
char *string;
playlist_t new_playlist;
int index = 0;
ll2array(&cur_playlist, tmp);
srand((unsigned)time(NULL));
if (num_songs > 1)
{
size_t i;
for (i = 0; i < num_songs - 1; i++)
{
if (strlen(tmp[i]) > 3)
{
size_t j = i + rand() / (RAND_MAX / (num_songs - i) + 1);
char *t = tmp[j];
tmp[j] = tmp[i];
tmp[i] = t;
}
}
}
// Convert array back into linked list.
playlist_init(&new_playlist);
index = 0;
while (index < num_songs)
{
string = malloc(MAXDATALEN);
if (string == NULL)
perror("malloc: shuffle");
strcpy(string, tmp[index]);
playlist_add_song(index, string, &new_playlist);
index++;
}
return new_playlist;
}
/*
* Threading functions
*
* Functions for when buttons are pressed
*/
void nextSong()
{
pthread_mutex_lock(&cur_song.pauseMutex);
cur_song.play_status = NEXT;
cur_song.song_over = TRUE;
pthread_mutex_unlock(&cur_song.pauseMutex);
}
void prevSong()
{
pthread_mutex_lock(&cur_song.pauseMutex);
cur_song.play_status = PREV;
cur_song.song_over = TRUE;
pthread_mutex_unlock(&cur_song.pauseMutex);
}
void shuffleMe()
{
pthread_mutex_lock(&cur_song.pauseMutex);
cur_song.play_status = SHUFFLE;
cur_song.song_over = TRUE;
pthread_mutex_unlock(&cur_song.pauseMutex);
}
void quitMe()
{
pthread_mutex_lock(&cur_song.pauseMutex);
cur_song.play_status = QUIT;
cur_song.song_over = TRUE;
pthread_mutex_unlock(&cur_song.pauseMutex);
}
void pauseMe()
{
pthread_mutex_lock(&cur_song.pauseMutex);
cur_song.play_status = PAUSE;
pthread_mutex_unlock(&cur_song.pauseMutex);
}
void playMe()
{
pthread_mutex_lock(&cur_song.pauseMutex);
cur_song.play_status = PLAY;
pthread_cond_broadcast(&cur_song.m_resumeCond);
pthread_mutex_unlock(&cur_song.pauseMutex);
}
void checkPause()
{
pthread_mutex_lock(&cur_song.pauseMutex);
while (cur_song.play_status == PAUSE)
pthread_cond_wait(&cur_song.m_resumeCond, &cur_song.pauseMutex);
pthread_mutex_unlock(&cur_song.pauseMutex);
}
/*
* MP3 ID3 tag - Attempt to get song/artist/album names from file
*/
// Split up a number of lines separated by \n, \r, both or just zero byte
// and print out each line with specified prefix.
void make_id(mpg123_string *inlines, int type)
{
size_t i;
int hadcr = 0, hadlf = 0;
char *lines = NULL;
char *line = NULL;
size_t len = 0;
char tmp_name[100];
if (inlines != NULL && inlines->fill)
{
lines = inlines->p;
len = inlines->fill;
}
else
return;
line = lines;
for (i = 0; i < len; ++i)
{
if (lines[i] == '\n' || lines[i] == '\r' || lines[i] == 0)
{
// Saving, changing, restoring a byte in the data
char save = lines[i];
if (save == '\n')
++hadlf;
if (save == '\r')
++hadcr;
if ((hadcr || hadlf) && hadlf % 2 == 0 && hadcr % 2 == 0)
line = "";
if (line)
{
lines[i] = 0;
strncpy(tmp_name, line, 100);
line = NULL;
lines[i] = save;
}
}
else
{
hadlf = hadcr = 0;
if (line == NULL)
line = lines + i;
}
}
switch (type)
{
case TITLE: strcpy(cur_song.title, tmp_name); break;
case ARTIST: strcpy(cur_song.artist, tmp_name); break;
case GENRE: strcpy(cur_song.genre, tmp_name); break;
case ALBUM: strcpy(cur_song.album, tmp_name); break;
case YEAR: strcpy(cur_song.year, tmp_name); break;
}
}
int id3_tagger()
{
int meta;
mpg123_handle* m;
mpg123_id3v1 *v1;
mpg123_id3v2 *v2;
// ID3 tag info for the song
mpg123_init();
m = mpg123_new(NULL, NULL);
if (mpg123_open(m, cur_song.filename) != MPG123_OK)
{
fprintf(stderr, "[%s - %d]: Cannot open %s: %s\n", __FILE__, __LINE__, cur_song.filename, mpg123_strerror(m));
return 1;
}
mpg123_scan(m);
meta = mpg123_meta_check(m);
if (meta & MPG123_ID3 && mpg123_id3(m, &v1, &v2) == MPG123_OK)
{
make_id(v2->title, TITLE);
make_id(v2->artist, ARTIST);
make_id(v2->album, ALBUM);
make_id(v2->genre, GENRE);
make_id(v2->year, YEAR);
}
else
{
// TODO fix this; maybe there's a better way since UNKNOWN is all the same
sprintf(cur_song.title, "UNKNOWN");
sprintf(cur_song.artist, "UNKNOWN");
sprintf(cur_song.album, "UNKNOWN");
sprintf(cur_song.genre, "UNKNOWN");
sprintf(cur_song.year, "UNKNOWN");
}
// If there is no title to be found, set title to the song file name.
if (strlen(cur_song.title) == 0)
strcpy(cur_song.title, cur_song.base_filename);
if (strlen(cur_song.artist) == 0)
sprintf(cur_song.artist, "UNKNOWN");
if (strlen(cur_song.album) == 0)
sprintf(cur_song.album, "UNKNOWN");
if (strlen(cur_song.year) == 0)
sprintf(cur_song.year, "UNKNOWN");
// Set the second row to be the artist by default.
strcpy(cur_song.FirstRow_text, cur_song.title);
strcpy(cur_song.SecondRow_text, cur_song.artist);
mpg123_close(m);
mpg123_delete(m);
mpg123_exit();
// The following two lines are just to see when the scrolling should pause
strncpy(cur_song.scroll_FirstRow, cur_song.FirstRow_text, 15);
strncpy(cur_song.scroll_SecondRow, cur_song.SecondRow_text, 16);
return 0;
}
/*
* OLED scroll message
*/
void scroll_msg(int pos, char *msg)
{
char buf[42];
char my_songname[128];
static int position = 0;
static int timer = 0;
int width = 21;
int font_sz = FONT_SMALL;
if (strlen(msg) < 22)
{
oledWriteString(0, pos, msg, font_sz);
}
else
{
// why is this here? what does it do?
/*
if (strcmp(title, prevtitle) != 0)
{
timer = 0;
position = 0;
strcpy(prevtitle, title);
}
*/
//printf("[%s] - %d\n", msg, strlen(msg) + strlen(spaces) + 2);
strcpy(my_songname, " ");
strncat(my_songname, msg, strlen(msg));
strcat(my_songname, spaces);
my_songname[strlen(my_songname) + 1] = 0;
if (millis() < timer)
return;
timer = millis() + 200;
strncpy(buf, &my_songname[position], width);
buf[width] = 0;
oledWriteString(0, pos, buf, font_sz);
position++;
if (position == (strlen(my_songname) - width))
position = 0;
}
}
// XXX the entire LCD portion is no longer used
#if 0
/*
* LCD display functions
*/
// Non-scrolling - Top row
int printLcdFirstRow()
{
int flag = TRUE;
// Do I even use this?
if (strcmp(cur_song.FirstRow_text, " QUIT - Shutdown") == 0)
{
lcdPosition(lcdHandle, 0, 0);
lcdPuts(lcdHandle, cur_song.FirstRow_text);
flag = FALSE;
}
else
{
// Have to set to 15 because of music note
if (strlen(cur_song.FirstRow_text) < 15)
{
// New song; set the previous title
if (strcmp(cur_song.title, cur_song.prevTitle) != 0)
strcpy(cur_song.prevTitle, cur_song.title);
lcdCharDef(lcdHandle, 2, musicNote);
lcdPosition(lcdHandle, 0, 0);
lcdPutchar(lcdHandle, 2);
lcdPosition(lcdHandle, 1, 0);
lcdPuts(lcdHandle, cur_song.FirstRow_text);
flag = FALSE;
}
}
return flag;
}
// Non-scrolling - Bottom row
int printLcdSecondRow()
{
int flag = TRUE;
if (strlen(cur_song.SecondRow_text) < 15)
{
lcdPosition(lcdHandle, 0, 1);
lcdPuts(lcdHandle, cur_song.SecondRow_text);
flag = FALSE;
// New song; set the previous artist
if (strcmp(cur_song.artist, cur_song.prevArtist) != 0)
strcpy(cur_song.prevArtist, cur_song.artist);
}
return flag;
}
// Scrolling - Top row
void scroll_Message_FirstRow(int *pause_Scroll_FirstRow_Flag)
{
char buf[32];
char my_songname[MAXDATALEN];
static int position = 0;
static int timer = 0;
int width = 15;
if (strcmp(cur_song.title, cur_song.prevTitle) != 0)
{
timer = 0;
position = 0;
strcpy(cur_song.prevTitle, cur_song.title);
}
strcpy(my_songname, " ");
strncat(my_songname, cur_song.title, strlen(cur_song.title));
strcat(my_songname, spaces);
my_songname[strlen(my_songname) + 1] = 0;
if (millis() < timer)
return;
timer = millis() + 200;
strncpy(buf, &my_songname[position], width);
buf[width] = 0;
lcdCharDef(lcdHandle, 2, musicNote);
lcdPosition(lcdHandle, 0, 0);
lcdPutchar(lcdHandle, 2);
lcdPosition(lcdHandle, 1, 0);
lcdPuts(lcdHandle, buf);
position++;
if (position == (strlen(my_songname) - width))
position = 0;
// Pause briefly when text reaches begining line before continuing
*pause_Scroll_FirstRow_Flag = (strcmp(buf, cur_song.scroll_FirstRow) == 0 ? TRUE : FALSE);
}
// Scrolling - Bottom row
void scroll_Message_SecondRow(int *pause_Scroll_SecondRow_Flag)
{
char buf[32];
static int position = 0;
static int timer = 0;
int width = 14;
char my_string[MAXDATALEN];
if (strcmp(cur_song.artist, cur_song.prevArtist) != 0)
{
timer = 0;
position = 0;
strcpy(cur_song.prevArtist, cur_song.artist);
}
//strcpy(my_string, spaces);
strcpy(my_string, " ");
strncat(my_string, cur_song.SecondRow_text, strlen(cur_song.SecondRow_text));
strcat(my_string, spaces);
my_string[strlen(my_string) + 1] = 0;
if (millis() < timer)
return;
timer = millis() + 200;
strncpy(buf, &my_string[position], width);
buf[width] = 0;
lcdPosition(lcdHandle, 0, 1);
lcdPuts(lcdHandle, buf);
position++;
if (position == (strlen(my_string) - width))
position = 0;
// Pause briefly when text reaches begining line before continuing
*pause_Scroll_SecondRow_Flag = (strcmp(buf, cur_song.scroll_SecondRow) == 0 ? TRUE : FALSE);
}
#endif
// The actual thing that plays the song
void play_song(void *arguments)
{
struct song_info *args = (struct song_info *)arguments;
mpg123_handle *mh;
mpg123_pars *mpar;
unsigned char *buffer;
size_t buffer_size;
size_t done;
int err;
int driver;
ao_device *dev;
ao_sample_format format;
int channels, encoding;
long rate;
ao_initialize();
driver = ao_default_driver_id();
mpg123_init();
// Try to not show error messages
mh = mpg123_new(NULL, &err);
mpar = mpg123_new_pars(&err);
mpg123_par(mpar, MPG123_ADD_FLAGS, MPG123_QUIET, 0);
mh = mpg123_parnew(mpar, NULL, &err);
buffer_size = mpg123_outblock(mh);
buffer = (unsigned char*) malloc(buffer_size * sizeof(unsigned char));
// Open the file and get the decoding format
mpg123_open(mh, args->filename);
mpg123_getformat(mh, &rate, &channels, &encoding);
// Set the output format and open the output device
format.bits = mpg123_encsize(encoding) * 8;
format.rate = rate;
format.channels = channels;
format.byte_format = AO_FMT_NATIVE;
format.matrix = 0;
dev = ao_open_live(driver, &format, NULL);
// Decode and play
while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
{
checkPause();
ao_play(dev, (char *) buffer, done);
// Stop playing if the user pressed quit, shuffle, next, or prev buttons
if (cur_song.play_status == QUIT || cur_song.play_status == NEXT || cur_song.play_status == PREV || cur_song.play_status == SHUFFLE)
break;
}
// Clean up
free(buffer);
ao_close(dev);
mpg123_close(mh);
mpg123_delete(mh);
mpg123_exit();