Increase MAXTHREADS
[Rockbox.git] / apps / playlist.c
blob676fc1e2c79ea03a6f520fc28f4a915d4d263c5b
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by wavey@wavey.org
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
21 Dynamic playlist design (based on design originally proposed by ricII)
23 There are two files associated with a dynamic playlist:
24 1. Playlist file : This file contains the initial songs in the playlist.
25 The file is created by the user and stored on the hard
26 drive. NOTE: If we are playing the contents of a
27 directory, there will be no playlist file.
28 2. Control file : This file is automatically created when a playlist is
29 started and contains all the commands done to it.
31 The first non-comment line in a control file must begin with
32 "P:VERSION:DIR:FILE" where VERSION is the playlist control file version,
33 DIR is the directory where the playlist is located and FILE is the
34 playlist filename. For dirplay, FILE will be empty. An empty playlist
35 will have both entries as null.
37 Control file commands:
38 a. Add track (A:<position>:<last position>:<path to track>)
39 - Insert a track at the specified position in the current
40 playlist. Last position is used to specify where last insertion
41 occurred.
42 b. Queue track (Q:<position>:<last position>:<path to track>)
43 - Queue a track at the specified position in the current
44 playlist. Queued tracks differ from added tracks in that they
45 are deleted from the playlist as soon as they are played and
46 they are not saved to disk as part of the playlist.
47 c. Delete track (D:<position>)
48 - Delete track from specified position in the current playlist.
49 d. Shuffle playlist (S:<seed>:<index>)
50 - Shuffle entire playlist with specified seed. The index
51 identifies the first index in the newly shuffled playlist
52 (needed for repeat mode).
53 e. Unshuffle playlist (U:<index>)
54 - Unshuffle entire playlist. The index identifies the first index
55 in the newly unshuffled playlist.
56 f. Reset last insert position (R)
57 - Needed so that insertions work properly after resume
59 Resume:
60 The only resume info that needs to be saved is the current index in the
61 playlist and the position in the track. When resuming, all the commands
62 in the control file will be reapplied so that the playlist indices are
63 exactly the same as before shutdown. To avoid unnecessary disk
64 accesses, the shuffle mode settings are also saved in settings and only
65 flushed to disk when required.
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <ctype.h>
72 #include "playlist.h"
73 #include "file.h"
74 #include "action.h"
75 #include "dir.h"
76 #include "sprintf.h"
77 #include "debug.h"
78 #include "audio.h"
79 #include "lcd.h"
80 #include "kernel.h"
81 #include "settings.h"
82 #include "status.h"
83 #include "applimits.h"
84 #include "screens.h"
85 #include "buffer.h"
86 #include "atoi.h"
87 #include "misc.h"
88 #include "button.h"
89 #include "filetree.h"
90 #include "abrepeat.h"
91 #include "thread.h"
92 #include "usb.h"
93 #include "filetypes.h"
94 #ifdef HAVE_LCD_BITMAP
95 #include "icons.h"
96 #endif
98 #include "lang.h"
99 #include "talk.h"
100 #include "splash.h"
101 #include "rbunicode.h"
102 #include "root_menu.h"
104 #define PLAYLIST_CONTROL_FILE ROCKBOX_DIR "/.playlist_control"
105 #define PLAYLIST_CONTROL_FILE_VERSION 2
108 Each playlist index has a flag associated with it which identifies what
109 type of track it is. These flags are stored in the 4 high order bits of
110 the index.
112 NOTE: This limits the playlist file size to a max of 256M.
114 Bits 31-30:
115 00 = Playlist track
116 01 = Track was prepended into playlist
117 10 = Track was inserted into playlist
118 11 = Track was appended into playlist
119 Bit 29:
120 0 = Added track
121 1 = Queued track
122 Bit 28:
123 0 = Track entry is valid
124 1 = Track does not exist on disk and should be skipped
126 #define PLAYLIST_SEEK_MASK 0x0FFFFFFF
127 #define PLAYLIST_INSERT_TYPE_MASK 0xC0000000
128 #define PLAYLIST_QUEUE_MASK 0x20000000
130 #define PLAYLIST_INSERT_TYPE_PREPEND 0x40000000
131 #define PLAYLIST_INSERT_TYPE_INSERT 0x80000000
132 #define PLAYLIST_INSERT_TYPE_APPEND 0xC0000000
134 #define PLAYLIST_QUEUED 0x20000000
135 #define PLAYLIST_SKIPPED 0x10000000
137 #define PLAYLIST_DISPLAY_COUNT 10
139 struct directory_search_context {
140 struct playlist_info* playlist;
141 int position;
142 bool queue;
143 int count;
146 static struct playlist_info current_playlist;
147 static char now_playing[MAX_PATH+1];
149 static void empty_playlist(struct playlist_info* playlist, bool resume);
150 static void new_playlist(struct playlist_info* playlist, const char *dir,
151 const char *file);
152 static void create_control(struct playlist_info* playlist);
153 static int check_control(struct playlist_info* playlist);
154 static int recreate_control(struct playlist_info* playlist);
155 static void update_playlist_filename(struct playlist_info* playlist,
156 const char *dir, const char *file);
157 static int add_indices_to_playlist(struct playlist_info* playlist,
158 char* buffer, size_t buflen);
159 static int add_track_to_playlist(struct playlist_info* playlist,
160 const char *filename, int position,
161 bool queue, int seek_pos);
162 static int directory_search_callback(char* filename, void* context);
163 static int remove_track_from_playlist(struct playlist_info* playlist,
164 int position, bool write);
165 static int randomise_playlist(struct playlist_info* playlist,
166 unsigned int seed, bool start_current,
167 bool write);
168 static int sort_playlist(struct playlist_info* playlist, bool start_current,
169 bool write);
170 static int get_next_index(const struct playlist_info* playlist, int steps,
171 int repeat_mode);
172 static void find_and_set_playlist_index(struct playlist_info* playlist,
173 unsigned int seek);
174 static int compare(const void* p1, const void* p2);
175 static int get_filename(struct playlist_info* playlist, int index, int seek,
176 bool control_file, char *buf, int buf_length);
177 static int get_next_directory(char *dir);
178 static int get_next_dir(char *dir, bool is_forward, bool recursion);
179 static int get_previous_directory(char *dir);
180 static int check_subdir_for_music(char *dir, char *subdir);
181 static int format_track_path(char *dest, char *src, int buf_length, int max,
182 char *dir);
183 static void display_playlist_count(int count, const unsigned char *fmt,
184 bool final);
185 static void display_buffer_full(void);
186 static int flush_cached_control(struct playlist_info* playlist);
187 static int update_control(struct playlist_info* playlist,
188 enum playlist_command command, int i1, int i2,
189 const char* s1, const char* s2, void* data);
190 static void sync_control(struct playlist_info* playlist, bool force);
191 static int rotate_index(const struct playlist_info* playlist, int index);
193 #ifdef HAVE_DIRCACHE
194 #define PLAYLIST_LOAD_POINTERS 1
196 static struct event_queue playlist_queue;
197 static long playlist_stack[(DEFAULT_STACK_SIZE + 0x800)/sizeof(long)];
198 static const char playlist_thread_name[] = "playlist cachectrl";
199 #endif
202 * remove any files and indices associated with the playlist
204 static void empty_playlist(struct playlist_info* playlist, bool resume)
206 playlist->filename[0] = '\0';
207 playlist->utf8 = true;
209 if(playlist->fd >= 0)
210 /* If there is an already open playlist, close it. */
211 close(playlist->fd);
212 playlist->fd = -1;
214 if(playlist->control_fd >= 0)
215 close(playlist->control_fd);
216 playlist->control_fd = -1;
217 playlist->control_created = false;
219 playlist->in_ram = false;
221 if (playlist->buffer)
222 playlist->buffer[0] = 0;
224 playlist->buffer_end_pos = 0;
226 playlist->index = 0;
227 playlist->first_index = 0;
228 playlist->amount = 0;
229 playlist->last_insert_pos = -1;
230 playlist->seed = 0;
231 playlist->shuffle_modified = false;
232 playlist->deleted = false;
233 playlist->num_inserted_tracks = 0;
234 playlist->started = false;
236 playlist->num_cached = 0;
237 playlist->pending_control_sync = false;
239 if (!resume && playlist->current)
241 /* start with fresh playlist control file when starting new
242 playlist */
243 create_control(playlist);
245 /* Reset resume settings */
246 global_status.resume_first_index = 0;
247 global_status.resume_seed = -1;
252 * Initialize a new playlist for viewing/editing/playing. dir is the
253 * directory where the playlist is located and file is the filename.
255 static void new_playlist(struct playlist_info* playlist, const char *dir,
256 const char *file)
258 empty_playlist(playlist, false);
260 if (!file)
262 file = "";
264 if (dir && playlist->current) /* !current cannot be in_ram */
265 playlist->in_ram = true;
266 else
267 dir = ""; /* empty playlist */
270 update_playlist_filename(playlist, dir, file);
272 if (playlist->control_fd >= 0)
274 update_control(playlist, PLAYLIST_COMMAND_PLAYLIST,
275 PLAYLIST_CONTROL_FILE_VERSION, -1, dir, file, NULL);
276 sync_control(playlist, false);
281 * create control file for playlist
283 static void create_control(struct playlist_info* playlist)
285 playlist->control_fd = open(playlist->control_filename,
286 O_CREAT|O_RDWR|O_TRUNC);
287 if (playlist->control_fd < 0)
289 if (check_rockboxdir())
291 cond_talk_ids_fq(LANG_PLAYLIST_CONTROL_ACCESS_ERROR);
292 gui_syncsplash(HZ*2, (unsigned char *)"%s (%d)",
293 str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR),
294 playlist->control_fd);
296 playlist->control_created = false;
298 else
300 playlist->control_created = true;
305 * validate the control file. This may include creating/initializing it if
306 * necessary;
308 static int check_control(struct playlist_info* playlist)
310 if (!playlist->control_created)
312 create_control(playlist);
314 if (playlist->control_fd >= 0)
316 char* dir = playlist->filename;
317 char* file = playlist->filename+playlist->dirlen;
318 char c = playlist->filename[playlist->dirlen-1];
320 playlist->filename[playlist->dirlen-1] = '\0';
322 update_control(playlist, PLAYLIST_COMMAND_PLAYLIST,
323 PLAYLIST_CONTROL_FILE_VERSION, -1, dir, file, NULL);
324 sync_control(playlist, false);
325 playlist->filename[playlist->dirlen-1] = c;
329 if (playlist->control_fd < 0)
330 return -1;
332 return 0;
336 * recreate the control file based on current playlist entries
338 static int recreate_control(struct playlist_info* playlist)
340 char temp_file[MAX_PATH+1];
341 int temp_fd = -1;
342 int i;
343 int result = 0;
345 if(playlist->control_fd >= 0)
347 char* dir = playlist->filename;
348 char* file = playlist->filename+playlist->dirlen;
349 char c = playlist->filename[playlist->dirlen-1];
351 close(playlist->control_fd);
353 snprintf(temp_file, sizeof(temp_file), "%s_temp",
354 playlist->control_filename);
356 if (rename(playlist->control_filename, temp_file) < 0)
357 return -1;
359 temp_fd = open(temp_file, O_RDONLY);
360 if (temp_fd < 0)
361 return -1;
363 playlist->control_fd = open(playlist->control_filename,
364 O_CREAT|O_RDWR|O_TRUNC);
365 if (playlist->control_fd < 0)
366 return -1;
368 playlist->filename[playlist->dirlen-1] = '\0';
370 /* cannot call update_control() because of mutex */
371 result = fdprintf(playlist->control_fd, "P:%d:%s:%s\n",
372 PLAYLIST_CONTROL_FILE_VERSION, dir, file);
374 playlist->filename[playlist->dirlen-1] = c;
376 if (result < 0)
378 close(temp_fd);
379 return result;
383 playlist->seed = 0;
384 playlist->shuffle_modified = false;
385 playlist->deleted = false;
386 playlist->num_inserted_tracks = 0;
388 if (playlist->current)
390 global_status.resume_seed = -1;
391 status_save();
394 for (i=0; i<playlist->amount; i++)
396 if (playlist->indices[i] & PLAYLIST_INSERT_TYPE_MASK)
398 bool queue = playlist->indices[i] & PLAYLIST_QUEUE_MASK;
399 char inserted_file[MAX_PATH+1];
401 lseek(temp_fd, playlist->indices[i] & PLAYLIST_SEEK_MASK,
402 SEEK_SET);
403 read_line(temp_fd, inserted_file, sizeof(inserted_file));
405 result = fdprintf(playlist->control_fd, "%c:%d:%d:",
406 queue?'Q':'A', i, playlist->last_insert_pos);
407 if (result > 0)
409 /* save the position in file where name is written */
410 int seek_pos = lseek(playlist->control_fd, 0, SEEK_CUR);
412 result = fdprintf(playlist->control_fd, "%s\n",
413 inserted_file);
415 playlist->indices[i] =
416 (playlist->indices[i] & ~PLAYLIST_SEEK_MASK) | seek_pos;
419 if (result < 0)
420 break;
422 playlist->num_inserted_tracks++;
426 close(temp_fd);
427 remove(temp_file);
428 fsync(playlist->control_fd);
430 if (result < 0)
431 return result;
433 return 0;
437 * store directory and name of playlist file
439 static void update_playlist_filename(struct playlist_info* playlist,
440 const char *dir, const char *file)
442 char *sep="";
443 int dirlen = strlen(dir);
444 int filelen = strlen(file);
446 /* Default to utf8 unless explicitly told otherwise. */
447 playlist->utf8 = !(filelen > 4 && strcasecmp(&file[filelen - 4], ".m3u") == 0);
449 /* If the dir does not end in trailing slash, we use a separator.
450 Otherwise we don't. */
451 if('/' != dir[dirlen-1])
453 sep="/";
454 dirlen++;
457 playlist->dirlen = dirlen;
459 snprintf(playlist->filename, sizeof(playlist->filename),
460 "%s%s%s", dir, sep, file);
464 * calculate track offsets within a playlist file
466 static int add_indices_to_playlist(struct playlist_info* playlist,
467 char* buffer, size_t buflen)
469 unsigned int nread;
470 unsigned int i = 0;
471 unsigned int count = 0;
472 bool store_index;
473 unsigned char *p;
474 int result = 0;
476 if(-1 == playlist->fd)
477 playlist->fd = open(playlist->filename, O_RDONLY);
478 if(playlist->fd < 0)
479 return -1; /* failure */
481 #ifdef HAVE_LCD_BITMAP
482 if(global_settings.statusbar)
483 lcd_setmargins(0, STATUSBAR_HEIGHT);
484 else
485 lcd_setmargins(0, 0);
486 #endif
487 gui_syncsplash(0, ID2P(LANG_WAIT));
489 if (!buffer)
491 /* use mp3 buffer for maximum load speed */
492 audio_stop();
493 #if CONFIG_CODEC != SWCODEC
494 talk_buffer_steal(); /* we use the mp3 buffer, need to tell */
495 buflen = (audiobufend - audiobuf);
496 buffer = (char *)audiobuf;
497 #else
498 buffer = (char *)audio_get_buffer(false, &buflen);
499 #endif
502 store_index = true;
504 while(1)
506 nread = read(playlist->fd, buffer, buflen);
507 /* Terminate on EOF */
508 if(nread <= 0)
509 break;
511 p = (unsigned char *)buffer;
513 /* utf8 BOM at beginning of file? */
514 if(i == 0 && nread > 3
515 && *p == 0xef && *(p+1) == 0xbb && *(p+2) == 0xbf) {
516 nread -= 3;
517 p += 3;
518 i += 3;
519 playlist->utf8 = true; /* Override any earlier indication. */
522 for(count=0; count < nread; count++,p++) {
524 /* Are we on a new line? */
525 if((*p == '\n') || (*p == '\r'))
527 store_index = true;
529 else if(store_index)
531 store_index = false;
533 if(*p != '#')
535 if ( playlist->amount >= playlist->max_playlist_size ) {
536 display_buffer_full();
537 result = -1;
538 goto exit;
541 /* Store a new entry */
542 playlist->indices[ playlist->amount ] = i+count;
543 #ifdef HAVE_DIRCACHE
544 if (playlist->filenames)
545 playlist->filenames[ playlist->amount ] = NULL;
546 #endif
547 playlist->amount++;
552 i+= count;
555 exit:
556 #ifdef HAVE_DIRCACHE
557 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
558 #endif
560 return result;
564 * Utility function to create a new playlist, fill it with the next or
565 * previous directory, shuffle it if needed, and start playback.
566 * If play_last is true and direction zero or negative, start playing
567 * the last file in the directory, otherwise start playing the first.
569 static int create_and_play_dir(int direction, bool play_last)
571 char dir[MAX_PATH + 1];
572 int res;
573 int index = -1;
575 if(direction > 0)
576 res = get_next_directory(dir);
577 else
578 res = get_previous_directory(dir);
580 if (!res)
582 if (playlist_create(dir, NULL) != -1)
584 ft_build_playlist(tree_get_context(), 0);
586 if (global_settings.playlist_shuffle)
587 playlist_shuffle(current_tick, -1);
589 if (play_last && direction <= 0)
590 index = current_playlist.amount - 1;
591 else
592 index = 0;
594 #if (CONFIG_CODEC != SWCODEC)
595 playlist_start(index, 0);
596 #endif
600 return index;
604 * Removes all tracks, from the playlist, leaving the presently playing
605 * track queued.
607 int remove_all_tracks(struct playlist_info *playlist)
609 int result;
611 if (playlist == NULL)
612 playlist = &current_playlist;
614 while (playlist->index > 0)
615 if ((result = remove_track_from_playlist(playlist, 0, true)) < 0)
616 return result;
618 while (playlist->amount > 1)
619 if ((result = remove_track_from_playlist(playlist, 1, true)) < 0)
620 return result;
622 if (playlist->amount == 1) {
623 playlist->indices[0] |= PLAYLIST_QUEUED;
626 return 0;
631 * Add track to playlist at specified position. There are five special
632 * positions that can be specified:
633 * PLAYLIST_PREPEND - Add track at beginning of playlist
634 * PLAYLIST_INSERT - Add track after current song. NOTE: If
635 * there are already inserted tracks then track
636 * is added to the end of the insertion list
637 * PLAYLIST_INSERT_FIRST - Add track immediately after current song, no
638 * matter what other tracks have been inserted
639 * PLAYLIST_INSERT_LAST - Add track to end of playlist
640 * PLAYLIST_INSERT_SHUFFLED - Add track at some random point between the
641 * current playing track and end of playlist
642 * PLAYLIST_REPLACE - Erase current playlist, Cue the current track
643 * and inster this track at the end.
645 static int add_track_to_playlist(struct playlist_info* playlist,
646 const char *filename, int position,
647 bool queue, int seek_pos)
649 int insert_position, orig_position;
650 unsigned long flags = PLAYLIST_INSERT_TYPE_INSERT;
651 int i;
653 insert_position = orig_position = position;
655 if (playlist->amount >= playlist->max_playlist_size)
657 display_buffer_full();
658 return -1;
661 switch (position)
663 case PLAYLIST_PREPEND:
664 position = insert_position = playlist->first_index;
665 break;
666 case PLAYLIST_INSERT:
667 /* if there are already inserted tracks then add track to end of
668 insertion list else add after current playing track */
669 if (playlist->last_insert_pos >= 0 &&
670 playlist->last_insert_pos < playlist->amount &&
671 (playlist->indices[playlist->last_insert_pos]&
672 PLAYLIST_INSERT_TYPE_MASK) == PLAYLIST_INSERT_TYPE_INSERT)
673 position = insert_position = playlist->last_insert_pos+1;
674 else if (playlist->amount > 0)
675 position = insert_position = playlist->index + 1;
676 else
677 position = insert_position = 0;
679 if (playlist->started)
680 playlist->last_insert_pos = position;
681 break;
682 case PLAYLIST_INSERT_FIRST:
683 if (playlist->amount > 0)
684 position = insert_position = playlist->index + 1;
685 else
686 position = insert_position = 0;
688 if (playlist->last_insert_pos < 0 && playlist->started)
689 playlist->last_insert_pos = position;
690 break;
691 case PLAYLIST_INSERT_LAST:
692 if (playlist->first_index > 0)
693 position = insert_position = playlist->first_index;
694 else
695 position = insert_position = playlist->amount;
696 break;
697 case PLAYLIST_INSERT_SHUFFLED:
699 if (playlist->started)
701 int offset;
702 int n = playlist->amount -
703 rotate_index(playlist, playlist->index);
705 if (n > 0)
706 offset = rand() % n;
707 else
708 offset = 0;
710 position = playlist->index + offset + 1;
711 if (position >= playlist->amount)
712 position -= playlist->amount;
714 insert_position = position;
716 else
717 position = insert_position = (rand() % (playlist->amount+1));
718 break;
720 case PLAYLIST_REPLACE:
721 if (remove_all_tracks(playlist) < 0)
722 return -1;
724 position = insert_position = playlist->index + 1;
725 break;
728 if (queue)
729 flags |= PLAYLIST_QUEUED;
731 /* shift indices so that track can be added */
732 for (i=playlist->amount; i>insert_position; i--)
734 playlist->indices[i] = playlist->indices[i-1];
735 #ifdef HAVE_DIRCACHE
736 if (playlist->filenames)
737 playlist->filenames[i] = playlist->filenames[i-1];
738 #endif
741 /* update stored indices if needed */
742 if (playlist->amount > 0 && insert_position <= playlist->index &&
743 playlist->started)
744 playlist->index++;
746 if (playlist->amount > 0 && insert_position <= playlist->first_index &&
747 orig_position != PLAYLIST_PREPEND && playlist->started)
749 playlist->first_index++;
751 if (seek_pos < 0 && playlist->current)
753 global_status.resume_first_index = playlist->first_index;
754 status_save();
758 if (insert_position < playlist->last_insert_pos ||
759 (insert_position == playlist->last_insert_pos && position < 0))
760 playlist->last_insert_pos++;
762 if (seek_pos < 0 && playlist->control_fd >= 0)
764 int result = update_control(playlist,
765 (queue?PLAYLIST_COMMAND_QUEUE:PLAYLIST_COMMAND_ADD), position,
766 playlist->last_insert_pos, filename, NULL, &seek_pos);
768 if (result < 0)
769 return result;
772 playlist->indices[insert_position] = flags | seek_pos;
774 #ifdef HAVE_DIRCACHE
775 if (playlist->filenames)
776 playlist->filenames[insert_position] = NULL;
777 #endif
779 playlist->amount++;
780 playlist->num_inserted_tracks++;
782 return insert_position;
786 * Callback for playlist_directory_tracksearch to insert track into
787 * playlist.
789 static int directory_search_callback(char* filename, void* context)
791 struct directory_search_context* c =
792 (struct directory_search_context*) context;
793 int insert_pos;
795 insert_pos = add_track_to_playlist(c->playlist, filename, c->position,
796 c->queue, -1);
798 if (insert_pos < 0)
799 return -1;
801 (c->count)++;
803 /* Make sure tracks are inserted in correct order if user requests
804 INSERT_FIRST */
805 if (c->position == PLAYLIST_INSERT_FIRST || c->position >= 0)
806 c->position = insert_pos + 1;
808 if (((c->count)%PLAYLIST_DISPLAY_COUNT) == 0)
810 unsigned char* count_str;
812 if (c->queue)
813 count_str = ID2P(LANG_PLAYLIST_QUEUE_COUNT);
814 else
815 count_str = ID2P(LANG_PLAYLIST_INSERT_COUNT);
817 display_playlist_count(c->count, count_str, false);
819 if ((c->count) == PLAYLIST_DISPLAY_COUNT &&
820 (audio_status() & AUDIO_STATUS_PLAY) &&
821 c->playlist->started)
822 audio_flush_and_reload_tracks();
825 return 0;
829 * remove track at specified position
831 static int remove_track_from_playlist(struct playlist_info* playlist,
832 int position, bool write)
834 int i;
835 bool inserted;
837 if (playlist->amount <= 0)
838 return -1;
840 inserted = playlist->indices[position] & PLAYLIST_INSERT_TYPE_MASK;
842 /* shift indices now that track has been removed */
843 for (i=position; i<playlist->amount; i++)
845 playlist->indices[i] = playlist->indices[i+1];
846 #ifdef HAVE_DIRCACHE
847 if (playlist->filenames)
848 playlist->filenames[i] = playlist->filenames[i+1];
849 #endif
852 playlist->amount--;
854 if (inserted)
855 playlist->num_inserted_tracks--;
856 else
857 playlist->deleted = true;
859 /* update stored indices if needed */
860 if (position < playlist->index)
861 playlist->index--;
863 if (position < playlist->first_index)
865 playlist->first_index--;
867 if (write)
869 global_status.resume_first_index = playlist->first_index;
870 status_save();
874 if (position <= playlist->last_insert_pos)
875 playlist->last_insert_pos--;
877 if (write && playlist->control_fd >= 0)
879 int result = update_control(playlist, PLAYLIST_COMMAND_DELETE,
880 position, -1, NULL, NULL, NULL);
882 if (result < 0)
883 return result;
885 sync_control(playlist, false);
888 return 0;
892 * randomly rearrange the array of indices for the playlist. If start_current
893 * is true then update the index to the new index of the current playing track
895 static int randomise_playlist(struct playlist_info* playlist,
896 unsigned int seed, bool start_current,
897 bool write)
899 int count;
900 int candidate;
901 long store;
902 unsigned int current = playlist->indices[playlist->index];
904 /* seed 0 is used to identify sorted playlist for resume purposes */
905 if (seed == 0)
906 seed = 1;
908 /* seed with the given seed */
909 srand(seed);
911 /* randomise entire indices list */
912 for(count = playlist->amount - 1; count >= 0; count--)
914 /* the rand is from 0 to RAND_MAX, so adjust to our value range */
915 candidate = rand() % (count + 1);
917 /* now swap the values at the 'count' and 'candidate' positions */
918 store = playlist->indices[candidate];
919 playlist->indices[candidate] = playlist->indices[count];
920 playlist->indices[count] = store;
921 #ifdef HAVE_DIRCACHE
922 if (playlist->filenames)
924 store = (long)playlist->filenames[candidate];
925 playlist->filenames[candidate] = playlist->filenames[count];
926 playlist->filenames[count] = (struct dircache_entry *)store;
928 #endif
931 if (start_current)
932 find_and_set_playlist_index(playlist, current);
934 /* indices have been moved so last insert position is no longer valid */
935 playlist->last_insert_pos = -1;
937 playlist->seed = seed;
938 if (playlist->num_inserted_tracks > 0 || playlist->deleted)
939 playlist->shuffle_modified = true;
941 if (write)
943 update_control(playlist, PLAYLIST_COMMAND_SHUFFLE, seed,
944 playlist->first_index, NULL, NULL, NULL);
945 global_status.resume_seed = seed;
946 status_save();
949 return 0;
953 * Sort the array of indices for the playlist. If start_current is true then
954 * set the index to the new index of the current song.
956 static int sort_playlist(struct playlist_info* playlist, bool start_current,
957 bool write)
959 unsigned int current = playlist->indices[playlist->index];
961 if (playlist->amount > 0)
962 qsort(playlist->indices, playlist->amount,
963 sizeof(playlist->indices[0]), compare);
965 #ifdef HAVE_DIRCACHE
966 /** We need to re-check the song names from disk because qsort can't
967 * sort two arrays at once :/
968 * FIXME: Please implement a better way to do this. */
969 memset(playlist->filenames, 0, playlist->max_playlist_size * sizeof(int));
970 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
971 #endif
973 if (start_current)
974 find_and_set_playlist_index(playlist, current);
976 /* indices have been moved so last insert position is no longer valid */
977 playlist->last_insert_pos = -1;
979 if (!playlist->num_inserted_tracks && !playlist->deleted)
980 playlist->shuffle_modified = false;
981 if (write && playlist->control_fd >= 0)
983 update_control(playlist, PLAYLIST_COMMAND_UNSHUFFLE,
984 playlist->first_index, -1, NULL, NULL, NULL);
985 global_status.resume_seed = 0;
986 status_save();
989 return 0;
992 /* Calculate how many steps we have to really step when skipping entries
993 * marked as bad.
995 static int calculate_step_count(const struct playlist_info *playlist, int steps)
997 int i, count, direction;
998 int index;
999 int stepped_count = 0;
1001 if (steps < 0)
1003 direction = -1;
1004 count = -steps;
1006 else
1008 direction = 1;
1009 count = steps;
1012 index = playlist->index;
1013 i = 0;
1014 do {
1015 /* Boundary check */
1016 if (index < 0)
1017 index += playlist->amount;
1018 if (index >= playlist->amount)
1019 index -= playlist->amount;
1021 /* Check if we found a bad entry. */
1022 if (playlist->indices[index] & PLAYLIST_SKIPPED)
1024 steps += direction;
1025 /* Are all entries bad? */
1026 if (stepped_count++ > playlist->amount)
1027 break ;
1029 else
1030 i++;
1032 index += direction;
1033 } while (i <= count);
1035 return steps;
1038 /* Marks the index of the track to be skipped that is "steps" away from
1039 * current playing track.
1041 void playlist_skip_entry(struct playlist_info *playlist, int steps)
1043 int index;
1045 if (playlist == NULL)
1046 playlist = &current_playlist;
1048 /* need to account for already skipped tracks */
1049 steps = calculate_step_count(playlist, steps);
1051 index = playlist->index + steps;
1052 if (index < 0)
1053 index += playlist->amount;
1054 else if (index >= playlist->amount)
1055 index -= playlist->amount;
1057 playlist->indices[index] |= PLAYLIST_SKIPPED;
1061 * returns the index of the track that is "steps" away from current playing
1062 * track.
1064 static int get_next_index(const struct playlist_info* playlist, int steps,
1065 int repeat_mode)
1067 int current_index = playlist->index;
1068 int next_index = -1;
1070 if (playlist->amount <= 0)
1071 return -1;
1073 if (repeat_mode == -1)
1074 repeat_mode = global_settings.repeat_mode;
1076 if (repeat_mode == REPEAT_SHUFFLE && playlist->amount <= 1)
1077 repeat_mode = REPEAT_ALL;
1079 steps = calculate_step_count(playlist, steps);
1080 switch (repeat_mode)
1082 case REPEAT_SHUFFLE:
1083 /* Treat repeat shuffle just like repeat off. At end of playlist,
1084 play will be resumed in playlist_next() */
1085 case REPEAT_OFF:
1087 current_index = rotate_index(playlist, current_index);
1088 next_index = current_index+steps;
1089 if ((next_index < 0) || (next_index >= playlist->amount))
1090 next_index = -1;
1091 else
1092 next_index = (next_index+playlist->first_index) %
1093 playlist->amount;
1095 break;
1098 case REPEAT_ONE:
1099 #ifdef AB_REPEAT_ENABLE
1100 case REPEAT_AB:
1101 #endif
1102 next_index = current_index;
1103 break;
1105 case REPEAT_ALL:
1106 default:
1108 next_index = (current_index+steps) % playlist->amount;
1109 while (next_index < 0)
1110 next_index += playlist->amount;
1112 if (steps >= playlist->amount)
1114 int i, index;
1116 index = next_index;
1117 next_index = -1;
1119 /* second time around so skip the queued files */
1120 for (i=0; i<playlist->amount; i++)
1122 if (playlist->indices[index] & PLAYLIST_QUEUE_MASK)
1123 index = (index+1) % playlist->amount;
1124 else
1126 next_index = index;
1127 break;
1131 break;
1135 /* No luck if the whole playlist was bad. */
1136 if (playlist->indices[next_index] & PLAYLIST_SKIPPED)
1137 return -1;
1139 return next_index;
1143 * Search for the seek track and set appropriate indices. Used after shuffle
1144 * to make sure the current index is still pointing to correct track.
1146 static void find_and_set_playlist_index(struct playlist_info* playlist,
1147 unsigned int seek)
1149 int i;
1151 /* Set the index to the current song */
1152 for (i=0; i<playlist->amount; i++)
1154 if (playlist->indices[i] == seek)
1156 playlist->index = playlist->first_index = i;
1158 if (playlist->current)
1160 global_status.resume_first_index = i;
1161 status_save();
1164 break;
1170 * used to sort track indices. Sort order is as follows:
1171 * 1. Prepended tracks (in prepend order)
1172 * 2. Playlist/directory tracks (in playlist order)
1173 * 3. Inserted/Appended tracks (in insert order)
1175 static int compare(const void* p1, const void* p2)
1177 unsigned long* e1 = (unsigned long*) p1;
1178 unsigned long* e2 = (unsigned long*) p2;
1179 unsigned long flags1 = *e1 & PLAYLIST_INSERT_TYPE_MASK;
1180 unsigned long flags2 = *e2 & PLAYLIST_INSERT_TYPE_MASK;
1182 if (flags1 == flags2)
1183 return (*e1 & PLAYLIST_SEEK_MASK) - (*e2 & PLAYLIST_SEEK_MASK);
1184 else if (flags1 == PLAYLIST_INSERT_TYPE_PREPEND ||
1185 flags2 == PLAYLIST_INSERT_TYPE_APPEND)
1186 return -1;
1187 else if (flags1 == PLAYLIST_INSERT_TYPE_APPEND ||
1188 flags2 == PLAYLIST_INSERT_TYPE_PREPEND)
1189 return 1;
1190 else if (flags1 && flags2)
1191 return (*e1 & PLAYLIST_SEEK_MASK) - (*e2 & PLAYLIST_SEEK_MASK);
1192 else
1193 return *e1 - *e2;
1196 #ifdef HAVE_DIRCACHE
1198 * Thread to update filename pointers to dircache on background
1199 * without affecting playlist load up performance. This thread also flushes
1200 * any pending control commands when the disk spins up.
1202 static void playlist_thread(void)
1204 struct queue_event ev;
1205 bool dirty_pointers = false;
1206 static char tmp[MAX_PATH+1];
1208 struct playlist_info *playlist;
1209 int index;
1210 int seek;
1211 bool control_file;
1213 int sleep_time = 5;
1215 #ifndef HAVE_FLASH_STORAGE
1216 if (global_settings.disk_spindown > 1 &&
1217 global_settings.disk_spindown <= 5)
1218 sleep_time = global_settings.disk_spindown - 1;
1219 #endif
1221 while (1)
1223 queue_wait_w_tmo(&playlist_queue, &ev, HZ*sleep_time);
1225 switch (ev.id)
1227 case PLAYLIST_LOAD_POINTERS:
1228 dirty_pointers = true;
1229 break ;
1231 /* Start the background scanning after either the disk spindown
1232 timeout or 5s, whichever is less */
1233 case SYS_TIMEOUT:
1234 playlist = &current_playlist;
1236 if (playlist->control_fd >= 0
1237 # ifndef SIMULATOR
1238 && ata_disk_is_active()
1239 # endif
1242 if (playlist->num_cached > 0)
1244 mutex_lock(&playlist->control_mutex);
1245 flush_cached_control(playlist);
1246 mutex_unlock(&playlist->control_mutex);
1249 sync_control(playlist, true);
1252 if (!dirty_pointers)
1253 break ;
1255 if (!dircache_is_enabled() || !playlist->filenames
1256 || playlist->amount <= 0)
1257 break ;
1259 #ifdef HAVE_ADJUSTABLE_CPU_FREQ
1260 cpu_boost(true);
1261 #endif
1262 for (index = 0; index < playlist->amount
1263 && queue_empty(&playlist_queue); index++)
1265 /* Process only pointers that are not already loaded. */
1266 if (playlist->filenames[index])
1267 continue ;
1269 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
1270 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
1272 /* Load the filename from playlist file. */
1273 if (get_filename(playlist, index, seek, control_file, tmp,
1274 sizeof(tmp)) < 0)
1275 break ;
1277 /* Set the dircache entry pointer. */
1278 playlist->filenames[index] = dircache_get_entry_ptr(tmp);
1280 /* And be on background so user doesn't notice any delays. */
1281 yield();
1284 #ifdef HAVE_ADJUSTABLE_CPU_FREQ
1285 cpu_boost(false);
1286 #endif
1287 dirty_pointers = false;
1288 break ;
1290 #ifndef SIMULATOR
1291 case SYS_USB_CONNECTED:
1292 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1293 usb_wait_for_disconnect(&playlist_queue);
1294 break ;
1295 #endif
1299 #endif
1302 * gets pathname for track at seek index
1304 static int get_filename(struct playlist_info* playlist, int index, int seek,
1305 bool control_file, char *buf, int buf_length)
1307 int fd;
1308 int max = -1;
1309 char tmp_buf[MAX_PATH+1];
1310 char dir_buf[MAX_PATH+1];
1312 if (buf_length > MAX_PATH+1)
1313 buf_length = MAX_PATH+1;
1315 #ifdef HAVE_DIRCACHE
1316 if (dircache_is_enabled() && playlist->filenames)
1318 if (playlist->filenames[index] != NULL)
1320 dircache_copy_path(playlist->filenames[index], tmp_buf, sizeof(tmp_buf)-1);
1321 max = strlen(tmp_buf) + 1;
1324 #else
1325 (void)index;
1326 #endif
1328 if (playlist->in_ram && !control_file && max < 0)
1330 strncpy(tmp_buf, &playlist->buffer[seek], sizeof(tmp_buf));
1331 tmp_buf[MAX_PATH] = '\0';
1332 max = strlen(tmp_buf) + 1;
1334 else if (max < 0)
1336 mutex_lock(&playlist->control_mutex);
1338 if (control_file)
1339 fd = playlist->control_fd;
1340 else
1342 if(-1 == playlist->fd)
1343 playlist->fd = open(playlist->filename, O_RDONLY);
1345 fd = playlist->fd;
1348 if(-1 != fd)
1351 if (lseek(fd, seek, SEEK_SET) != seek)
1352 max = -1;
1353 else
1355 max = read(fd, tmp_buf, MIN((size_t) buf_length, sizeof(tmp_buf)));
1357 if ((max > 0) && !playlist->utf8)
1359 char* end;
1360 int i = 0;
1362 /* Locate EOL. */
1363 while ((tmp_buf[i] != '\n') && (tmp_buf[i] != '\r')
1364 && (i < max))
1366 i++;
1369 /* Now work back killing white space. */
1370 while ((i > 0) && isspace(tmp_buf[i - 1]))
1372 i--;
1375 /* Borrow dir_buf a little... */
1376 /* TODO: iso_decode can overflow dir_buf; it really
1377 * should take a dest size argument.
1379 end = iso_decode(tmp_buf, dir_buf, -1, i);
1380 *end = 0;
1381 strncpy(tmp_buf, dir_buf, sizeof(tmp_buf));
1382 tmp_buf[sizeof(tmp_buf) - 1] = 0;
1383 max = strlen(tmp_buf);
1388 mutex_unlock(&playlist->control_mutex);
1390 if (max < 0)
1392 if (control_file)
1393 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
1394 else
1395 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
1397 return max;
1401 strncpy(dir_buf, playlist->filename, playlist->dirlen-1);
1402 dir_buf[playlist->dirlen-1] = 0;
1404 return (format_track_path(buf, tmp_buf, buf_length, max, dir_buf));
1407 static int get_next_directory(char *dir){
1408 return get_next_dir(dir,true,false);
1411 static int get_previous_directory(char *dir){
1412 return get_next_dir(dir,false,false);
1416 * search through all the directories (starting with the current) to find
1417 * one that has tracks to play
1419 static int get_next_dir(char *dir, bool is_forward, bool recursion)
1421 struct playlist_info* playlist = &current_playlist;
1422 int result = -1;
1423 int sort_dir = global_settings.sort_dir;
1424 char *start_dir = NULL;
1425 bool exit = false;
1426 struct tree_context* tc = tree_get_context();
1427 int dirfilter = *(tc->dirfilter);
1429 if (global_settings.next_folder == FOLDER_ADVANCE_RANDOM)
1431 int fd = open(ROCKBOX_DIR "/folder_advance_list.dat",O_RDONLY);
1432 char buffer[MAX_PATH];
1433 int folder_count = 0,i;
1434 srand(current_tick);
1435 *(tc->dirfilter) = SHOW_MUSIC;
1436 if (fd >= 0)
1438 read(fd,&folder_count,sizeof(int));
1439 while (!exit)
1441 i = rand()%folder_count;
1442 lseek(fd,sizeof(int) + (MAX_PATH*i),SEEK_SET);
1443 read(fd,buffer,MAX_PATH);
1444 if (check_subdir_for_music(buffer,"") ==0)
1445 exit = true;
1447 strcpy(dir,buffer);
1448 close(fd);
1449 *(tc->dirfilter) = dirfilter;
1450 reload_directory();
1451 return 0;
1454 /* not random folder advance */
1455 if (recursion){
1456 /* start with root */
1457 dir[0] = '\0';
1459 else{
1460 /* start with current directory */
1461 strncpy(dir, playlist->filename, playlist->dirlen-1);
1462 dir[playlist->dirlen-1] = '\0';
1465 /* use the tree browser dircache to load files */
1466 *(tc->dirfilter) = SHOW_ALL;
1468 /* sort in another direction if previous dir is requested */
1469 if(!is_forward){
1470 if ((global_settings.sort_dir == 0) || (global_settings.sort_dir == 3))
1471 global_settings.sort_dir = 4;
1472 else if (global_settings.sort_dir == 1)
1473 global_settings.sort_dir = 2;
1474 else if (global_settings.sort_dir == 2)
1475 global_settings.sort_dir = 1;
1476 else if (global_settings.sort_dir == 4)
1477 global_settings.sort_dir = 0;
1480 while (!exit)
1482 struct entry *files;
1483 int num_files = 0;
1484 int i;
1486 if (ft_load(tc, (dir[0]=='\0')?"/":dir) < 0)
1488 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));
1489 exit = true;
1490 result = -1;
1491 break;
1494 files = (struct entry*) tc->dircache;
1495 num_files = tc->filesindir;
1497 for (i=0; i<num_files; i++)
1499 /* user abort */
1500 if (action_userabort(TIMEOUT_NOBLOCK))
1502 result = -1;
1503 exit = true;
1504 break;
1507 if (files[i].attr & ATTR_DIRECTORY)
1509 if (!start_dir)
1511 result = check_subdir_for_music(dir, files[i].name);
1512 if (result != -1)
1514 exit = true;
1515 break;
1518 else if (!strcmp(start_dir, files[i].name))
1519 start_dir = NULL;
1523 if (!exit)
1525 /* move down to parent directory. current directory name is
1526 stored as the starting point for the search in parent */
1527 start_dir = strrchr(dir, '/');
1528 if (start_dir)
1530 *start_dir = '\0';
1531 start_dir++;
1533 else
1534 break;
1538 /* we've overwritten the dircache so tree browser will need to be
1539 reloaded */
1540 reload_directory();
1542 /* restore dirfilter & sort_dir */
1543 *(tc->dirfilter) = dirfilter;
1544 global_settings.sort_dir = sort_dir;
1546 /* special case if nothing found: try start searching again from root */
1547 if (result == -1 && !recursion){
1548 result = get_next_dir(dir,is_forward, true);
1551 return result;
1555 * Checks if there are any music files in the dir or any of its
1556 * subdirectories. May be called recursively.
1558 static int check_subdir_for_music(char *dir, char *subdir)
1560 int result = -1;
1561 int dirlen = strlen(dir);
1562 int num_files = 0;
1563 int i;
1564 struct entry *files;
1565 bool has_music = false;
1566 bool has_subdir = false;
1567 struct tree_context* tc = tree_get_context();
1569 snprintf(dir+dirlen, MAX_PATH-dirlen, "/%s", subdir);
1571 if (ft_load(tc, dir) < 0)
1573 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));
1574 return -2;
1577 files = (struct entry*) tc->dircache;
1578 num_files = tc->filesindir;
1580 for (i=0; i<num_files; i++)
1582 if (files[i].attr & ATTR_DIRECTORY)
1583 has_subdir = true;
1584 else if ((files[i].attr & FILE_ATTR_MASK) == FILE_ATTR_AUDIO)
1586 has_music = true;
1587 break;
1591 if (has_music)
1592 return 0;
1594 if (has_subdir)
1596 for (i=0; i<num_files; i++)
1598 if (action_userabort(TIMEOUT_NOBLOCK))
1600 result = -2;
1601 break;
1604 if (files[i].attr & ATTR_DIRECTORY)
1606 result = check_subdir_for_music(dir, files[i].name);
1607 if (!result)
1608 break;
1613 if (result < 0)
1615 if (dirlen)
1617 dir[dirlen] = '\0';
1619 else
1621 strcpy(dir, "/");
1624 /* we now need to reload our current directory */
1625 if(ft_load(tc, dir) < 0)
1626 gui_syncsplash(HZ*2,
1627 ID2P(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));
1630 return result;
1634 * Returns absolute path of track
1636 static int format_track_path(char *dest, char *src, int buf_length, int max,
1637 char *dir)
1639 int i = 0;
1640 int j;
1641 char *temp_ptr;
1643 /* Zero-terminate the file name */
1644 while((src[i] != '\n') &&
1645 (src[i] != '\r') &&
1646 (i < max))
1647 i++;
1649 /* Now work back killing white space */
1650 while((src[i-1] == ' ') ||
1651 (src[i-1] == '\t'))
1652 i--;
1654 src[i]=0;
1656 /* replace backslashes with forward slashes */
1657 for ( j=0; j<i; j++ )
1658 if ( src[j] == '\\' )
1659 src[j] = '/';
1661 if('/' == src[0])
1663 strncpy(dest, src, buf_length);
1665 else
1667 /* handle dos style drive letter */
1668 if (':' == src[1])
1669 strncpy(dest, &src[2], buf_length);
1670 else if (!strncmp(src, "../", 3))
1672 /* handle relative paths */
1673 i=3;
1674 while(!strncmp(&src[i], "../", 3))
1675 i += 3;
1676 for (j=0; j<i/3; j++) {
1677 temp_ptr = strrchr(dir, '/');
1678 if (temp_ptr)
1679 *temp_ptr = '\0';
1680 else
1681 break;
1683 snprintf(dest, buf_length, "%s/%s", dir, &src[i]);
1685 else if ( '.' == src[0] && '/' == src[1] ) {
1686 snprintf(dest, buf_length, "%s/%s", dir, &src[2]);
1688 else {
1689 snprintf(dest, buf_length, "%s/%s", dir, src);
1693 return 0;
1697 * Display splash message showing progress of playlist/directory insertion or
1698 * save.
1700 static void display_playlist_count(int count, const unsigned char *fmt,
1701 bool final)
1703 static long talked_tick = 0;
1704 long id = P2ID(fmt);
1705 if(global_settings.talk_menu && id>=0)
1707 if(final || (count && (talked_tick == 0
1708 || TIME_AFTER(current_tick, talked_tick+5*HZ))))
1710 talked_tick = current_tick;
1711 talk_number(count, false);
1712 talk_id(id, true);
1715 fmt = P2STR(fmt);
1717 lcd_clear_display();
1719 #ifdef HAVE_LCD_BITMAP
1720 if(global_settings.statusbar)
1721 lcd_setmargins(0, STATUSBAR_HEIGHT);
1722 else
1723 lcd_setmargins(0, 0);
1724 #endif
1726 gui_syncsplash(0, fmt, count, str(LANG_OFF_ABORT));
1730 * Display buffer full message
1732 static void display_buffer_full(void)
1734 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_BUFFER_FULL));
1738 * Flush any cached control commands to disk. Called when playlist is being
1739 * modified. Returns 0 on success and -1 on failure.
1741 static int flush_cached_control(struct playlist_info* playlist)
1743 int result = 0;
1744 int i;
1746 if (!playlist->num_cached)
1747 return 0;
1749 lseek(playlist->control_fd, 0, SEEK_END);
1751 for (i=0; i<playlist->num_cached; i++)
1753 struct playlist_control_cache* cache =
1754 &(playlist->control_cache[i]);
1756 switch (cache->command)
1758 case PLAYLIST_COMMAND_PLAYLIST:
1759 result = fdprintf(playlist->control_fd, "P:%d:%s:%s\n",
1760 cache->i1, cache->s1, cache->s2);
1761 break;
1762 case PLAYLIST_COMMAND_ADD:
1763 case PLAYLIST_COMMAND_QUEUE:
1764 result = fdprintf(playlist->control_fd, "%c:%d:%d:",
1765 (cache->command == PLAYLIST_COMMAND_ADD)?'A':'Q',
1766 cache->i1, cache->i2);
1767 if (result > 0)
1769 /* save the position in file where name is written */
1770 int* seek_pos = (int *)cache->data;
1771 *seek_pos = lseek(playlist->control_fd, 0, SEEK_CUR);
1772 result = fdprintf(playlist->control_fd, "%s\n",
1773 cache->s1);
1775 break;
1776 case PLAYLIST_COMMAND_DELETE:
1777 result = fdprintf(playlist->control_fd, "D:%d\n", cache->i1);
1778 break;
1779 case PLAYLIST_COMMAND_SHUFFLE:
1780 result = fdprintf(playlist->control_fd, "S:%d:%d\n",
1781 cache->i1, cache->i2);
1782 break;
1783 case PLAYLIST_COMMAND_UNSHUFFLE:
1784 result = fdprintf(playlist->control_fd, "U:%d\n", cache->i1);
1785 break;
1786 case PLAYLIST_COMMAND_RESET:
1787 result = fdprintf(playlist->control_fd, "R\n");
1788 break;
1789 default:
1790 break;
1793 if (result <= 0)
1794 break;
1797 if (result > 0)
1799 if (global_status.resume_seed >= 0)
1801 global_status.resume_seed = -1;
1802 status_save();
1805 playlist->num_cached = 0;
1806 playlist->pending_control_sync = true;
1808 result = 0;
1810 else
1812 result = -1;
1813 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_UPDATE_ERROR));
1816 return result;
1820 * Update control data with new command. Depending on the command, it may be
1821 * cached or flushed to disk.
1823 static int update_control(struct playlist_info* playlist,
1824 enum playlist_command command, int i1, int i2,
1825 const char* s1, const char* s2, void* data)
1827 int result = 0;
1828 struct playlist_control_cache* cache;
1829 bool flush = false;
1831 mutex_lock(&playlist->control_mutex);
1833 cache = &(playlist->control_cache[playlist->num_cached++]);
1835 cache->command = command;
1836 cache->i1 = i1;
1837 cache->i2 = i2;
1838 cache->s1 = s1;
1839 cache->s2 = s2;
1840 cache->data = data;
1842 switch (command)
1844 case PLAYLIST_COMMAND_PLAYLIST:
1845 case PLAYLIST_COMMAND_ADD:
1846 case PLAYLIST_COMMAND_QUEUE:
1847 #ifndef HAVE_DIRCACHE
1848 case PLAYLIST_COMMAND_DELETE:
1849 case PLAYLIST_COMMAND_RESET:
1850 #endif
1851 flush = true;
1852 break;
1853 case PLAYLIST_COMMAND_SHUFFLE:
1854 case PLAYLIST_COMMAND_UNSHUFFLE:
1855 default:
1856 /* only flush when needed */
1857 break;
1860 if (flush || playlist->num_cached == PLAYLIST_MAX_CACHE)
1861 result = flush_cached_control(playlist);
1863 mutex_unlock(&playlist->control_mutex);
1865 return result;
1869 * sync control file to disk
1871 static void sync_control(struct playlist_info* playlist, bool force)
1873 #ifdef HAVE_DIRCACHE
1874 if (playlist->started && force)
1875 #else
1876 (void) force;
1878 if (playlist->started)
1879 #endif
1881 if (playlist->pending_control_sync)
1883 mutex_lock(&playlist->control_mutex);
1884 fsync(playlist->control_fd);
1885 playlist->pending_control_sync = false;
1886 mutex_unlock(&playlist->control_mutex);
1892 * Rotate indices such that first_index is index 0
1894 static int rotate_index(const struct playlist_info* playlist, int index)
1896 index -= playlist->first_index;
1897 if (index < 0)
1898 index += playlist->amount;
1900 return index;
1904 * Initialize playlist entries at startup
1906 void playlist_init(void)
1908 struct playlist_info* playlist = &current_playlist;
1910 playlist->current = true;
1911 snprintf(playlist->control_filename, sizeof(playlist->control_filename),
1912 "%s", PLAYLIST_CONTROL_FILE);
1913 playlist->fd = -1;
1914 playlist->control_fd = -1;
1915 playlist->max_playlist_size = global_settings.max_files_in_playlist;
1916 playlist->indices = buffer_alloc(
1917 playlist->max_playlist_size * sizeof(int));
1918 playlist->buffer_size =
1919 AVERAGE_FILENAME_LENGTH * global_settings.max_files_in_dir;
1920 playlist->buffer = buffer_alloc(playlist->buffer_size);
1921 mutex_init(&playlist->control_mutex);
1922 empty_playlist(playlist, true);
1924 #ifdef HAVE_DIRCACHE
1925 playlist->filenames = buffer_alloc(
1926 playlist->max_playlist_size * sizeof(int));
1927 memset(playlist->filenames, 0,
1928 playlist->max_playlist_size * sizeof(int));
1929 create_thread(playlist_thread, playlist_stack, sizeof(playlist_stack),
1930 0, playlist_thread_name IF_PRIO(, PRIORITY_BACKGROUND)
1931 IF_COP(, CPU));
1932 queue_init(&playlist_queue, true);
1933 #endif
1937 * Clean playlist at shutdown
1939 void playlist_shutdown(void)
1941 struct playlist_info* playlist = &current_playlist;
1943 if (playlist->control_fd >= 0)
1945 mutex_lock(&playlist->control_mutex);
1947 if (playlist->num_cached > 0)
1948 flush_cached_control(playlist);
1950 close(playlist->control_fd);
1952 mutex_unlock(&playlist->control_mutex);
1957 * Create new playlist
1959 int playlist_create(const char *dir, const char *file)
1961 struct playlist_info* playlist = &current_playlist;
1963 new_playlist(playlist, dir, file);
1965 if (file)
1966 /* load the playlist file */
1967 add_indices_to_playlist(playlist, NULL, 0);
1969 return 0;
1972 #define PLAYLIST_COMMAND_SIZE (MAX_PATH+12)
1975 * Restore the playlist state based on control file commands. Called to
1976 * resume playback after shutdown.
1978 int playlist_resume(void)
1980 struct playlist_info* playlist = &current_playlist;
1981 char *buffer;
1982 size_t buflen;
1983 int nread;
1984 int total_read = 0;
1985 int control_file_size = 0;
1986 bool first = true;
1987 bool sorted = true;
1989 /* use mp3 buffer for maximum load speed */
1990 #if CONFIG_CODEC != SWCODEC
1991 talk_buffer_steal(); /* we use the mp3 buffer, need to tell */
1992 buflen = (audiobufend - audiobuf);
1993 buffer = (char *)audiobuf;
1994 #else
1995 buffer = (char *)audio_get_buffer(false, &buflen);
1996 #endif
1998 empty_playlist(playlist, true);
2000 gui_syncsplash(0, ID2P(LANG_WAIT));
2001 playlist->control_fd = open(playlist->control_filename, O_RDWR);
2002 if (playlist->control_fd < 0)
2004 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2005 return -1;
2007 playlist->control_created = true;
2009 control_file_size = filesize(playlist->control_fd);
2010 if (control_file_size <= 0)
2012 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2013 return -1;
2016 /* read a small amount first to get the header */
2017 nread = read(playlist->control_fd, buffer,
2018 PLAYLIST_COMMAND_SIZE<buflen?PLAYLIST_COMMAND_SIZE:buflen);
2019 if(nread <= 0)
2021 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2022 return -1;
2025 playlist->started = true;
2027 while (1)
2029 int result = 0;
2030 int count;
2031 enum playlist_command current_command = PLAYLIST_COMMAND_COMMENT;
2032 int last_newline = 0;
2033 int str_count = -1;
2034 bool newline = true;
2035 bool exit_loop = false;
2036 char *p = buffer;
2037 char *str1 = NULL;
2038 char *str2 = NULL;
2039 char *str3 = NULL;
2040 unsigned long last_tick = current_tick;
2042 for(count=0; count<nread && !exit_loop; count++,p++)
2044 /* So a splash while we are loading. */
2045 if (current_tick - last_tick > HZ/4)
2047 gui_syncsplash(0, str(LANG_LOADING_PERCENT),
2048 (total_read+count)*100/control_file_size,
2049 str(LANG_OFF_ABORT));
2050 if (action_userabort(TIMEOUT_NOBLOCK))
2052 /* FIXME:
2053 * Not sure how to implement this, somebody more familiar
2054 * with the code, please fix this. */
2056 last_tick = current_tick;
2059 /* Are we on a new line? */
2060 if((*p == '\n') || (*p == '\r'))
2062 *p = '\0';
2064 /* save last_newline in case we need to load more data */
2065 last_newline = count;
2067 switch (current_command)
2069 case PLAYLIST_COMMAND_PLAYLIST:
2071 /* str1=version str2=dir str3=file */
2072 int version;
2074 if (!str1)
2076 result = -1;
2077 exit_loop = true;
2078 break;
2081 if (!str2)
2082 str2 = "";
2084 if (!str3)
2085 str3 = "";
2087 version = atoi(str1);
2089 if (version != PLAYLIST_CONTROL_FILE_VERSION)
2090 return -1;
2092 update_playlist_filename(playlist, str2, str3);
2094 if (str3[0] != '\0')
2096 /* NOTE: add_indices_to_playlist() overwrites the
2097 audiobuf so we need to reload control file
2098 data */
2099 add_indices_to_playlist(playlist, NULL, 0);
2101 else if (str2[0] != '\0')
2103 playlist->in_ram = true;
2104 resume_directory(str2);
2107 /* load the rest of the data */
2108 first = false;
2109 exit_loop = true;
2111 break;
2113 case PLAYLIST_COMMAND_ADD:
2114 case PLAYLIST_COMMAND_QUEUE:
2116 /* str1=position str2=last_position str3=file */
2117 int position, last_position;
2118 bool queue;
2120 if (!str1 || !str2 || !str3)
2122 result = -1;
2123 exit_loop = true;
2124 break;
2127 position = atoi(str1);
2128 last_position = atoi(str2);
2130 queue = (current_command == PLAYLIST_COMMAND_ADD)?
2131 false:true;
2133 /* seek position is based on str3's position in
2134 buffer */
2135 if (add_track_to_playlist(playlist, str3, position,
2136 queue, total_read+(str3-buffer)) < 0)
2137 return -1;
2139 playlist->last_insert_pos = last_position;
2141 break;
2143 case PLAYLIST_COMMAND_DELETE:
2145 /* str1=position */
2146 int position;
2148 if (!str1)
2150 result = -1;
2151 exit_loop = true;
2152 break;
2155 position = atoi(str1);
2157 if (remove_track_from_playlist(playlist, position,
2158 false) < 0)
2159 return -1;
2161 break;
2163 case PLAYLIST_COMMAND_SHUFFLE:
2165 /* str1=seed str2=first_index */
2166 int seed;
2168 if (!str1 || !str2)
2170 result = -1;
2171 exit_loop = true;
2172 break;
2175 if (!sorted)
2177 /* Always sort list before shuffling */
2178 sort_playlist(playlist, false, false);
2181 seed = atoi(str1);
2182 playlist->first_index = atoi(str2);
2184 if (randomise_playlist(playlist, seed, false,
2185 false) < 0)
2186 return -1;
2188 sorted = false;
2189 break;
2191 case PLAYLIST_COMMAND_UNSHUFFLE:
2193 /* str1=first_index */
2194 if (!str1)
2196 result = -1;
2197 exit_loop = true;
2198 break;
2201 playlist->first_index = atoi(str1);
2203 if (sort_playlist(playlist, false, false) < 0)
2204 return -1;
2206 sorted = true;
2207 break;
2209 case PLAYLIST_COMMAND_RESET:
2211 playlist->last_insert_pos = -1;
2212 break;
2214 case PLAYLIST_COMMAND_COMMENT:
2215 default:
2216 break;
2219 newline = true;
2221 /* to ignore any extra newlines */
2222 current_command = PLAYLIST_COMMAND_COMMENT;
2224 else if(newline)
2226 newline = false;
2228 /* first non-comment line must always specify playlist */
2229 if (first && *p != 'P' && *p != '#')
2231 result = -1;
2232 exit_loop = true;
2233 break;
2236 switch (*p)
2238 case 'P':
2239 /* playlist can only be specified once */
2240 if (!first)
2242 result = -1;
2243 exit_loop = true;
2244 break;
2247 current_command = PLAYLIST_COMMAND_PLAYLIST;
2248 break;
2249 case 'A':
2250 current_command = PLAYLIST_COMMAND_ADD;
2251 break;
2252 case 'Q':
2253 current_command = PLAYLIST_COMMAND_QUEUE;
2254 break;
2255 case 'D':
2256 current_command = PLAYLIST_COMMAND_DELETE;
2257 break;
2258 case 'S':
2259 current_command = PLAYLIST_COMMAND_SHUFFLE;
2260 break;
2261 case 'U':
2262 current_command = PLAYLIST_COMMAND_UNSHUFFLE;
2263 break;
2264 case 'R':
2265 current_command = PLAYLIST_COMMAND_RESET;
2266 break;
2267 case '#':
2268 current_command = PLAYLIST_COMMAND_COMMENT;
2269 break;
2270 default:
2271 result = -1;
2272 exit_loop = true;
2273 break;
2276 str_count = -1;
2277 str1 = NULL;
2278 str2 = NULL;
2279 str3 = NULL;
2281 else if(current_command != PLAYLIST_COMMAND_COMMENT)
2283 /* all control file strings are separated with a colon.
2284 Replace the colon with 0 to get proper strings that can be
2285 used by commands above */
2286 if (*p == ':')
2288 *p = '\0';
2289 str_count++;
2291 if ((count+1) < nread)
2293 switch (str_count)
2295 case 0:
2296 str1 = p+1;
2297 break;
2298 case 1:
2299 str2 = p+1;
2300 break;
2301 case 2:
2302 str3 = p+1;
2303 break;
2304 default:
2305 /* allow last string to contain colons */
2306 *p = ':';
2307 break;
2314 if (result < 0)
2316 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_INVALID));
2317 return result;
2320 if (!newline || (exit_loop && count<nread))
2322 if ((total_read + count) >= control_file_size)
2324 /* no newline at end of control file */
2325 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_INVALID));
2326 return -1;
2329 /* We didn't end on a newline or we exited loop prematurely.
2330 Either way, re-read the remainder. */
2331 count = last_newline;
2332 lseek(playlist->control_fd, total_read+count, SEEK_SET);
2335 total_read += count;
2337 if (first)
2338 /* still looking for header */
2339 nread = read(playlist->control_fd, buffer,
2340 PLAYLIST_COMMAND_SIZE<buflen?PLAYLIST_COMMAND_SIZE:buflen);
2341 else
2342 nread = read(playlist->control_fd, buffer, buflen);
2344 /* Terminate on EOF */
2345 if(nread <= 0)
2347 if (global_status.resume_seed >= 0)
2349 /* Apply shuffle command saved in settings */
2350 if (global_status.resume_seed == 0)
2351 sort_playlist(playlist, false, true);
2352 else
2354 if (!sorted)
2355 sort_playlist(playlist, false, false);
2357 randomise_playlist(playlist, global_status.resume_seed,
2358 false, true);
2362 playlist->first_index = global_status.resume_first_index;
2363 break;
2367 #ifdef HAVE_DIRCACHE
2368 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
2369 #endif
2371 return 0;
2375 * Add track to in_ram playlist. Used when playing directories.
2377 int playlist_add(const char *filename)
2379 struct playlist_info* playlist = &current_playlist;
2380 int len = strlen(filename);
2382 if((len+1 > playlist->buffer_size - playlist->buffer_end_pos) ||
2383 (playlist->amount >= playlist->max_playlist_size))
2385 display_buffer_full();
2386 return -1;
2389 playlist->indices[playlist->amount] = playlist->buffer_end_pos;
2390 #ifdef HAVE_DIRCACHE
2391 playlist->filenames[playlist->amount] = NULL;
2392 #endif
2393 playlist->amount++;
2395 strcpy(&playlist->buffer[playlist->buffer_end_pos], filename);
2396 playlist->buffer_end_pos += len;
2397 playlist->buffer[playlist->buffer_end_pos++] = '\0';
2399 return 0;
2402 /* shuffle newly created playlist using random seed. */
2403 int playlist_shuffle(int random_seed, int start_index)
2405 struct playlist_info* playlist = &current_playlist;
2407 unsigned int seek_pos = 0;
2408 bool start_current = false;
2410 if (start_index >= 0 && global_settings.play_selected)
2412 /* store the seek position before the shuffle */
2413 seek_pos = playlist->indices[start_index];
2414 playlist->index = global_status.resume_first_index =
2415 playlist->first_index = start_index;
2416 start_current = true;
2419 randomise_playlist(playlist, random_seed, start_current, true);
2421 return playlist->index;
2424 /* start playing current playlist at specified index/offset */
2425 int playlist_start(int start_index, int offset)
2427 struct playlist_info* playlist = &current_playlist;
2429 /* Cancel FM radio selection as previous music. For cases where we start
2430 playback without going to the WPS, such as playlist insert.. or
2431 playlist catalog. */
2432 previous_music_is_wps();
2434 playlist->index = start_index;
2436 #if CONFIG_CODEC != SWCODEC
2437 talk_buffer_steal(); /* will use the mp3 buffer */
2438 #endif
2440 playlist->started = true;
2441 sync_control(playlist, false);
2442 audio_play(offset);
2444 return 0;
2447 /* Returns false if 'steps' is out of bounds, else true */
2448 bool playlist_check(int steps)
2450 struct playlist_info* playlist = &current_playlist;
2452 /* always allow folder navigation */
2453 if (global_settings.next_folder && playlist->in_ram)
2454 return true;
2456 int index = get_next_index(playlist, steps, -1);
2458 if (index < 0 && steps >= 0 && global_settings.repeat_mode == REPEAT_SHUFFLE)
2459 index = get_next_index(playlist, steps, REPEAT_ALL);
2461 return (index >= 0);
2464 /* get trackname of track that is "steps" away from current playing track.
2465 NULL is used to identify end of playlist */
2466 char* playlist_peek(int steps)
2468 struct playlist_info* playlist = &current_playlist;
2469 int seek;
2470 int fd;
2471 char *temp_ptr;
2472 int index;
2473 bool control_file;
2475 index = get_next_index(playlist, steps, -1);
2476 if (index < 0)
2477 return NULL;
2479 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
2480 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
2482 if (get_filename(playlist, index, seek, control_file, now_playing,
2483 MAX_PATH+1) < 0)
2484 return NULL;
2486 temp_ptr = now_playing;
2488 if (!playlist->in_ram || control_file)
2490 /* remove bogus dirs from beginning of path
2491 (workaround for buggy playlist creation tools) */
2492 while (temp_ptr)
2494 #ifdef HAVE_DIRCACHE
2495 if (dircache_is_enabled())
2497 if (dircache_get_entry_ptr(temp_ptr))
2498 break;
2500 else
2501 #endif
2503 fd = open(temp_ptr, O_RDONLY);
2504 if (fd >= 0)
2506 close(fd);
2507 break;
2511 temp_ptr = strchr(temp_ptr+1, '/');
2514 if (!temp_ptr)
2516 /* Even though this is an invalid file, we still need to pass a
2517 file name to the caller because NULL is used to indicate end
2518 of playlist */
2519 return now_playing;
2523 return temp_ptr;
2527 * Update indices as track has changed
2529 int playlist_next(int steps)
2531 struct playlist_info* playlist = &current_playlist;
2532 int index;
2534 if ( (steps > 0)
2535 #ifdef AB_REPEAT_ENABLE
2536 && (global_settings.repeat_mode != REPEAT_AB)
2537 #endif
2538 && (global_settings.repeat_mode != REPEAT_ONE) )
2540 int i, j;
2542 /* We need to delete all the queued songs */
2543 for (i=0, j=steps; i<j; i++)
2545 index = get_next_index(playlist, i, -1);
2547 if (playlist->indices[index] & PLAYLIST_QUEUE_MASK)
2549 remove_track_from_playlist(playlist, index, true);
2550 steps--; /* one less track */
2555 index = get_next_index(playlist, steps, -1);
2557 if (index < 0)
2559 /* end of playlist... or is it */
2560 if (global_settings.repeat_mode == REPEAT_SHUFFLE &&
2561 playlist->amount > 1)
2563 /* Repeat shuffle mode. Re-shuffle playlist and resume play */
2564 playlist->first_index = global_status.resume_first_index = 0;
2565 sort_playlist(playlist, false, false);
2566 randomise_playlist(playlist, current_tick, false, true);
2567 #if CONFIG_CODEC != SWCODEC
2568 playlist_start(0, 0);
2569 #endif
2570 playlist->index = 0;
2571 index = 0;
2573 else if (playlist->in_ram && global_settings.next_folder)
2575 index = create_and_play_dir(steps, true);
2577 if (index >= 0)
2579 playlist->index = index;
2583 return index;
2586 playlist->index = index;
2588 if (playlist->last_insert_pos >= 0 && steps > 0)
2590 /* check to see if we've gone beyond the last inserted track */
2591 int cur = rotate_index(playlist, index);
2592 int last_pos = rotate_index(playlist, playlist->last_insert_pos);
2594 if (cur > last_pos)
2596 /* reset last inserted track */
2597 playlist->last_insert_pos = -1;
2599 if (playlist->control_fd >= 0)
2601 int result = update_control(playlist, PLAYLIST_COMMAND_RESET,
2602 -1, -1, NULL, NULL, NULL);
2604 if (result < 0)
2605 return result;
2607 sync_control(playlist, false);
2612 return index;
2615 /* try playing next or previous folder */
2616 bool playlist_next_dir(int direction)
2618 /* not to mess up real playlists */
2619 if(!current_playlist.in_ram)
2620 return false;
2622 return create_and_play_dir(direction, false) >= 0;
2625 /* Get resume info for current playing song. If return value is -1 then
2626 settings shouldn't be saved. */
2627 int playlist_get_resume_info(int *resume_index)
2629 struct playlist_info* playlist = &current_playlist;
2631 *resume_index = playlist->index;
2633 return 0;
2636 /* Update resume info for current playing song. Returns -1 on error. */
2637 int playlist_update_resume_info(const struct mp3entry* id3)
2639 struct playlist_info* playlist = &current_playlist;
2641 if (id3)
2643 if (global_status.resume_index != playlist->index ||
2644 global_status.resume_offset != id3->offset)
2646 global_status.resume_index = playlist->index;
2647 global_status.resume_offset = id3->offset;
2648 status_save();
2651 else
2653 global_status.resume_index = -1;
2654 global_status.resume_offset = -1;
2655 status_save();
2658 return 0;
2661 /* Returns index of current playing track for display purposes. This value
2662 should not be used for resume purposes as it doesn't represent the actual
2663 index into the playlist */
2664 int playlist_get_display_index(void)
2666 struct playlist_info* playlist = &current_playlist;
2668 /* first_index should always be index 0 for display purposes */
2669 int index = rotate_index(playlist, playlist->index);
2671 return (index+1);
2674 /* returns number of tracks in current playlist */
2675 int playlist_amount(void)
2677 return playlist_amount_ex(NULL);
2681 * Create a new playlist If playlist is not NULL then we're loading a
2682 * playlist off disk for viewing/editing. The index_buffer is used to store
2683 * playlist indices (required for and only used if !current playlist). The
2684 * temp_buffer (if not NULL) is used as a scratchpad when loading indices.
2686 int playlist_create_ex(struct playlist_info* playlist,
2687 const char* dir, const char* file,
2688 void* index_buffer, int index_buffer_size,
2689 void* temp_buffer, int temp_buffer_size)
2691 if (!playlist)
2692 playlist = &current_playlist;
2693 else
2695 /* Initialize playlist structure */
2696 int r = rand() % 10;
2697 playlist->current = false;
2699 /* Use random name for control file */
2700 snprintf(playlist->control_filename, sizeof(playlist->control_filename),
2701 "%s.%d", PLAYLIST_CONTROL_FILE, r);
2702 playlist->fd = -1;
2703 playlist->control_fd = -1;
2705 if (index_buffer)
2707 int num_indices = index_buffer_size / sizeof(int);
2709 #ifdef HAVE_DIRCACHE
2710 num_indices /= 2;
2711 #endif
2712 if (num_indices > global_settings.max_files_in_playlist)
2713 num_indices = global_settings.max_files_in_playlist;
2715 playlist->max_playlist_size = num_indices;
2716 playlist->indices = index_buffer;
2717 #ifdef HAVE_DIRCACHE
2718 playlist->filenames = (const struct dircache_entry **)
2719 &playlist->indices[num_indices];
2720 #endif
2722 else
2724 playlist->max_playlist_size = current_playlist.max_playlist_size;
2725 playlist->indices = current_playlist.indices;
2726 #ifdef HAVE_DIRCACHE
2727 playlist->filenames = current_playlist.filenames;
2728 #endif
2731 playlist->buffer_size = 0;
2732 playlist->buffer = NULL;
2733 mutex_init(&playlist->control_mutex);
2736 new_playlist(playlist, dir, file);
2738 if (file)
2739 /* load the playlist file */
2740 add_indices_to_playlist(playlist, temp_buffer, temp_buffer_size);
2742 return 0;
2746 * Set the specified playlist as the current.
2747 * NOTE: You will get undefined behaviour if something is already playing so
2748 * remember to stop before calling this. Also, this call will
2749 * effectively close your playlist, making it unusable.
2751 int playlist_set_current(struct playlist_info* playlist)
2753 if (!playlist || (check_control(playlist) < 0))
2754 return -1;
2756 empty_playlist(&current_playlist, false);
2758 strncpy(current_playlist.filename, playlist->filename,
2759 sizeof(current_playlist.filename));
2761 current_playlist.utf8 = playlist->utf8;
2762 current_playlist.fd = playlist->fd;
2764 close(playlist->control_fd);
2765 close(current_playlist.control_fd);
2766 remove(current_playlist.control_filename);
2767 if (rename(playlist->control_filename,
2768 current_playlist.control_filename) < 0)
2769 return -1;
2770 current_playlist.control_fd = open(current_playlist.control_filename,
2771 O_RDWR);
2772 if (current_playlist.control_fd < 0)
2773 return -1;
2774 current_playlist.control_created = true;
2776 current_playlist.dirlen = playlist->dirlen;
2778 if (playlist->indices && playlist->indices != current_playlist.indices)
2780 memcpy(current_playlist.indices, playlist->indices,
2781 playlist->max_playlist_size*sizeof(int));
2782 #ifdef HAVE_DIRCACHE
2783 memcpy(current_playlist.filenames, playlist->filenames,
2784 playlist->max_playlist_size*sizeof(int));
2785 #endif
2788 current_playlist.first_index = playlist->first_index;
2789 current_playlist.amount = playlist->amount;
2790 current_playlist.last_insert_pos = playlist->last_insert_pos;
2791 current_playlist.seed = playlist->seed;
2792 current_playlist.shuffle_modified = playlist->shuffle_modified;
2793 current_playlist.deleted = playlist->deleted;
2794 current_playlist.num_inserted_tracks = playlist->num_inserted_tracks;
2796 memcpy(current_playlist.control_cache, playlist->control_cache,
2797 sizeof(current_playlist.control_cache));
2798 current_playlist.num_cached = playlist->num_cached;
2799 current_playlist.pending_control_sync = playlist->pending_control_sync;
2801 return 0;
2805 * Close files and delete control file for non-current playlist.
2807 void playlist_close(struct playlist_info* playlist)
2809 if (!playlist)
2810 return;
2812 if (playlist->fd >= 0)
2813 close(playlist->fd);
2815 if (playlist->control_fd >= 0)
2816 close(playlist->control_fd);
2818 if (playlist->control_created)
2819 remove(playlist->control_filename);
2822 void playlist_sync(struct playlist_info* playlist)
2824 if (!playlist)
2825 playlist = &current_playlist;
2827 sync_control(playlist, false);
2828 if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
2829 audio_flush_and_reload_tracks();
2831 #ifdef HAVE_DIRCACHE
2832 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
2833 #endif
2837 * Insert track into playlist at specified position (or one of the special
2838 * positions). Returns position where track was inserted or -1 if error.
2840 int playlist_insert_track(struct playlist_info* playlist, const char *filename,
2841 int position, bool queue, bool sync)
2843 int result;
2845 if (!playlist)
2846 playlist = &current_playlist;
2848 if (check_control(playlist) < 0)
2850 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2851 return -1;
2854 result = add_track_to_playlist(playlist, filename, position, queue, -1);
2856 /* Check if we want manually sync later. For example when adding
2857 * bunch of files from tagcache, syncing after every file wouldn't be
2858 * a good thing to do. */
2859 if (sync && result >= 0)
2860 playlist_sync(playlist);
2862 return result;
2866 * Insert all tracks from specified directory into playlist.
2868 int playlist_insert_directory(struct playlist_info* playlist,
2869 const char *dirname, int position, bool queue,
2870 bool recurse)
2872 int result;
2873 unsigned char *count_str;
2874 struct directory_search_context context;
2876 if (!playlist)
2877 playlist = &current_playlist;
2879 if (check_control(playlist) < 0)
2881 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2882 return -1;
2885 if (position == PLAYLIST_REPLACE)
2887 if (remove_all_tracks(playlist) == 0)
2888 position = PLAYLIST_INSERT_LAST;
2889 else
2890 return -1;
2893 if (queue)
2894 count_str = ID2P(LANG_PLAYLIST_QUEUE_COUNT);
2895 else
2896 count_str = ID2P(LANG_PLAYLIST_INSERT_COUNT);
2898 display_playlist_count(0, count_str, false);
2900 context.playlist = playlist;
2901 context.position = position;
2902 context.queue = queue;
2903 context.count = 0;
2905 cpu_boost(true);
2907 result = playlist_directory_tracksearch(dirname, recurse,
2908 directory_search_callback, &context);
2910 sync_control(playlist, false);
2912 cpu_boost(false);
2914 display_playlist_count(context.count, count_str, true);
2916 if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
2917 audio_flush_and_reload_tracks();
2919 #ifdef HAVE_DIRCACHE
2920 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
2921 #endif
2923 return result;
2927 * Insert all tracks from specified playlist into dynamic playlist.
2929 int playlist_insert_playlist(struct playlist_info* playlist, char *filename,
2930 int position, bool queue)
2932 int fd;
2933 int max;
2934 char *temp_ptr;
2935 char *dir;
2936 unsigned char *count_str;
2937 char temp_buf[MAX_PATH+1];
2938 char trackname[MAX_PATH+1];
2939 int count = 0;
2940 int result = 0;
2942 if (!playlist)
2943 playlist = &current_playlist;
2945 if (check_control(playlist) < 0)
2947 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2948 return -1;
2951 fd = open(filename, O_RDONLY);
2952 if (fd < 0)
2954 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
2955 return -1;
2958 /* we need the directory name for formatting purposes */
2959 dir = filename;
2961 temp_ptr = strrchr(filename+1,'/');
2962 if (temp_ptr)
2963 *temp_ptr = 0;
2964 else
2965 dir = "/";
2967 if (queue)
2968 count_str = ID2P(LANG_PLAYLIST_QUEUE_COUNT);
2969 else
2970 count_str = ID2P(LANG_PLAYLIST_INSERT_COUNT);
2972 display_playlist_count(count, count_str, false);
2974 if (position == PLAYLIST_REPLACE)
2976 if (remove_all_tracks(playlist) == 0)
2977 position = PLAYLIST_INSERT_LAST;
2978 else return -1;
2981 cpu_boost(true);
2983 while ((max = read_line(fd, temp_buf, sizeof(temp_buf))) > 0)
2985 /* user abort */
2986 if (action_userabort(TIMEOUT_NOBLOCK))
2987 break;
2989 if (temp_buf[0] != '#' && temp_buf[0] != '\0')
2991 int insert_pos;
2993 /* we need to format so that relative paths are correctly
2994 handled */
2995 if (format_track_path(trackname, temp_buf, sizeof(trackname), max,
2996 dir) < 0)
2998 result = -1;
2999 break;
3002 insert_pos = add_track_to_playlist(playlist, trackname, position,
3003 queue, -1);
3005 if (insert_pos < 0)
3007 result = -1;
3008 break;
3011 /* Make sure tracks are inserted in correct order if user
3012 requests INSERT_FIRST */
3013 if (position == PLAYLIST_INSERT_FIRST || position >= 0)
3014 position = insert_pos + 1;
3016 count++;
3018 if ((count%PLAYLIST_DISPLAY_COUNT) == 0)
3020 display_playlist_count(count, count_str, false);
3022 if (count == PLAYLIST_DISPLAY_COUNT &&
3023 (audio_status() & AUDIO_STATUS_PLAY) &&
3024 playlist->started)
3025 audio_flush_and_reload_tracks();
3029 /* let the other threads work */
3030 yield();
3033 close(fd);
3035 if (temp_ptr)
3036 *temp_ptr = '/';
3038 sync_control(playlist, false);
3040 cpu_boost(false);
3042 display_playlist_count(count, count_str, true);
3044 if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
3045 audio_flush_and_reload_tracks();
3047 #ifdef HAVE_DIRCACHE
3048 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
3049 #endif
3051 return result;
3055 * Delete track at specified index. If index is PLAYLIST_DELETE_CURRENT then
3056 * we want to delete the current playing track.
3058 int playlist_delete(struct playlist_info* playlist, int index)
3060 int result = 0;
3062 if (!playlist)
3063 playlist = &current_playlist;
3065 if (check_control(playlist) < 0)
3067 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
3068 return -1;
3071 if (index == PLAYLIST_DELETE_CURRENT)
3072 index = playlist->index;
3074 result = remove_track_from_playlist(playlist, index, true);
3076 if (result != -1 && (audio_status() & AUDIO_STATUS_PLAY) &&
3077 playlist->started)
3078 audio_flush_and_reload_tracks();
3080 return result;
3084 * Move track at index to new_index. Tracks between the two are shifted
3085 * appropriately. Returns 0 on success and -1 on failure.
3087 int playlist_move(struct playlist_info* playlist, int index, int new_index)
3089 int result;
3090 int seek;
3091 bool control_file;
3092 bool queue;
3093 bool current = false;
3094 int r;
3095 char filename[MAX_PATH];
3097 if (!playlist)
3098 playlist = &current_playlist;
3100 if (check_control(playlist) < 0)
3102 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
3103 return -1;
3106 if (index == new_index)
3107 return -1;
3109 if (index == playlist->index)
3110 /* Moving the current track */
3111 current = true;
3113 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
3114 queue = playlist->indices[index] & PLAYLIST_QUEUE_MASK;
3115 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
3117 if (get_filename(playlist, index, seek, control_file, filename,
3118 sizeof(filename)) < 0)
3119 return -1;
3121 /* Delete track from original position */
3122 result = remove_track_from_playlist(playlist, index, true);
3124 if (result != -1)
3126 /* We want to insert the track at the position that was specified by
3127 new_index. This may be different then new_index because of the
3128 shifting that occurred after the delete */
3129 r = rotate_index(playlist, new_index);
3131 if (r == 0)
3132 /* First index */
3133 new_index = PLAYLIST_PREPEND;
3134 else if (r == playlist->amount)
3135 /* Append */
3136 new_index = PLAYLIST_INSERT_LAST;
3137 else
3138 /* Calculate index of desired position */
3139 new_index = (r+playlist->first_index)%playlist->amount;
3141 result = add_track_to_playlist(playlist, filename, new_index, queue,
3142 -1);
3144 if (result != -1)
3146 if (current)
3148 /* Moved the current track */
3149 switch (new_index)
3151 case PLAYLIST_PREPEND:
3152 playlist->index = playlist->first_index;
3153 break;
3154 case PLAYLIST_INSERT_LAST:
3155 playlist->index = playlist->first_index - 1;
3156 if (playlist->index < 0)
3157 playlist->index += playlist->amount;
3158 break;
3159 default:
3160 playlist->index = new_index;
3161 break;
3165 if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
3166 audio_flush_and_reload_tracks();
3170 #ifdef HAVE_DIRCACHE
3171 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
3172 #endif
3174 return result;
3177 /* shuffle currently playing playlist */
3178 int playlist_randomise(struct playlist_info* playlist, unsigned int seed,
3179 bool start_current)
3181 int result;
3183 if (!playlist)
3184 playlist = &current_playlist;
3186 check_control(playlist);
3188 result = randomise_playlist(playlist, seed, start_current, true);
3190 if (result != -1 && (audio_status() & AUDIO_STATUS_PLAY) &&
3191 playlist->started)
3192 audio_flush_and_reload_tracks();
3194 return result;
3197 /* sort currently playing playlist */
3198 int playlist_sort(struct playlist_info* playlist, bool start_current)
3200 int result;
3202 if (!playlist)
3203 playlist = &current_playlist;
3205 check_control(playlist);
3207 result = sort_playlist(playlist, start_current, true);
3209 if (result != -1 && (audio_status() & AUDIO_STATUS_PLAY) &&
3210 playlist->started)
3211 audio_flush_and_reload_tracks();
3213 return result;
3216 /* returns true if playlist has been modified */
3217 bool playlist_modified(const struct playlist_info* playlist)
3219 if (!playlist)
3220 playlist = &current_playlist;
3222 if (playlist->shuffle_modified ||
3223 playlist->deleted ||
3224 playlist->num_inserted_tracks > 0)
3225 return true;
3227 return false;
3230 /* returns index of first track in playlist */
3231 int playlist_get_first_index(const struct playlist_info* playlist)
3233 if (!playlist)
3234 playlist = &current_playlist;
3236 return playlist->first_index;
3239 /* returns shuffle seed of playlist */
3240 int playlist_get_seed(const struct playlist_info* playlist)
3242 if (!playlist)
3243 playlist = &current_playlist;
3245 return playlist->seed;
3248 /* returns number of tracks in playlist (includes queued/inserted tracks) */
3249 int playlist_amount_ex(const struct playlist_info* playlist)
3251 if (!playlist)
3252 playlist = &current_playlist;
3254 return playlist->amount;
3257 /* returns full path of playlist (minus extension) */
3258 char *playlist_name(const struct playlist_info* playlist, char *buf,
3259 int buf_size)
3261 char *sep;
3263 if (!playlist)
3264 playlist = &current_playlist;
3266 snprintf(buf, buf_size, "%s", playlist->filename+playlist->dirlen);
3268 if (!buf[0])
3269 return NULL;
3271 /* Remove extension */
3272 sep = strrchr(buf, '.');
3273 if (sep)
3274 *sep = 0;
3276 return buf;
3279 /* returns the playlist filename */
3280 char *playlist_get_name(const struct playlist_info* playlist, char *buf,
3281 int buf_size)
3283 if (!playlist)
3284 playlist = &current_playlist;
3286 snprintf(buf, buf_size, "%s", playlist->filename);
3288 if (!buf[0])
3289 return NULL;
3291 return buf;
3294 /* Fills info structure with information about track at specified index.
3295 Returns 0 on success and -1 on failure */
3296 int playlist_get_track_info(struct playlist_info* playlist, int index,
3297 struct playlist_track_info* info)
3299 int seek;
3300 bool control_file;
3302 if (!playlist)
3303 playlist = &current_playlist;
3305 if (index < 0 || index >= playlist->amount)
3306 return -1;
3308 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
3309 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
3311 if (get_filename(playlist, index, seek, control_file, info->filename,
3312 sizeof(info->filename)) < 0)
3313 return -1;
3315 info->attr = 0;
3317 if (control_file)
3319 if (playlist->indices[index] & PLAYLIST_QUEUE_MASK)
3320 info->attr |= PLAYLIST_ATTR_QUEUED;
3321 else
3322 info->attr |= PLAYLIST_ATTR_INSERTED;
3326 if (playlist->indices[index] & PLAYLIST_SKIPPED)
3327 info->attr |= PLAYLIST_ATTR_SKIPPED;
3329 info->index = index;
3330 info->display_index = rotate_index(playlist, index) + 1;
3332 return 0;
3335 /* save the current dynamic playlist to specified file */
3336 int playlist_save(struct playlist_info* playlist, char *filename)
3338 int fd;
3339 int i, index;
3340 int count = 0;
3341 char path[MAX_PATH+1];
3342 char tmp_buf[MAX_PATH+1];
3343 int result = 0;
3344 bool overwrite_current = false;
3345 int* index_buf = NULL;
3347 if (!playlist)
3348 playlist = &current_playlist;
3350 if (playlist->amount <= 0)
3351 return -1;
3353 /* use current working directory as base for pathname */
3354 if (format_track_path(path, filename, sizeof(tmp_buf),
3355 strlen(filename)+1, getcwd(NULL, -1)) < 0)
3356 return -1;
3358 if (!strncmp(playlist->filename, path, strlen(path)))
3360 /* Attempting to overwrite current playlist file.*/
3362 if (playlist->buffer_size < (int)(playlist->amount * sizeof(int)))
3364 /* not enough buffer space to store updated indices */
3365 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
3366 return -1;
3369 /* in_ram buffer is unused for m3u files so we'll use for storing
3370 updated indices */
3371 index_buf = (int*)playlist->buffer;
3373 /* use temporary pathname */
3374 snprintf(path, sizeof(path), "%s_temp", playlist->filename);
3375 overwrite_current = true;
3378 fd = open(path, O_CREAT|O_WRONLY|O_TRUNC);
3379 if (fd < 0)
3381 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
3382 return -1;
3385 display_playlist_count(count, ID2P(LANG_PLAYLIST_SAVE_COUNT), false);
3387 cpu_boost(true);
3389 index = playlist->first_index;
3390 for (i=0; i<playlist->amount; i++)
3392 bool control_file;
3393 bool queue;
3394 int seek;
3396 /* user abort */
3397 if (action_userabort(TIMEOUT_NOBLOCK))
3399 result = -1;
3400 break;
3403 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
3404 queue = playlist->indices[index] & PLAYLIST_QUEUE_MASK;
3405 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
3407 /* Don't save queued files */
3408 if (!queue)
3410 if (get_filename(playlist, index, seek, control_file, tmp_buf,
3411 MAX_PATH+1) < 0)
3413 result = -1;
3414 break;
3417 if (overwrite_current)
3418 index_buf[count] = lseek(fd, 0, SEEK_CUR);
3420 if (fdprintf(fd, "%s\n", tmp_buf) < 0)
3422 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
3423 result = -1;
3424 break;
3427 count++;
3429 if ((count % PLAYLIST_DISPLAY_COUNT) == 0)
3430 display_playlist_count(count, ID2P(LANG_PLAYLIST_SAVE_COUNT),
3431 false);
3433 yield();
3436 index = (index+1)%playlist->amount;
3439 display_playlist_count(count, ID2P(LANG_PLAYLIST_SAVE_COUNT), true);
3441 close(fd);
3443 if (overwrite_current && result >= 0)
3445 result = -1;
3447 mutex_lock(&playlist->control_mutex);
3449 /* Replace the current playlist with the new one and update indices */
3450 close(playlist->fd);
3451 if (remove(playlist->filename) >= 0)
3453 if (rename(path, playlist->filename) >= 0)
3455 playlist->fd = open(playlist->filename, O_RDONLY);
3456 if (playlist->fd >= 0)
3458 index = playlist->first_index;
3459 for (i=0, count=0; i<playlist->amount; i++)
3461 if (!(playlist->indices[index] & PLAYLIST_QUEUE_MASK))
3463 playlist->indices[index] = index_buf[count];
3464 count++;
3466 index = (index+1)%playlist->amount;
3469 /* we need to recreate control because inserted tracks are
3470 now part of the playlist and shuffle has been
3471 invalidated */
3472 result = recreate_control(playlist);
3477 mutex_unlock(&playlist->control_mutex);
3481 cpu_boost(false);
3483 return result;
3487 * Search specified directory for tracks and notify via callback. May be
3488 * called recursively.
3490 int playlist_directory_tracksearch(const char* dirname, bool recurse,
3491 int (*callback)(char*, void*),
3492 void* context)
3494 char buf[MAX_PATH+1];
3495 int result = 0;
3496 int num_files = 0;
3497 int i;
3498 struct entry *files;
3499 struct tree_context* tc = tree_get_context();
3500 int old_dirfilter = *(tc->dirfilter);
3502 if (!callback)
3503 return -1;
3505 /* use the tree browser dircache to load files */
3506 *(tc->dirfilter) = SHOW_ALL;
3508 if (ft_load(tc, dirname) < 0)
3510 gui_syncsplash(HZ*2, ID2P(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));
3511 *(tc->dirfilter) = old_dirfilter;
3512 return -1;
3515 files = (struct entry*) tc->dircache;
3516 num_files = tc->filesindir;
3518 /* we've overwritten the dircache so tree browser will need to be
3519 reloaded */
3520 reload_directory();
3522 for (i=0; i<num_files; i++)
3524 /* user abort */
3525 if (action_userabort(TIMEOUT_NOBLOCK))
3527 result = -1;
3528 break;
3531 if (files[i].attr & ATTR_DIRECTORY)
3533 if (recurse)
3535 /* recursively add directories */
3536 snprintf(buf, sizeof(buf), "%s/%s", dirname, files[i].name);
3537 result = playlist_directory_tracksearch(buf, recurse,
3538 callback, context);
3539 if (result < 0)
3540 break;
3542 /* we now need to reload our current directory */
3543 if(ft_load(tc, dirname) < 0)
3545 result = -1;
3546 break;
3549 files = (struct entry*) tc->dircache;
3550 num_files = tc->filesindir;
3551 if (!num_files)
3553 result = -1;
3554 break;
3557 else
3558 continue;
3560 else if ((files[i].attr & FILE_ATTR_MASK) == FILE_ATTR_AUDIO)
3562 snprintf(buf, sizeof(buf), "%s/%s", dirname, files[i].name);
3564 if (callback(buf, context) != 0)
3566 result = -1;
3567 break;
3570 /* let the other threads work */
3571 yield();
3575 /* restore dirfilter */
3576 *(tc->dirfilter) = old_dirfilter;
3578 return result;