Few more fixes, notably make audiobufend static.
[kugel-rb.git] / apps / playlist.c
blob978ceea1bf47e6b9dab97cc0d79399f785188243
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by wavey@wavey.org
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
23 Dynamic playlist design (based on design originally proposed by ricII)
25 There are two files associated with a dynamic playlist:
26 1. Playlist file : This file contains the initial songs in the playlist.
27 The file is created by the user and stored on the hard
28 drive. NOTE: If we are playing the contents of a
29 directory, there will be no playlist file.
30 2. Control file : This file is automatically created when a playlist is
31 started and contains all the commands done to it.
33 The first non-comment line in a control file must begin with
34 "P:VERSION:DIR:FILE" where VERSION is the playlist control file version,
35 DIR is the directory where the playlist is located and FILE is the
36 playlist filename. For dirplay, FILE will be empty. An empty playlist
37 will have both entries as null.
39 Control file commands:
40 a. Add track (A:<position>:<last position>:<path to track>)
41 - Insert a track at the specified position in the current
42 playlist. Last position is used to specify where last insertion
43 occurred.
44 b. Queue track (Q:<position>:<last position>:<path to track>)
45 - Queue a track at the specified position in the current
46 playlist. Queued tracks differ from added tracks in that they
47 are deleted from the playlist as soon as they are played and
48 they are not saved to disk as part of the playlist.
49 c. Delete track (D:<position>)
50 - Delete track from specified position in the current playlist.
51 d. Shuffle playlist (S:<seed>:<index>)
52 - Shuffle entire playlist with specified seed. The index
53 identifies the first index in the newly shuffled playlist
54 (needed for repeat mode).
55 e. Unshuffle playlist (U:<index>)
56 - Unshuffle entire playlist. The index identifies the first index
57 in the newly unshuffled playlist.
58 f. Reset last insert position (R)
59 - Needed so that insertions work properly after resume
61 Resume:
62 The only resume info that needs to be saved is the current index in the
63 playlist and the position in the track. When resuming, all the commands
64 in the control file will be reapplied so that the playlist indices are
65 exactly the same as before shutdown. To avoid unnecessary disk
66 accesses, the shuffle mode settings are also saved in settings and only
67 flushed to disk when required.
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <ctype.h>
73 #include "string-extra.h"
74 #include "playlist.h"
75 #include "ata_idle_notify.h"
76 #include "file.h"
77 #include "action.h"
78 #include "dir.h"
79 #include "debug.h"
80 #include "audio.h"
81 #include "lcd.h"
82 #include "kernel.h"
83 #include "settings.h"
84 #include "status.h"
85 #include "applimits.h"
86 #include "screens.h"
87 #include "buffer.h"
88 #include "misc.h"
89 #include "filefuncs.h"
90 #include "button.h"
91 #include "filetree.h"
92 #include "abrepeat.h"
93 #include "thread.h"
94 #include "usb.h"
95 #include "filetypes.h"
96 #ifdef HAVE_LCD_BITMAP
97 #include "icons.h"
98 #endif
99 #include "system.h"
101 #include "lang.h"
102 #include "talk.h"
103 #include "splash.h"
104 #include "rbunicode.h"
105 #include "root_menu.h"
107 #define PLAYLIST_CONTROL_FILE_VERSION 2
110 Each playlist index has a flag associated with it which identifies what
111 type of track it is. These flags are stored in the 4 high order bits of
112 the index.
114 NOTE: This limits the playlist file size to a max of 256M.
116 Bits 31-30:
117 00 = Playlist track
118 01 = Track was prepended into playlist
119 10 = Track was inserted into playlist
120 11 = Track was appended into playlist
121 Bit 29:
122 0 = Added track
123 1 = Queued track
124 Bit 28:
125 0 = Track entry is valid
126 1 = Track does not exist on disk and should be skipped
128 #define PLAYLIST_SEEK_MASK 0x0FFFFFFF
129 #define PLAYLIST_INSERT_TYPE_MASK 0xC0000000
130 #define PLAYLIST_QUEUE_MASK 0x20000000
132 #define PLAYLIST_INSERT_TYPE_PREPEND 0x40000000
133 #define PLAYLIST_INSERT_TYPE_INSERT 0x80000000
134 #define PLAYLIST_INSERT_TYPE_APPEND 0xC0000000
136 #define PLAYLIST_QUEUED 0x20000000
137 #define PLAYLIST_SKIPPED 0x10000000
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;
148 static void empty_playlist(struct playlist_info* playlist, bool resume);
149 static void new_playlist(struct playlist_info* playlist, const char *dir,
150 const char *file);
151 static void create_control(struct playlist_info* playlist);
152 static int check_control(struct playlist_info* playlist);
153 static int recreate_control(struct playlist_info* playlist);
154 static void update_playlist_filename(struct playlist_info* playlist,
155 const char *dir, const char *file);
156 static int add_indices_to_playlist(struct playlist_info* playlist,
157 char* buffer, size_t buflen);
158 static int add_track_to_playlist(struct playlist_info* playlist,
159 const char *filename, int position,
160 bool queue, int seek_pos);
161 static int directory_search_callback(char* filename, void* context);
162 static int remove_track_from_playlist(struct playlist_info* playlist,
163 int position, bool write);
164 static int randomise_playlist(struct playlist_info* playlist,
165 unsigned int seed, bool start_current,
166 bool write);
167 static int sort_playlist(struct playlist_info* playlist, bool start_current,
168 bool write);
169 static int get_next_index(const struct playlist_info* playlist, int steps,
170 int repeat_mode);
171 static void find_and_set_playlist_index(struct playlist_info* playlist,
172 unsigned int seek);
173 static int compare(const void* p1, const void* p2);
174 static int get_filename(struct playlist_info* playlist, int index, int seek,
175 bool control_file, char *buf, int buf_length);
176 static int get_next_directory(char *dir);
177 static int get_next_dir(char *dir, bool is_forward, bool recursion);
178 static int get_previous_directory(char *dir);
179 static int check_subdir_for_music(char *dir, const char *subdir, bool recurse);
180 static int format_track_path(char *dest, char *src, int buf_length, int max,
181 const char *dir);
182 static void display_playlist_count(int count, const unsigned char *fmt,
183 bool final);
184 static void display_buffer_full(void);
185 static int flush_cached_control(struct playlist_info* playlist);
186 static int update_control(struct playlist_info* playlist,
187 enum playlist_command command, int i1, int i2,
188 const char* s1, const char* s2, void* data);
189 static void sync_control(struct playlist_info* playlist, bool force);
190 static int rotate_index(const struct playlist_info* playlist, int index);
192 #ifdef HAVE_DIRCACHE
193 #define PLAYLIST_LOAD_POINTERS 1
195 static struct event_queue playlist_queue SHAREDBSS_ATTR;
196 static long playlist_stack[(DEFAULT_STACK_SIZE + 0x800)/sizeof(long)];
197 static const char playlist_thread_name[] = "playlist cachectrl";
198 #endif
200 static struct mutex current_playlist_mutex SHAREDBSS_ATTR;
201 static struct mutex created_playlist_mutex SHAREDBSS_ATTR;
203 /* Check if the filename suggests M3U or M3U8 format. */
204 static bool is_m3u8(const char* filename)
206 int len = strlen(filename);
208 /* Default to M3U8 unless explicitly told otherwise. */
209 return !(len > 4 && strcasecmp(&filename[len - 4], ".m3u") == 0);
213 /* Convert a filename in an M3U playlist to UTF-8.
215 * buf - the filename to convert; can contain more than one line from the
216 * playlist.
217 * buf_len - amount of buf that is used.
218 * buf_max - total size of buf.
219 * temp - temporary conversion buffer, at least buf_max bytes.
221 * Returns the length of the converted filename.
223 static int convert_m3u(char* buf, int buf_len, int buf_max, char* temp)
225 int i = 0;
226 char* dest;
228 /* Locate EOL. */
229 while ((buf[i] != '\n') && (buf[i] != '\r') && (i < buf_len))
231 i++;
234 /* Work back killing white space. */
235 while ((i > 0) && isspace(buf[i - 1]))
237 i--;
240 buf_len = i;
241 dest = temp;
243 /* Convert char by char, so as to not overflow temp (iso_decode should
244 * preferably handle this). No more than 4 bytes should be generated for
245 * each input char.
247 for (i = 0; i < buf_len && dest < (temp + buf_max - 4); i++)
249 dest = iso_decode(&buf[i], dest, -1, 1);
252 *dest = 0;
253 strcpy(buf, temp);
254 return dest - temp;
258 * remove any files and indices associated with the playlist
260 static void empty_playlist(struct playlist_info* playlist, bool resume)
262 playlist->filename[0] = '\0';
263 playlist->utf8 = true;
265 if(playlist->fd >= 0)
266 /* If there is an already open playlist, close it. */
267 close(playlist->fd);
268 playlist->fd = -1;
270 if(playlist->control_fd >= 0)
271 close(playlist->control_fd);
272 playlist->control_fd = -1;
273 playlist->control_created = false;
275 playlist->in_ram = false;
277 if (playlist->buffer)
278 playlist->buffer[0] = 0;
280 playlist->buffer_end_pos = 0;
282 playlist->index = 0;
283 playlist->first_index = 0;
284 playlist->amount = 0;
285 playlist->last_insert_pos = -1;
286 playlist->seed = 0;
287 playlist->shuffle_modified = false;
288 playlist->deleted = false;
289 playlist->num_inserted_tracks = 0;
290 playlist->started = false;
292 playlist->num_cached = 0;
293 playlist->pending_control_sync = false;
295 if (!resume && playlist->current)
297 /* start with fresh playlist control file when starting new
298 playlist */
299 create_control(playlist);
304 * Initialize a new playlist for viewing/editing/playing. dir is the
305 * directory where the playlist is located and file is the filename.
307 static void new_playlist(struct playlist_info* playlist, const char *dir,
308 const char *file)
310 const char *fileused = file;
311 const char *dirused = dir;
312 empty_playlist(playlist, false);
314 if (!fileused)
316 fileused = "";
318 if (dirused && playlist->current) /* !current cannot be in_ram */
319 playlist->in_ram = true;
320 else
321 dirused = ""; /* empty playlist */
324 update_playlist_filename(playlist, dirused, fileused);
326 if (playlist->control_fd >= 0)
328 update_control(playlist, PLAYLIST_COMMAND_PLAYLIST,
329 PLAYLIST_CONTROL_FILE_VERSION, -1, dirused, fileused, NULL);
330 sync_control(playlist, false);
335 * create control file for playlist
337 static void create_control(struct playlist_info* playlist)
339 playlist->control_fd = open(playlist->control_filename,
340 O_CREAT|O_RDWR|O_TRUNC, 0666);
341 if (playlist->control_fd < 0)
343 if (check_rockboxdir())
345 cond_talk_ids_fq(LANG_PLAYLIST_CONTROL_ACCESS_ERROR);
346 splashf(HZ*2, (unsigned char *)"%s (%d)",
347 str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR),
348 playlist->control_fd);
350 playlist->control_created = false;
352 else
354 playlist->control_created = true;
359 * validate the control file. This may include creating/initializing it if
360 * necessary;
362 static int check_control(struct playlist_info* playlist)
364 if (!playlist->control_created)
366 create_control(playlist);
368 if (playlist->control_fd >= 0)
370 char* dir = playlist->filename;
371 char* file = playlist->filename+playlist->dirlen;
372 char c = playlist->filename[playlist->dirlen-1];
374 playlist->filename[playlist->dirlen-1] = '\0';
376 update_control(playlist, PLAYLIST_COMMAND_PLAYLIST,
377 PLAYLIST_CONTROL_FILE_VERSION, -1, dir, file, NULL);
378 sync_control(playlist, false);
379 playlist->filename[playlist->dirlen-1] = c;
383 if (playlist->control_fd < 0)
384 return -1;
386 return 0;
390 * recreate the control file based on current playlist entries
392 static int recreate_control(struct playlist_info* playlist)
394 char temp_file[MAX_PATH+1];
395 int temp_fd = -1;
396 int i;
397 int result = 0;
399 if(playlist->control_fd >= 0)
401 char* dir = playlist->filename;
402 char* file = playlist->filename+playlist->dirlen;
403 char c = playlist->filename[playlist->dirlen-1];
405 close(playlist->control_fd);
407 snprintf(temp_file, sizeof(temp_file), "%s_temp",
408 playlist->control_filename);
410 if (rename(playlist->control_filename, temp_file) < 0)
411 return -1;
413 temp_fd = open(temp_file, O_RDONLY);
414 if (temp_fd < 0)
415 return -1;
417 playlist->control_fd = open(playlist->control_filename,
418 O_CREAT|O_RDWR|O_TRUNC, 0666);
419 if (playlist->control_fd < 0)
420 return -1;
422 playlist->filename[playlist->dirlen-1] = '\0';
424 /* cannot call update_control() because of mutex */
425 result = fdprintf(playlist->control_fd, "P:%d:%s:%s\n",
426 PLAYLIST_CONTROL_FILE_VERSION, dir, file);
428 playlist->filename[playlist->dirlen-1] = c;
430 if (result < 0)
432 close(temp_fd);
433 return result;
437 playlist->seed = 0;
438 playlist->shuffle_modified = false;
439 playlist->deleted = false;
440 playlist->num_inserted_tracks = 0;
442 for (i=0; i<playlist->amount; i++)
444 if (playlist->indices[i] & PLAYLIST_INSERT_TYPE_MASK)
446 bool queue = playlist->indices[i] & PLAYLIST_QUEUE_MASK;
447 char inserted_file[MAX_PATH+1];
449 lseek(temp_fd, playlist->indices[i] & PLAYLIST_SEEK_MASK,
450 SEEK_SET);
451 read_line(temp_fd, inserted_file, sizeof(inserted_file));
453 result = fdprintf(playlist->control_fd, "%c:%d:%d:",
454 queue?'Q':'A', i, playlist->last_insert_pos);
455 if (result > 0)
457 /* save the position in file where name is written */
458 int seek_pos = lseek(playlist->control_fd, 0, SEEK_CUR);
460 result = fdprintf(playlist->control_fd, "%s\n",
461 inserted_file);
463 playlist->indices[i] =
464 (playlist->indices[i] & ~PLAYLIST_SEEK_MASK) | seek_pos;
467 if (result < 0)
468 break;
470 playlist->num_inserted_tracks++;
474 close(temp_fd);
475 remove(temp_file);
476 fsync(playlist->control_fd);
478 if (result < 0)
479 return result;
481 return 0;
485 * store directory and name of playlist file
487 static void update_playlist_filename(struct playlist_info* playlist,
488 const char *dir, const char *file)
490 char *sep="";
491 int dirlen = strlen(dir);
493 playlist->utf8 = is_m3u8(file);
495 /* If the dir does not end in trailing slash, we use a separator.
496 Otherwise we don't. */
497 if('/' != dir[dirlen-1])
499 sep="/";
500 dirlen++;
503 playlist->dirlen = dirlen;
505 snprintf(playlist->filename, sizeof(playlist->filename),
506 "%s%s%s", dir, sep, file);
510 * calculate track offsets within a playlist file
512 static int add_indices_to_playlist(struct playlist_info* playlist,
513 char* buffer, size_t buflen)
515 unsigned int nread;
516 unsigned int i = 0;
517 unsigned int count = 0;
518 bool store_index;
519 unsigned char *p;
520 int result = 0;
522 if(-1 == playlist->fd)
523 playlist->fd = open_utf8(playlist->filename, O_RDONLY);
524 if(playlist->fd < 0)
525 return -1; /* failure */
526 if((i = lseek(playlist->fd, 0, SEEK_CUR)) > 0)
527 playlist->utf8 = true; /* Override any earlier indication. */
529 splash(0, ID2P(LANG_WAIT));
531 if (!buffer)
533 /* use mp3 buffer for maximum load speed */
534 audio_stop();
535 buffer = audio_get_buffer(false, &buflen);
538 store_index = true;
540 while(1)
542 nread = read(playlist->fd, buffer, buflen);
543 /* Terminate on EOF */
544 if(nread <= 0)
545 break;
547 p = (unsigned char *)buffer;
549 for(count=0; count < nread; count++,p++) {
551 /* Are we on a new line? */
552 if((*p == '\n') || (*p == '\r'))
554 store_index = true;
556 else if(store_index)
558 store_index = false;
560 if(*p != '#')
562 if ( playlist->amount >= playlist->max_playlist_size ) {
563 display_buffer_full();
564 result = -1;
565 goto exit;
568 /* Store a new entry */
569 playlist->indices[ playlist->amount ] = i+count;
570 #ifdef HAVE_DIRCACHE
571 if (playlist->filenames)
572 playlist->filenames[ playlist->amount ] = NULL;
573 #endif
574 playlist->amount++;
579 i+= count;
582 exit:
583 #ifdef HAVE_DIRCACHE
584 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
585 #endif
587 return result;
591 * Utility function to create a new playlist, fill it with the next or
592 * previous directory, shuffle it if needed, and start playback.
593 * If play_last is true and direction zero or negative, start playing
594 * the last file in the directory, otherwise start playing the first.
596 static int create_and_play_dir(int direction, bool play_last)
598 char dir[MAX_PATH + 1];
599 int res;
600 int index = -1;
602 if(direction > 0)
603 res = get_next_directory(dir);
604 else
605 res = get_previous_directory(dir);
607 if (!res)
609 if (playlist_create(dir, NULL) != -1)
611 ft_build_playlist(tree_get_context(), 0);
613 if (global_settings.playlist_shuffle)
614 playlist_shuffle(current_tick, -1);
616 if (play_last && direction <= 0)
617 index = current_playlist.amount - 1;
618 else
619 index = 0;
621 #if (CONFIG_CODEC == SWCODEC)
622 current_playlist.started = true;
623 #else
624 playlist_start(index, 0);
625 #endif
628 /* we've overwritten the dircache when getting the next/previous dir,
629 so the tree browser context will need to be reloaded */
630 reload_directory();
633 return index;
637 * Removes all tracks, from the playlist, leaving the presently playing
638 * track queued.
640 int playlist_remove_all_tracks(struct playlist_info *playlist)
642 int result;
644 if (playlist == NULL)
645 playlist = &current_playlist;
647 while (playlist->index > 0)
648 if ((result = remove_track_from_playlist(playlist, 0, true)) < 0)
649 return result;
651 while (playlist->amount > 1)
652 if ((result = remove_track_from_playlist(playlist, 1, true)) < 0)
653 return result;
655 if (playlist->amount == 1) {
656 playlist->indices[0] |= PLAYLIST_QUEUED;
659 return 0;
664 * Add track to playlist at specified position. There are seven special
665 * positions that can be specified:
666 * PLAYLIST_PREPEND - Add track at beginning of playlist
667 * PLAYLIST_INSERT - Add track after current song. NOTE: If
668 * there are already inserted tracks then track
669 * is added to the end of the insertion list
670 * PLAYLIST_INSERT_FIRST - Add track immediately after current song, no
671 * matter what other tracks have been inserted
672 * PLAYLIST_INSERT_LAST - Add track to end of playlist
673 * PLAYLIST_INSERT_SHUFFLED - Add track at some random point between the
674 * current playing track and end of playlist
675 * PLAYLIST_INSERT_LAST_SHUFFLED - Add tracks in random order to the end of
676 * the playlist.
677 * PLAYLIST_REPLACE - Erase current playlist, Cue the current track
678 * and inster this track at the end.
680 static int add_track_to_playlist(struct playlist_info* playlist,
681 const char *filename, int position,
682 bool queue, int seek_pos)
684 int insert_position, orig_position;
685 unsigned long flags = PLAYLIST_INSERT_TYPE_INSERT;
686 int i;
688 insert_position = orig_position = position;
690 if (playlist->amount >= playlist->max_playlist_size)
692 display_buffer_full();
693 return -1;
696 switch (position)
698 case PLAYLIST_PREPEND:
699 position = insert_position = playlist->first_index;
700 break;
701 case PLAYLIST_INSERT:
702 /* if there are already inserted tracks then add track to end of
703 insertion list else add after current playing track */
704 if (playlist->last_insert_pos >= 0 &&
705 playlist->last_insert_pos < playlist->amount &&
706 (playlist->indices[playlist->last_insert_pos]&
707 PLAYLIST_INSERT_TYPE_MASK) == PLAYLIST_INSERT_TYPE_INSERT)
708 position = insert_position = playlist->last_insert_pos+1;
709 else if (playlist->amount > 0)
710 position = insert_position = playlist->index + 1;
711 else
712 position = insert_position = 0;
714 playlist->last_insert_pos = position;
715 break;
716 case PLAYLIST_INSERT_FIRST:
717 if (playlist->amount > 0)
718 position = insert_position = playlist->index + 1;
719 else
720 position = insert_position = 0;
722 playlist->last_insert_pos = position;
723 break;
724 case PLAYLIST_INSERT_LAST:
725 if (playlist->first_index > 0)
726 position = insert_position = playlist->first_index;
727 else
728 position = insert_position = playlist->amount;
730 playlist->last_insert_pos = position;
731 break;
732 case PLAYLIST_INSERT_SHUFFLED:
734 if (playlist->started)
736 int offset;
737 int n = playlist->amount -
738 rotate_index(playlist, playlist->index);
740 if (n > 0)
741 offset = rand() % n;
742 else
743 offset = 0;
745 position = playlist->index + offset + 1;
746 if (position >= playlist->amount)
747 position -= playlist->amount;
749 insert_position = position;
751 else
752 position = insert_position = (rand() % (playlist->amount+1));
753 break;
755 case PLAYLIST_INSERT_LAST_SHUFFLED:
757 position = insert_position = playlist->last_shuffled_start +
758 rand() % (playlist->amount - playlist->last_shuffled_start + 1);
759 break;
761 case PLAYLIST_REPLACE:
762 if (playlist_remove_all_tracks(playlist) < 0)
763 return -1;
765 playlist->last_insert_pos = position = insert_position = playlist->index + 1;
766 break;
769 if (queue)
770 flags |= PLAYLIST_QUEUED;
772 /* shift indices so that track can be added */
773 for (i=playlist->amount; i>insert_position; i--)
775 playlist->indices[i] = playlist->indices[i-1];
776 #ifdef HAVE_DIRCACHE
777 if (playlist->filenames)
778 playlist->filenames[i] = playlist->filenames[i-1];
779 #endif
782 /* update stored indices if needed */
784 if (orig_position < 0)
786 if (playlist->amount > 0 && insert_position <= playlist->index &&
787 playlist->started)
788 playlist->index++;
790 if (playlist->amount > 0 && insert_position <= playlist->first_index &&
791 orig_position != PLAYLIST_PREPEND && playlist->started)
792 playlist->first_index++;
795 if (insert_position < playlist->last_insert_pos ||
796 (insert_position == playlist->last_insert_pos && position < 0))
797 playlist->last_insert_pos++;
799 if (seek_pos < 0 && playlist->control_fd >= 0)
801 int result = update_control(playlist,
802 (queue?PLAYLIST_COMMAND_QUEUE:PLAYLIST_COMMAND_ADD), position,
803 playlist->last_insert_pos, filename, NULL, &seek_pos);
805 if (result < 0)
806 return result;
809 playlist->indices[insert_position] = flags | seek_pos;
811 #ifdef HAVE_DIRCACHE
812 if (playlist->filenames)
813 playlist->filenames[insert_position] = NULL;
814 #endif
816 playlist->amount++;
817 playlist->num_inserted_tracks++;
819 return insert_position;
823 * Callback for playlist_directory_tracksearch to insert track into
824 * playlist.
826 static int directory_search_callback(char* filename, void* context)
828 struct directory_search_context* c =
829 (struct directory_search_context*) context;
830 int insert_pos;
832 insert_pos = add_track_to_playlist(c->playlist, filename, c->position,
833 c->queue, -1);
835 if (insert_pos < 0)
836 return -1;
838 (c->count)++;
840 /* Make sure tracks are inserted in correct order if user requests
841 INSERT_FIRST */
842 if (c->position == PLAYLIST_INSERT_FIRST || c->position >= 0)
843 c->position = insert_pos + 1;
845 if (((c->count)%PLAYLIST_DISPLAY_COUNT) == 0)
847 unsigned char* count_str;
849 if (c->queue)
850 count_str = ID2P(LANG_PLAYLIST_QUEUE_COUNT);
851 else
852 count_str = ID2P(LANG_PLAYLIST_INSERT_COUNT);
854 display_playlist_count(c->count, count_str, false);
856 if ((c->count) == PLAYLIST_DISPLAY_COUNT &&
857 (audio_status() & AUDIO_STATUS_PLAY) &&
858 c->playlist->started)
859 audio_flush_and_reload_tracks();
862 return 0;
866 * remove track at specified position
868 static int remove_track_from_playlist(struct playlist_info* playlist,
869 int position, bool write)
871 int i;
872 bool inserted;
874 if (playlist->amount <= 0)
875 return -1;
877 inserted = playlist->indices[position] & PLAYLIST_INSERT_TYPE_MASK;
879 /* shift indices now that track has been removed */
880 for (i=position; i<playlist->amount; i++)
882 playlist->indices[i] = playlist->indices[i+1];
883 #ifdef HAVE_DIRCACHE
884 if (playlist->filenames)
885 playlist->filenames[i] = playlist->filenames[i+1];
886 #endif
889 playlist->amount--;
891 if (inserted)
892 playlist->num_inserted_tracks--;
893 else
894 playlist->deleted = true;
896 /* update stored indices if needed */
897 if (position < playlist->index)
898 playlist->index--;
900 if (position < playlist->first_index)
902 playlist->first_index--;
905 if (position <= playlist->last_insert_pos)
906 playlist->last_insert_pos--;
908 if (write && playlist->control_fd >= 0)
910 int result = update_control(playlist, PLAYLIST_COMMAND_DELETE,
911 position, -1, NULL, NULL, NULL);
913 if (result < 0)
914 return result;
916 sync_control(playlist, false);
919 return 0;
923 * randomly rearrange the array of indices for the playlist. If start_current
924 * is true then update the index to the new index of the current playing track
926 static int randomise_playlist(struct playlist_info* playlist,
927 unsigned int seed, bool start_current,
928 bool write)
930 int count;
931 int candidate;
932 long store;
933 unsigned int current = playlist->indices[playlist->index];
935 /* seed 0 is used to identify sorted playlist for resume purposes */
936 if (seed == 0)
937 seed = 1;
939 /* seed with the given seed */
940 srand(seed);
942 /* randomise entire indices list */
943 for(count = playlist->amount - 1; count >= 0; count--)
945 /* the rand is from 0 to RAND_MAX, so adjust to our value range */
946 candidate = rand() % (count + 1);
948 /* now swap the values at the 'count' and 'candidate' positions */
949 store = playlist->indices[candidate];
950 playlist->indices[candidate] = playlist->indices[count];
951 playlist->indices[count] = store;
952 #ifdef HAVE_DIRCACHE
953 if (playlist->filenames)
955 store = (long)playlist->filenames[candidate];
956 playlist->filenames[candidate] = playlist->filenames[count];
957 playlist->filenames[count] = (struct dircache_entry *)store;
959 #endif
962 if (start_current)
963 find_and_set_playlist_index(playlist, current);
965 /* indices have been moved so last insert position is no longer valid */
966 playlist->last_insert_pos = -1;
968 playlist->seed = seed;
969 if (playlist->num_inserted_tracks > 0 || playlist->deleted)
970 playlist->shuffle_modified = true;
972 if (write)
974 update_control(playlist, PLAYLIST_COMMAND_SHUFFLE, seed,
975 playlist->first_index, NULL, NULL, NULL);
978 return 0;
982 * Sort the array of indices for the playlist. If start_current is true then
983 * set the index to the new index of the current song.
984 * Also while going to unshuffled mode set the first_index to 0.
986 static int sort_playlist(struct playlist_info* playlist, bool start_current,
987 bool write)
989 unsigned int current = playlist->indices[playlist->index];
991 if (playlist->amount > 0)
992 qsort(playlist->indices, playlist->amount,
993 sizeof(playlist->indices[0]), compare);
995 #ifdef HAVE_DIRCACHE
996 /** We need to re-check the song names from disk because qsort can't
997 * sort two arrays at once :/
998 * FIXME: Please implement a better way to do this. */
999 memset(playlist->filenames, 0, playlist->max_playlist_size * sizeof(int));
1000 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
1001 #endif
1003 if (start_current)
1004 find_and_set_playlist_index(playlist, current);
1006 /* indices have been moved so last insert position is no longer valid */
1007 playlist->last_insert_pos = -1;
1009 if (!playlist->num_inserted_tracks && !playlist->deleted)
1010 playlist->shuffle_modified = false;
1011 if (write && playlist->control_fd >= 0)
1013 playlist->first_index = 0;
1014 update_control(playlist, PLAYLIST_COMMAND_UNSHUFFLE,
1015 playlist->first_index, -1, NULL, NULL, NULL);
1018 return 0;
1021 /* Calculate how many steps we have to really step when skipping entries
1022 * marked as bad.
1024 static int calculate_step_count(const struct playlist_info *playlist, int steps)
1026 int i, count, direction;
1027 int index;
1028 int stepped_count = 0;
1030 if (steps < 0)
1032 direction = -1;
1033 count = -steps;
1035 else
1037 direction = 1;
1038 count = steps;
1041 index = playlist->index;
1042 i = 0;
1043 do {
1044 /* Boundary check */
1045 if (index < 0)
1046 index += playlist->amount;
1047 if (index >= playlist->amount)
1048 index -= playlist->amount;
1050 /* Check if we found a bad entry. */
1051 if (playlist->indices[index] & PLAYLIST_SKIPPED)
1053 steps += direction;
1054 /* Are all entries bad? */
1055 if (stepped_count++ > playlist->amount)
1056 break ;
1058 else
1059 i++;
1061 index += direction;
1062 } while (i <= count);
1064 return steps;
1067 /* Marks the index of the track to be skipped that is "steps" away from
1068 * current playing track.
1070 void playlist_skip_entry(struct playlist_info *playlist, int steps)
1072 int index;
1074 if (playlist == NULL)
1075 playlist = &current_playlist;
1077 /* need to account for already skipped tracks */
1078 steps = calculate_step_count(playlist, steps);
1080 index = playlist->index + steps;
1081 if (index < 0)
1082 index += playlist->amount;
1083 else if (index >= playlist->amount)
1084 index -= playlist->amount;
1086 playlist->indices[index] |= PLAYLIST_SKIPPED;
1090 * returns the index of the track that is "steps" away from current playing
1091 * track.
1093 static int get_next_index(const struct playlist_info* playlist, int steps,
1094 int repeat_mode)
1096 int current_index = playlist->index;
1097 int next_index = -1;
1099 if (playlist->amount <= 0)
1100 return -1;
1102 if (repeat_mode == -1)
1103 repeat_mode = global_settings.repeat_mode;
1105 if (repeat_mode == REPEAT_SHUFFLE && playlist->amount <= 1)
1106 repeat_mode = REPEAT_ALL;
1108 steps = calculate_step_count(playlist, steps);
1109 switch (repeat_mode)
1111 case REPEAT_SHUFFLE:
1112 /* Treat repeat shuffle just like repeat off. At end of playlist,
1113 play will be resumed in playlist_next() */
1114 case REPEAT_OFF:
1116 current_index = rotate_index(playlist, current_index);
1117 next_index = current_index+steps;
1118 if ((next_index < 0) || (next_index >= playlist->amount))
1119 next_index = -1;
1120 else
1121 next_index = (next_index+playlist->first_index) %
1122 playlist->amount;
1124 break;
1127 case REPEAT_ONE:
1128 #ifdef AB_REPEAT_ENABLE
1129 case REPEAT_AB:
1130 #endif
1131 next_index = current_index;
1132 break;
1134 case REPEAT_ALL:
1135 default:
1137 next_index = (current_index+steps) % playlist->amount;
1138 while (next_index < 0)
1139 next_index += playlist->amount;
1141 if (steps >= playlist->amount)
1143 int i, index;
1145 index = next_index;
1146 next_index = -1;
1148 /* second time around so skip the queued files */
1149 for (i=0; i<playlist->amount; i++)
1151 if (playlist->indices[index] & PLAYLIST_QUEUE_MASK)
1152 index = (index+1) % playlist->amount;
1153 else
1155 next_index = index;
1156 break;
1160 break;
1164 /* No luck if the whole playlist was bad. */
1165 if (playlist->indices[next_index] & PLAYLIST_SKIPPED)
1166 return -1;
1168 return next_index;
1172 * Search for the seek track and set appropriate indices. Used after shuffle
1173 * to make sure the current index is still pointing to correct track.
1175 static void find_and_set_playlist_index(struct playlist_info* playlist,
1176 unsigned int seek)
1178 int i;
1180 /* Set the index to the current song */
1181 for (i=0; i<playlist->amount; i++)
1183 if (playlist->indices[i] == seek)
1185 playlist->index = playlist->first_index = i;
1187 break;
1193 * used to sort track indices. Sort order is as follows:
1194 * 1. Prepended tracks (in prepend order)
1195 * 2. Playlist/directory tracks (in playlist order)
1196 * 3. Inserted/Appended tracks (in insert order)
1198 static int compare(const void* p1, const void* p2)
1200 unsigned long* e1 = (unsigned long*) p1;
1201 unsigned long* e2 = (unsigned long*) p2;
1202 unsigned long flags1 = *e1 & PLAYLIST_INSERT_TYPE_MASK;
1203 unsigned long flags2 = *e2 & PLAYLIST_INSERT_TYPE_MASK;
1205 if (flags1 == flags2)
1206 return (*e1 & PLAYLIST_SEEK_MASK) - (*e2 & PLAYLIST_SEEK_MASK);
1207 else if (flags1 == PLAYLIST_INSERT_TYPE_PREPEND ||
1208 flags2 == PLAYLIST_INSERT_TYPE_APPEND)
1209 return -1;
1210 else if (flags1 == PLAYLIST_INSERT_TYPE_APPEND ||
1211 flags2 == PLAYLIST_INSERT_TYPE_PREPEND)
1212 return 1;
1213 else if (flags1 && flags2)
1214 return (*e1 & PLAYLIST_SEEK_MASK) - (*e2 & PLAYLIST_SEEK_MASK);
1215 else
1216 return *e1 - *e2;
1219 #ifdef HAVE_DIRCACHE
1221 * Thread to update filename pointers to dircache on background
1222 * without affecting playlist load up performance. This thread also flushes
1223 * any pending control commands when the disk spins up.
1225 static void playlist_flush_callback(void *param)
1227 (void)param;
1228 struct playlist_info *playlist;
1229 playlist = &current_playlist;
1230 if (playlist->control_fd >= 0)
1232 if (playlist->num_cached > 0)
1234 mutex_lock(playlist->control_mutex);
1235 flush_cached_control(playlist);
1236 mutex_unlock(playlist->control_mutex);
1238 sync_control(playlist, true);
1242 static void playlist_thread(void)
1244 struct queue_event ev;
1245 bool dirty_pointers = false;
1246 static char tmp[MAX_PATH+1];
1248 struct playlist_info *playlist;
1249 int index;
1250 int seek;
1251 bool control_file;
1253 int sleep_time = 5;
1255 #ifdef HAVE_DISK_STORAGE
1256 if (global_settings.disk_spindown > 1 &&
1257 global_settings.disk_spindown <= 5)
1258 sleep_time = global_settings.disk_spindown - 1;
1259 #endif
1261 while (1)
1263 queue_wait_w_tmo(&playlist_queue, &ev, HZ*sleep_time);
1265 switch (ev.id)
1267 case PLAYLIST_LOAD_POINTERS:
1268 dirty_pointers = true;
1269 break ;
1271 /* Start the background scanning after either the disk spindown
1272 timeout or 5s, whichever is less */
1273 case SYS_TIMEOUT:
1274 playlist = &current_playlist;
1275 if (playlist->control_fd >= 0)
1277 if (playlist->num_cached > 0)
1278 register_storage_idle_func(playlist_flush_callback);
1281 if (!dirty_pointers)
1282 break ;
1284 if (!dircache_is_enabled() || !playlist->filenames
1285 || playlist->amount <= 0)
1286 break ;
1288 #ifdef HAVE_ADJUSTABLE_CPU_FREQ
1289 cpu_boost(true);
1290 #endif
1291 for (index = 0; index < playlist->amount
1292 && queue_empty(&playlist_queue); index++)
1294 /* Process only pointers that are not already loaded. */
1295 if (playlist->filenames[index])
1296 continue ;
1298 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
1299 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
1301 /* Load the filename from playlist file. */
1302 if (get_filename(playlist, index, seek, control_file, tmp,
1303 sizeof(tmp)) < 0)
1304 break ;
1306 /* Set the dircache entry pointer. */
1307 playlist->filenames[index] = dircache_get_entry_ptr(tmp);
1309 /* And be on background so user doesn't notice any delays. */
1310 yield();
1313 #ifdef HAVE_ADJUSTABLE_CPU_FREQ
1314 cpu_boost(false);
1315 #endif
1316 dirty_pointers = false;
1317 break ;
1319 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
1320 case SYS_USB_CONNECTED:
1321 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1322 usb_wait_for_disconnect(&playlist_queue);
1323 break ;
1324 #endif
1328 #endif
1331 * gets pathname for track at seek index
1333 static int get_filename(struct playlist_info* playlist, int index, int seek,
1334 bool control_file, char *buf, int buf_length)
1336 int fd;
1337 int max = -1;
1338 char tmp_buf[MAX_PATH+1];
1339 char dir_buf[MAX_PATH+1];
1340 bool utf8 = playlist->utf8;
1342 if (buf_length > MAX_PATH+1)
1343 buf_length = MAX_PATH+1;
1345 #ifdef HAVE_DIRCACHE
1346 if (dircache_is_enabled() && playlist->filenames)
1348 if (playlist->filenames[index] != NULL)
1350 dircache_copy_path(playlist->filenames[index], tmp_buf, sizeof(tmp_buf)-1);
1351 max = strlen(tmp_buf);
1354 #else
1355 (void)index;
1356 #endif
1358 if (playlist->in_ram && !control_file && max < 0)
1360 max = strlcpy(tmp_buf, &playlist->buffer[seek], sizeof(tmp_buf));
1362 else if (max < 0)
1364 mutex_lock(playlist->control_mutex);
1366 if (control_file)
1368 fd = playlist->control_fd;
1369 utf8 = true;
1371 else
1373 if(-1 == playlist->fd)
1374 playlist->fd = open(playlist->filename, O_RDONLY);
1376 fd = playlist->fd;
1379 if(-1 != fd)
1382 if (lseek(fd, seek, SEEK_SET) != seek)
1383 max = -1;
1384 else
1386 max = read(fd, tmp_buf, MIN((size_t) buf_length, sizeof(tmp_buf)));
1388 if ((max > 0) && !utf8)
1390 /* Use dir_buf as a temporary buffer. Note that dir_buf must
1391 * be as large as tmp_buf.
1393 max = convert_m3u(tmp_buf, max, sizeof(tmp_buf), dir_buf);
1398 mutex_unlock(playlist->control_mutex);
1400 if (max < 0)
1402 if (control_file)
1403 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
1404 else
1405 splash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
1407 return max;
1411 strlcpy(dir_buf, playlist->filename, playlist->dirlen);
1413 return (format_track_path(buf, tmp_buf, buf_length, max, dir_buf));
1416 static int get_next_directory(char *dir){
1417 return get_next_dir(dir,true,false);
1420 static int get_previous_directory(char *dir){
1421 return get_next_dir(dir,false,false);
1425 * search through all the directories (starting with the current) to find
1426 * one that has tracks to play
1428 static int get_next_dir(char *dir, bool is_forward, bool recursion)
1430 struct playlist_info* playlist = &current_playlist;
1431 int result = -1;
1432 char *start_dir = NULL;
1433 bool exit = false;
1434 int i;
1435 struct tree_context* tc = tree_get_context();
1436 int saved_dirfilter = *(tc->dirfilter);
1438 /* process random folder advance */
1439 if (global_settings.next_folder == FOLDER_ADVANCE_RANDOM)
1441 int fd = open(ROCKBOX_DIR "/folder_advance_list.dat", O_RDONLY);
1442 if (fd >= 0)
1444 char buffer[MAX_PATH];
1445 int folder_count = 0;
1446 srand(current_tick);
1447 *(tc->dirfilter) = SHOW_MUSIC;
1448 tc->sort_dir = global_settings.sort_dir;
1449 read(fd,&folder_count,sizeof(int));
1450 if (!folder_count)
1451 exit = true;
1452 while (!exit)
1454 i = rand()%folder_count;
1455 lseek(fd,sizeof(int) + (MAX_PATH*i),SEEK_SET);
1456 read(fd,buffer,MAX_PATH);
1457 if (check_subdir_for_music(buffer, "", false) ==0)
1458 exit = true;
1460 if (folder_count)
1461 strcpy(dir,buffer);
1462 close(fd);
1463 *(tc->dirfilter) = saved_dirfilter;
1464 tc->sort_dir = global_settings.sort_dir;
1465 reload_directory();
1466 return 0;
1470 /* not random folder advance (or random folder advance unavailable) */
1471 if (recursion)
1473 /* start with root */
1474 dir[0] = '\0';
1476 else
1478 /* start with current directory */
1479 strlcpy(dir, playlist->filename, playlist->dirlen);
1482 /* use the tree browser dircache to load files */
1483 *(tc->dirfilter) = SHOW_ALL;
1485 /* set up sorting/direction */
1486 tc->sort_dir = global_settings.sort_dir;
1487 if (!is_forward)
1489 static const char sortpairs[] =
1491 [SORT_ALPHA] = SORT_ALPHA_REVERSED,
1492 [SORT_DATE] = SORT_DATE_REVERSED,
1493 [SORT_TYPE] = SORT_TYPE_REVERSED,
1494 [SORT_ALPHA_REVERSED] = SORT_ALPHA,
1495 [SORT_DATE_REVERSED] = SORT_DATE,
1496 [SORT_TYPE_REVERSED] = SORT_TYPE,
1499 if ((unsigned)tc->sort_dir < sizeof(sortpairs))
1500 tc->sort_dir = sortpairs[tc->sort_dir];
1503 while (!exit)
1505 struct entry *files;
1506 int num_files = 0;
1507 int i;
1509 if (ft_load(tc, (dir[0]=='\0')?"/":dir) < 0)
1511 exit = true;
1512 result = -1;
1513 break;
1516 files = (struct entry*) tc->dircache;
1517 num_files = tc->filesindir;
1519 for (i=0; i<num_files; i++)
1521 /* user abort */
1522 if (action_userabort(TIMEOUT_NOBLOCK))
1524 result = -1;
1525 exit = true;
1526 break;
1529 if (files[i].attr & ATTR_DIRECTORY)
1531 if (!start_dir)
1533 result = check_subdir_for_music(dir, files[i].name, true);
1534 if (result != -1)
1536 exit = true;
1537 break;
1540 else if (!strcmp(start_dir, files[i].name))
1541 start_dir = NULL;
1545 if (!exit)
1547 /* move down to parent directory. current directory name is
1548 stored as the starting point for the search in parent */
1549 start_dir = strrchr(dir, '/');
1550 if (start_dir)
1552 *start_dir = '\0';
1553 start_dir++;
1555 else
1556 break;
1560 /* restore dirfilter */
1561 *(tc->dirfilter) = saved_dirfilter;
1562 tc->sort_dir = global_settings.sort_dir;
1564 /* special case if nothing found: try start searching again from root */
1565 if (result == -1 && !recursion){
1566 result = get_next_dir(dir, is_forward, true);
1569 return result;
1573 * Checks if there are any music files in the dir or any of its
1574 * subdirectories. May be called recursively.
1576 static int check_subdir_for_music(char *dir, const char *subdir, bool recurse)
1578 int result = -1;
1579 int dirlen = strlen(dir);
1580 int num_files = 0;
1581 int i;
1582 struct entry *files;
1583 bool has_music = false;
1584 bool has_subdir = false;
1585 struct tree_context* tc = tree_get_context();
1587 snprintf(dir+dirlen, MAX_PATH-dirlen, "/%s", subdir);
1589 if (ft_load(tc, dir) < 0)
1591 return -2;
1594 files = (struct entry*) tc->dircache;
1595 num_files = tc->filesindir;
1597 for (i=0; i<num_files; i++)
1599 if (files[i].attr & ATTR_DIRECTORY)
1600 has_subdir = true;
1601 else if ((files[i].attr & FILE_ATTR_MASK) == FILE_ATTR_AUDIO)
1603 has_music = true;
1604 break;
1608 if (has_music)
1609 return 0;
1611 if (has_subdir && recurse)
1613 for (i=0; i<num_files; i++)
1615 if (action_userabort(TIMEOUT_NOBLOCK))
1617 result = -2;
1618 break;
1621 if (files[i].attr & ATTR_DIRECTORY)
1623 result = check_subdir_for_music(dir, files[i].name, true);
1624 if (!result)
1625 break;
1630 if (result < 0)
1632 if (dirlen)
1634 dir[dirlen] = '\0';
1636 else
1638 strcpy(dir, "/");
1641 /* we now need to reload our current directory */
1642 if(ft_load(tc, dir) < 0)
1643 splash(HZ*2, ID2P(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));
1645 return result;
1649 * Returns absolute path of track
1651 static int format_track_path(char *dest, char *src, int buf_length, int max,
1652 const char *dir)
1654 int i = 0;
1655 int j;
1656 char *temp_ptr;
1658 /* Look for the end of the string */
1659 while((i < max) &&
1660 (src[i] != '\n') &&
1661 (src[i] != '\r') &&
1662 (src[i] != '\0'))
1663 i++;
1665 /* Now work back killing white space */
1666 while((i > 0) &&
1667 ((src[i-1] == ' ') ||
1668 (src[i-1] == '\t')))
1669 i--;
1671 /* Zero-terminate the file name */
1672 src[i]=0;
1674 /* replace backslashes with forward slashes */
1675 for ( j=0; j<i; j++ )
1676 if ( src[j] == '\\' )
1677 src[j] = '/';
1679 if('/' == src[0])
1681 strlcpy(dest, src, buf_length);
1683 else
1685 /* handle dos style drive letter */
1686 if (':' == src[1])
1687 strlcpy(dest, &src[2], buf_length);
1688 else if (!strncmp(src, "../", 3))
1690 /* handle relative paths */
1691 i=3;
1692 while(!strncmp(&src[i], "../", 3))
1693 i += 3;
1694 for (j=0; j<i/3; j++) {
1695 temp_ptr = strrchr(dir, '/');
1696 if (temp_ptr)
1697 *temp_ptr = '\0';
1698 else
1699 break;
1701 snprintf(dest, buf_length, "%s/%s", dir, &src[i]);
1703 else if ( '.' == src[0] && '/' == src[1] ) {
1704 snprintf(dest, buf_length, "%s/%s", dir, &src[2]);
1706 else {
1707 snprintf(dest, buf_length, "%s/%s", dir, src);
1711 return 0;
1715 * Display splash message showing progress of playlist/directory insertion or
1716 * save.
1718 static void display_playlist_count(int count, const unsigned char *fmt,
1719 bool final)
1721 static long talked_tick = 0;
1722 long id = P2ID(fmt);
1723 if(global_settings.talk_menu && id>=0)
1725 if(final || (count && (talked_tick == 0
1726 || TIME_AFTER(current_tick, talked_tick+5*HZ))))
1728 talked_tick = current_tick;
1729 talk_number(count, false);
1730 talk_id(id, true);
1733 fmt = P2STR(fmt);
1735 splashf(0, fmt, count, str(LANG_OFF_ABORT));
1739 * Display buffer full message
1741 static void display_buffer_full(void)
1743 splash(HZ*2, ID2P(LANG_PLAYLIST_BUFFER_FULL));
1747 * Flush any cached control commands to disk. Called when playlist is being
1748 * modified. Returns 0 on success and -1 on failure.
1750 static int flush_cached_control(struct playlist_info* playlist)
1752 int result = 0;
1753 int i;
1755 if (!playlist->num_cached)
1756 return 0;
1758 lseek(playlist->control_fd, 0, SEEK_END);
1760 for (i=0; i<playlist->num_cached; i++)
1762 struct playlist_control_cache* cache =
1763 &(playlist->control_cache[i]);
1765 switch (cache->command)
1767 case PLAYLIST_COMMAND_PLAYLIST:
1768 result = fdprintf(playlist->control_fd, "P:%d:%s:%s\n",
1769 cache->i1, cache->s1, cache->s2);
1770 break;
1771 case PLAYLIST_COMMAND_ADD:
1772 case PLAYLIST_COMMAND_QUEUE:
1773 result = fdprintf(playlist->control_fd, "%c:%d:%d:",
1774 (cache->command == PLAYLIST_COMMAND_ADD)?'A':'Q',
1775 cache->i1, cache->i2);
1776 if (result > 0)
1778 /* save the position in file where name is written */
1779 int* seek_pos = (int *)cache->data;
1780 *seek_pos = lseek(playlist->control_fd, 0, SEEK_CUR);
1781 result = fdprintf(playlist->control_fd, "%s\n",
1782 cache->s1);
1784 break;
1785 case PLAYLIST_COMMAND_DELETE:
1786 result = fdprintf(playlist->control_fd, "D:%d\n", cache->i1);
1787 break;
1788 case PLAYLIST_COMMAND_SHUFFLE:
1789 result = fdprintf(playlist->control_fd, "S:%d:%d\n",
1790 cache->i1, cache->i2);
1791 break;
1792 case PLAYLIST_COMMAND_UNSHUFFLE:
1793 result = fdprintf(playlist->control_fd, "U:%d\n", cache->i1);
1794 break;
1795 case PLAYLIST_COMMAND_RESET:
1796 result = fdprintf(playlist->control_fd, "R\n");
1797 break;
1798 default:
1799 break;
1802 if (result <= 0)
1803 break;
1806 if (result > 0)
1808 playlist->num_cached = 0;
1809 playlist->pending_control_sync = true;
1811 result = 0;
1813 else
1815 result = -1;
1816 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_UPDATE_ERROR));
1819 return result;
1823 * Update control data with new command. Depending on the command, it may be
1824 * cached or flushed to disk.
1826 static int update_control(struct playlist_info* playlist,
1827 enum playlist_command command, int i1, int i2,
1828 const char* s1, const char* s2, void* data)
1830 int result = 0;
1831 struct playlist_control_cache* cache;
1832 bool flush = false;
1834 mutex_lock(playlist->control_mutex);
1836 cache = &(playlist->control_cache[playlist->num_cached++]);
1838 cache->command = command;
1839 cache->i1 = i1;
1840 cache->i2 = i2;
1841 cache->s1 = s1;
1842 cache->s2 = s2;
1843 cache->data = data;
1845 switch (command)
1847 case PLAYLIST_COMMAND_PLAYLIST:
1848 case PLAYLIST_COMMAND_ADD:
1849 case PLAYLIST_COMMAND_QUEUE:
1850 #ifndef HAVE_DIRCACHE
1851 case PLAYLIST_COMMAND_DELETE:
1852 case PLAYLIST_COMMAND_RESET:
1853 #endif
1854 flush = true;
1855 break;
1856 case PLAYLIST_COMMAND_SHUFFLE:
1857 case PLAYLIST_COMMAND_UNSHUFFLE:
1858 default:
1859 /* only flush when needed */
1860 break;
1863 if (flush || playlist->num_cached == PLAYLIST_MAX_CACHE)
1864 result = flush_cached_control(playlist);
1866 mutex_unlock(playlist->control_mutex);
1868 return result;
1872 * sync control file to disk
1874 static void sync_control(struct playlist_info* playlist, bool force)
1876 #ifdef HAVE_DIRCACHE
1877 if (playlist->started && force)
1878 #else
1879 (void) force;
1881 if (playlist->started)
1882 #endif
1884 if (playlist->pending_control_sync)
1886 mutex_lock(playlist->control_mutex);
1887 fsync(playlist->control_fd);
1888 playlist->pending_control_sync = false;
1889 mutex_unlock(playlist->control_mutex);
1895 * Rotate indices such that first_index is index 0
1897 static int rotate_index(const struct playlist_info* playlist, int index)
1899 index -= playlist->first_index;
1900 if (index < 0)
1901 index += playlist->amount;
1903 return index;
1907 * Initialize playlist entries at startup
1909 void playlist_init(void)
1911 struct playlist_info* playlist = &current_playlist;
1913 mutex_init(&current_playlist_mutex);
1914 mutex_init(&created_playlist_mutex);
1916 playlist->current = true;
1917 strlcpy(playlist->control_filename, PLAYLIST_CONTROL_FILE,
1918 sizeof(playlist->control_filename));
1919 playlist->fd = -1;
1920 playlist->control_fd = -1;
1921 playlist->max_playlist_size = global_settings.max_files_in_playlist;
1922 playlist->indices = buffer_alloc(
1923 playlist->max_playlist_size * sizeof(int));
1924 playlist->buffer_size =
1925 AVERAGE_FILENAME_LENGTH * global_settings.max_files_in_dir;
1926 playlist->buffer = buffer_alloc(playlist->buffer_size);
1927 playlist->control_mutex = &current_playlist_mutex;
1929 empty_playlist(playlist, true);
1931 #ifdef HAVE_DIRCACHE
1932 playlist->filenames = buffer_alloc(
1933 playlist->max_playlist_size * sizeof(int));
1934 memset(playlist->filenames, 0,
1935 playlist->max_playlist_size * sizeof(int));
1936 create_thread(playlist_thread, playlist_stack, sizeof(playlist_stack),
1937 0, playlist_thread_name IF_PRIO(, PRIORITY_BACKGROUND)
1938 IF_COP(, CPU));
1939 queue_init(&playlist_queue, true);
1940 #endif
1944 * Clean playlist at shutdown
1946 void playlist_shutdown(void)
1948 struct playlist_info* playlist = &current_playlist;
1950 if (playlist->control_fd >= 0)
1952 mutex_lock(playlist->control_mutex);
1954 if (playlist->num_cached > 0)
1955 flush_cached_control(playlist);
1957 close(playlist->control_fd);
1959 mutex_unlock(playlist->control_mutex);
1964 * Create new playlist
1966 int playlist_create(const char *dir, const char *file)
1968 struct playlist_info* playlist = &current_playlist;
1970 new_playlist(playlist, dir, file);
1972 if (file)
1973 /* load the playlist file */
1974 add_indices_to_playlist(playlist, NULL, 0);
1976 return 0;
1979 #define PLAYLIST_COMMAND_SIZE (MAX_PATH+12)
1982 * Restore the playlist state based on control file commands. Called to
1983 * resume playback after shutdown.
1985 int playlist_resume(void)
1987 struct playlist_info* playlist = &current_playlist;
1988 char *buffer;
1989 size_t buflen;
1990 int nread;
1991 int total_read = 0;
1992 int control_file_size = 0;
1993 bool first = true;
1994 bool sorted = true;
1996 /* use mp3 buffer for maximum load speed */
1997 buffer = (char *)audio_get_buffer(false, &buflen);
1999 empty_playlist(playlist, true);
2001 splash(0, ID2P(LANG_WAIT));
2002 playlist->control_fd = open(playlist->control_filename, O_RDWR);
2003 if (playlist->control_fd < 0)
2005 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2006 return -1;
2008 playlist->control_created = true;
2010 control_file_size = filesize(playlist->control_fd);
2011 if (control_file_size <= 0)
2013 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2014 return -1;
2017 /* read a small amount first to get the header */
2018 nread = read(playlist->control_fd, buffer,
2019 PLAYLIST_COMMAND_SIZE<buflen?PLAYLIST_COMMAND_SIZE:buflen);
2020 if(nread <= 0)
2022 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2023 return -1;
2026 playlist->started = true;
2028 while (1)
2030 int result = 0;
2031 int count;
2032 enum playlist_command current_command = PLAYLIST_COMMAND_COMMENT;
2033 int last_newline = 0;
2034 int str_count = -1;
2035 bool newline = true;
2036 bool exit_loop = false;
2037 char *p = buffer;
2038 char *str1 = NULL;
2039 char *str2 = NULL;
2040 char *str3 = NULL;
2041 unsigned long last_tick = current_tick;
2042 bool useraborted = false;
2044 for(count=0; count<nread && !exit_loop && !useraborted; count++,p++)
2046 /* So a splash while we are loading. */
2047 if (TIME_AFTER(current_tick, last_tick + HZ/4))
2049 splashf(0, str(LANG_LOADING_PERCENT),
2050 (total_read+count)*100/control_file_size,
2051 str(LANG_OFF_ABORT));
2052 if (action_userabort(TIMEOUT_NOBLOCK))
2054 useraborted = true;
2055 break;
2057 last_tick = current_tick;
2060 /* Are we on a new line? */
2061 if((*p == '\n') || (*p == '\r'))
2063 *p = '\0';
2065 /* save last_newline in case we need to load more data */
2066 last_newline = count;
2068 switch (current_command)
2070 case PLAYLIST_COMMAND_PLAYLIST:
2072 /* str1=version str2=dir str3=file */
2073 int version;
2075 if (!str1)
2077 result = -1;
2078 exit_loop = true;
2079 break;
2082 if (!str2)
2083 str2 = "";
2085 if (!str3)
2086 str3 = "";
2088 version = atoi(str1);
2090 if (version != PLAYLIST_CONTROL_FILE_VERSION)
2091 return -1;
2093 update_playlist_filename(playlist, str2, str3);
2095 if (str3[0] != '\0')
2097 /* NOTE: add_indices_to_playlist() overwrites the
2098 audiobuf so we need to reload control file
2099 data */
2100 add_indices_to_playlist(playlist, NULL, 0);
2102 else if (str2[0] != '\0')
2104 playlist->in_ram = true;
2105 resume_directory(str2);
2108 /* load the rest of the data */
2109 first = false;
2110 exit_loop = true;
2112 break;
2114 case PLAYLIST_COMMAND_ADD:
2115 case PLAYLIST_COMMAND_QUEUE:
2117 /* str1=position str2=last_position str3=file */
2118 int position, last_position;
2119 bool queue;
2121 if (!str1 || !str2 || !str3)
2123 result = -1;
2124 exit_loop = true;
2125 break;
2128 position = atoi(str1);
2129 last_position = atoi(str2);
2131 queue = (current_command == PLAYLIST_COMMAND_ADD)?
2132 false:true;
2134 /* seek position is based on str3's position in
2135 buffer */
2136 if (add_track_to_playlist(playlist, str3, position,
2137 queue, total_read+(str3-buffer)) < 0)
2138 return -1;
2140 playlist->last_insert_pos = last_position;
2142 break;
2144 case PLAYLIST_COMMAND_DELETE:
2146 /* str1=position */
2147 int position;
2149 if (!str1)
2151 result = -1;
2152 exit_loop = true;
2153 break;
2156 position = atoi(str1);
2158 if (remove_track_from_playlist(playlist, position,
2159 false) < 0)
2160 return -1;
2162 break;
2164 case PLAYLIST_COMMAND_SHUFFLE:
2166 /* str1=seed str2=first_index */
2167 int seed;
2169 if (!str1 || !str2)
2171 result = -1;
2172 exit_loop = true;
2173 break;
2176 if (!sorted)
2178 /* Always sort list before shuffling */
2179 sort_playlist(playlist, false, false);
2182 seed = atoi(str1);
2183 playlist->first_index = atoi(str2);
2185 if (randomise_playlist(playlist, seed, false,
2186 false) < 0)
2187 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 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_INVALID));
2317 return result;
2320 if (useraborted)
2322 splash(HZ*2, ID2P(LANG_CANCEL));
2323 return -1;
2325 if (!newline || (exit_loop && count<nread))
2327 if ((total_read + count) >= control_file_size)
2329 /* no newline at end of control file */
2330 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_INVALID));
2331 return -1;
2334 /* We didn't end on a newline or we exited loop prematurely.
2335 Either way, re-read the remainder. */
2336 count = last_newline;
2337 lseek(playlist->control_fd, total_read+count, SEEK_SET);
2340 total_read += count;
2342 if (first)
2343 /* still looking for header */
2344 nread = read(playlist->control_fd, buffer,
2345 PLAYLIST_COMMAND_SIZE<buflen?PLAYLIST_COMMAND_SIZE:buflen);
2346 else
2347 nread = read(playlist->control_fd, buffer, buflen);
2349 /* Terminate on EOF */
2350 if(nread <= 0)
2352 break;
2356 #ifdef HAVE_DIRCACHE
2357 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
2358 #endif
2360 return 0;
2364 * Add track to in_ram playlist. Used when playing directories.
2366 int playlist_add(const char *filename)
2368 struct playlist_info* playlist = &current_playlist;
2369 int len = strlen(filename);
2371 if((len+1 > playlist->buffer_size - playlist->buffer_end_pos) ||
2372 (playlist->amount >= playlist->max_playlist_size))
2374 display_buffer_full();
2375 return -1;
2378 playlist->indices[playlist->amount] = playlist->buffer_end_pos;
2379 #ifdef HAVE_DIRCACHE
2380 playlist->filenames[playlist->amount] = NULL;
2381 #endif
2382 playlist->amount++;
2384 strcpy(&playlist->buffer[playlist->buffer_end_pos], filename);
2385 playlist->buffer_end_pos += len;
2386 playlist->buffer[playlist->buffer_end_pos++] = '\0';
2388 return 0;
2391 /* shuffle newly created playlist using random seed. */
2392 int playlist_shuffle(int random_seed, int start_index)
2394 struct playlist_info* playlist = &current_playlist;
2396 bool start_current = false;
2398 if (start_index >= 0 && global_settings.play_selected)
2400 /* store the seek position before the shuffle */
2401 playlist->index = playlist->first_index = start_index;
2402 start_current = true;
2405 randomise_playlist(playlist, random_seed, start_current, true);
2407 return playlist->index;
2410 /* start playing current playlist at specified index/offset */
2411 void playlist_start(int start_index, int offset)
2413 struct playlist_info* playlist = &current_playlist;
2415 /* Cancel FM radio selection as previous music. For cases where we start
2416 playback without going to the WPS, such as playlist insert.. or
2417 playlist catalog. */
2418 previous_music_is_wps();
2420 playlist->index = start_index;
2422 playlist->started = true;
2423 sync_control(playlist, false);
2424 audio_play(offset);
2427 /* Returns false if 'steps' is out of bounds, else true */
2428 bool playlist_check(int steps)
2430 struct playlist_info* playlist = &current_playlist;
2432 /* always allow folder navigation */
2433 if (global_settings.next_folder && playlist->in_ram)
2434 return true;
2436 int index = get_next_index(playlist, steps, -1);
2438 if (index < 0 && steps >= 0 && global_settings.repeat_mode == REPEAT_SHUFFLE)
2439 index = get_next_index(playlist, steps, REPEAT_ALL);
2441 return (index >= 0);
2444 /* get trackname of track that is "steps" away from current playing track.
2445 NULL is used to identify end of playlist */
2446 const char* playlist_peek(int steps, char* buf, size_t buf_size)
2448 struct playlist_info* playlist = &current_playlist;
2449 int seek;
2450 char *temp_ptr;
2451 int index;
2452 bool control_file;
2454 index = get_next_index(playlist, steps, -1);
2455 if (index < 0)
2456 return NULL;
2458 #if CONFIG_CODEC == SWCODEC
2459 /* Just testing - don't care about the file name */
2460 if (!buf || !buf_size)
2461 return "";
2462 #endif
2464 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
2465 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
2467 if (get_filename(playlist, index, seek, control_file, buf,
2468 buf_size) < 0)
2469 return NULL;
2471 temp_ptr = buf;
2473 if (!playlist->in_ram || control_file)
2475 /* remove bogus dirs from beginning of path
2476 (workaround for buggy playlist creation tools) */
2477 while (temp_ptr)
2479 if (file_exists(temp_ptr))
2480 break;
2482 temp_ptr = strchr(temp_ptr+1, '/');
2485 if (!temp_ptr)
2487 /* Even though this is an invalid file, we still need to pass a
2488 file name to the caller because NULL is used to indicate end
2489 of playlist */
2490 return buf;
2494 return temp_ptr;
2498 * Update indices as track has changed
2500 int playlist_next(int steps)
2502 struct playlist_info* playlist = &current_playlist;
2503 int index;
2505 if ( (steps > 0)
2506 #ifdef AB_REPEAT_ENABLE
2507 && (global_settings.repeat_mode != REPEAT_AB)
2508 #endif
2509 && (global_settings.repeat_mode != REPEAT_ONE) )
2511 int i, j;
2513 /* We need to delete all the queued songs */
2514 for (i=0, j=steps; i<j; i++)
2516 index = get_next_index(playlist, i, -1);
2518 if (playlist->indices[index] & PLAYLIST_QUEUE_MASK)
2520 remove_track_from_playlist(playlist, index, true);
2521 steps--; /* one less track */
2526 index = get_next_index(playlist, steps, -1);
2528 if (index < 0)
2530 /* end of playlist... or is it */
2531 if (global_settings.repeat_mode == REPEAT_SHUFFLE &&
2532 playlist->amount > 1)
2534 /* Repeat shuffle mode. Re-shuffle playlist and resume play */
2535 playlist->first_index = 0;
2536 sort_playlist(playlist, false, false);
2537 randomise_playlist(playlist, current_tick, false, true);
2539 #if CONFIG_CODEC == SWCODEC
2540 playlist->started = true;
2541 #else
2542 playlist_start(0, 0);
2543 #endif
2544 playlist->index = 0;
2545 index = 0;
2547 else if (playlist->in_ram && global_settings.next_folder)
2549 index = create_and_play_dir(steps, true);
2551 if (index >= 0)
2553 playlist->index = index;
2557 return index;
2560 playlist->index = index;
2562 if (playlist->last_insert_pos >= 0 && steps > 0)
2564 /* check to see if we've gone beyond the last inserted track */
2565 int cur = rotate_index(playlist, index);
2566 int last_pos = rotate_index(playlist, playlist->last_insert_pos);
2568 if (cur > last_pos)
2570 /* reset last inserted track */
2571 playlist->last_insert_pos = -1;
2573 if (playlist->control_fd >= 0)
2575 int result = update_control(playlist, PLAYLIST_COMMAND_RESET,
2576 -1, -1, NULL, NULL, NULL);
2578 if (result < 0)
2579 return result;
2581 sync_control(playlist, false);
2586 return index;
2589 /* try playing next or previous folder */
2590 bool playlist_next_dir(int direction)
2592 /* not to mess up real playlists */
2593 if(!current_playlist.in_ram)
2594 return false;
2596 return create_and_play_dir(direction, false) >= 0;
2599 /* Get resume info for current playing song. If return value is -1 then
2600 settings shouldn't be saved. */
2601 int playlist_get_resume_info(int *resume_index)
2603 struct playlist_info* playlist = &current_playlist;
2605 *resume_index = playlist->index;
2607 return 0;
2610 /* Update resume info for current playing song. Returns -1 on error. */
2611 int playlist_update_resume_info(const struct mp3entry* id3)
2613 struct playlist_info* playlist = &current_playlist;
2615 if (id3)
2617 if (global_status.resume_index != playlist->index ||
2618 global_status.resume_offset != id3->offset)
2620 global_status.resume_index = playlist->index;
2621 global_status.resume_offset = id3->offset;
2622 status_save();
2625 else
2627 global_status.resume_index = -1;
2628 global_status.resume_offset = -1;
2629 status_save();
2632 return 0;
2635 /* Returns index of current playing track for display purposes. This value
2636 should not be used for resume purposes as it doesn't represent the actual
2637 index into the playlist */
2638 int playlist_get_display_index(void)
2640 struct playlist_info* playlist = &current_playlist;
2642 /* first_index should always be index 0 for display purposes */
2643 int index = rotate_index(playlist, playlist->index);
2645 return (index+1);
2648 /* returns number of tracks in current playlist */
2649 int playlist_amount(void)
2651 return playlist_amount_ex(NULL);
2653 /* set playlist->last_shuffle_start to playlist->amount for
2654 PLAYLIST_INSERT_LAST_SHUFFLED command purposes*/
2655 void playlist_set_last_shuffled_start(void)
2657 struct playlist_info* playlist = &current_playlist;
2658 playlist->last_shuffled_start = playlist->amount;
2661 * Create a new playlist If playlist is not NULL then we're loading a
2662 * playlist off disk for viewing/editing. The index_buffer is used to store
2663 * playlist indices (required for and only used if !current playlist). The
2664 * temp_buffer (if not NULL) is used as a scratchpad when loading indices.
2666 int playlist_create_ex(struct playlist_info* playlist,
2667 const char* dir, const char* file,
2668 void* index_buffer, int index_buffer_size,
2669 void* temp_buffer, int temp_buffer_size)
2671 if (!playlist)
2672 playlist = &current_playlist;
2673 else
2675 /* Initialize playlist structure */
2676 int r = rand() % 10;
2677 playlist->current = false;
2679 /* Use random name for control file */
2680 snprintf(playlist->control_filename, sizeof(playlist->control_filename),
2681 "%s.%d", PLAYLIST_CONTROL_FILE, r);
2682 playlist->fd = -1;
2683 playlist->control_fd = -1;
2685 if (index_buffer)
2687 int num_indices = index_buffer_size / sizeof(int);
2689 #ifdef HAVE_DIRCACHE
2690 num_indices /= 2;
2691 #endif
2692 if (num_indices > global_settings.max_files_in_playlist)
2693 num_indices = global_settings.max_files_in_playlist;
2695 playlist->max_playlist_size = num_indices;
2696 playlist->indices = index_buffer;
2697 #ifdef HAVE_DIRCACHE
2698 playlist->filenames = (const struct dircache_entry **)
2699 &playlist->indices[num_indices];
2700 #endif
2702 else
2704 playlist->max_playlist_size = current_playlist.max_playlist_size;
2705 playlist->indices = current_playlist.indices;
2706 #ifdef HAVE_DIRCACHE
2707 playlist->filenames = current_playlist.filenames;
2708 #endif
2711 playlist->buffer_size = 0;
2712 playlist->buffer = NULL;
2713 playlist->control_mutex = &created_playlist_mutex;
2716 new_playlist(playlist, dir, file);
2718 if (file)
2719 /* load the playlist file */
2720 add_indices_to_playlist(playlist, temp_buffer, temp_buffer_size);
2722 return 0;
2726 * Set the specified playlist as the current.
2727 * NOTE: You will get undefined behaviour if something is already playing so
2728 * remember to stop before calling this. Also, this call will
2729 * effectively close your playlist, making it unusable.
2731 int playlist_set_current(struct playlist_info* playlist)
2733 if (!playlist || (check_control(playlist) < 0))
2734 return -1;
2736 empty_playlist(&current_playlist, false);
2738 strlcpy(current_playlist.filename, playlist->filename,
2739 sizeof(current_playlist.filename));
2741 current_playlist.utf8 = playlist->utf8;
2742 current_playlist.fd = playlist->fd;
2744 close(playlist->control_fd);
2745 close(current_playlist.control_fd);
2746 remove(current_playlist.control_filename);
2747 if (rename(playlist->control_filename,
2748 current_playlist.control_filename) < 0)
2749 return -1;
2750 current_playlist.control_fd = open(current_playlist.control_filename,
2751 O_RDWR);
2752 if (current_playlist.control_fd < 0)
2753 return -1;
2754 current_playlist.control_created = true;
2756 current_playlist.dirlen = playlist->dirlen;
2758 if (playlist->indices && playlist->indices != current_playlist.indices)
2760 memcpy(current_playlist.indices, playlist->indices,
2761 playlist->max_playlist_size*sizeof(int));
2762 #ifdef HAVE_DIRCACHE
2763 memcpy(current_playlist.filenames, playlist->filenames,
2764 playlist->max_playlist_size*sizeof(int));
2765 #endif
2768 current_playlist.first_index = playlist->first_index;
2769 current_playlist.amount = playlist->amount;
2770 current_playlist.last_insert_pos = playlist->last_insert_pos;
2771 current_playlist.seed = playlist->seed;
2772 current_playlist.shuffle_modified = playlist->shuffle_modified;
2773 current_playlist.deleted = playlist->deleted;
2774 current_playlist.num_inserted_tracks = playlist->num_inserted_tracks;
2776 memcpy(current_playlist.control_cache, playlist->control_cache,
2777 sizeof(current_playlist.control_cache));
2778 current_playlist.num_cached = playlist->num_cached;
2779 current_playlist.pending_control_sync = playlist->pending_control_sync;
2781 return 0;
2783 struct playlist_info *playlist_get_current(void)
2785 return &current_playlist;
2788 * Close files and delete control file for non-current playlist.
2790 void playlist_close(struct playlist_info* playlist)
2792 if (!playlist)
2793 return;
2795 if (playlist->fd >= 0)
2796 close(playlist->fd);
2798 if (playlist->control_fd >= 0)
2799 close(playlist->control_fd);
2801 if (playlist->control_created)
2802 remove(playlist->control_filename);
2805 void playlist_sync(struct playlist_info* playlist)
2807 if (!playlist)
2808 playlist = &current_playlist;
2810 sync_control(playlist, false);
2811 if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
2812 audio_flush_and_reload_tracks();
2814 #ifdef HAVE_DIRCACHE
2815 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
2816 #endif
2820 * Insert track into playlist at specified position (or one of the special
2821 * positions). Returns position where track was inserted or -1 if error.
2823 int playlist_insert_track(struct playlist_info* playlist, const char *filename,
2824 int position, bool queue, bool sync)
2826 int result;
2828 if (!playlist)
2829 playlist = &current_playlist;
2831 if (check_control(playlist) < 0)
2833 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2834 return -1;
2837 result = add_track_to_playlist(playlist, filename, position, queue, -1);
2839 /* Check if we want manually sync later. For example when adding
2840 * bunch of files from tagcache, syncing after every file wouldn't be
2841 * a good thing to do. */
2842 if (sync && result >= 0)
2843 playlist_sync(playlist);
2845 return result;
2849 * Insert all tracks from specified directory into playlist.
2851 int playlist_insert_directory(struct playlist_info* playlist,
2852 const char *dirname, int position, bool queue,
2853 bool recurse)
2855 int result;
2856 unsigned char *count_str;
2857 struct directory_search_context context;
2859 if (!playlist)
2860 playlist = &current_playlist;
2862 if (check_control(playlist) < 0)
2864 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2865 return -1;
2868 if (position == PLAYLIST_REPLACE)
2870 if (playlist_remove_all_tracks(playlist) == 0)
2871 position = PLAYLIST_INSERT_LAST;
2872 else
2873 return -1;
2876 if (queue)
2877 count_str = ID2P(LANG_PLAYLIST_QUEUE_COUNT);
2878 else
2879 count_str = ID2P(LANG_PLAYLIST_INSERT_COUNT);
2881 display_playlist_count(0, count_str, false);
2883 context.playlist = playlist;
2884 context.position = position;
2885 context.queue = queue;
2886 context.count = 0;
2888 cpu_boost(true);
2890 result = playlist_directory_tracksearch(dirname, recurse,
2891 directory_search_callback, &context);
2893 sync_control(playlist, false);
2895 cpu_boost(false);
2897 display_playlist_count(context.count, count_str, true);
2899 if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
2900 audio_flush_and_reload_tracks();
2902 #ifdef HAVE_DIRCACHE
2903 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
2904 #endif
2906 return result;
2910 * Insert all tracks from specified playlist into dynamic playlist.
2912 int playlist_insert_playlist(struct playlist_info* playlist, const char *filename,
2913 int position, bool queue)
2915 int fd;
2916 int max;
2917 char *temp_ptr;
2918 const char *dir;
2919 unsigned char *count_str;
2920 char temp_buf[MAX_PATH+1];
2921 char trackname[MAX_PATH+1];
2922 int count = 0;
2923 int result = 0;
2924 bool utf8 = is_m3u8(filename);
2926 if (!playlist)
2927 playlist = &current_playlist;
2929 if (check_control(playlist) < 0)
2931 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
2932 return -1;
2935 fd = open_utf8(filename, O_RDONLY);
2936 if (fd < 0)
2938 splash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
2939 return -1;
2942 /* we need the directory name for formatting purposes */
2943 dir = filename;
2945 temp_ptr = strrchr(filename+1,'/');
2946 if (temp_ptr)
2947 *temp_ptr = 0;
2948 else
2949 dir = "/";
2951 if (queue)
2952 count_str = ID2P(LANG_PLAYLIST_QUEUE_COUNT);
2953 else
2954 count_str = ID2P(LANG_PLAYLIST_INSERT_COUNT);
2956 display_playlist_count(count, count_str, false);
2958 if (position == PLAYLIST_REPLACE)
2960 if (playlist_remove_all_tracks(playlist) == 0)
2961 position = PLAYLIST_INSERT_LAST;
2962 else return -1;
2965 cpu_boost(true);
2967 while ((max = read_line(fd, temp_buf, sizeof(temp_buf))) > 0)
2969 /* user abort */
2970 if (action_userabort(TIMEOUT_NOBLOCK))
2971 break;
2973 if (temp_buf[0] != '#' && temp_buf[0] != '\0')
2975 int insert_pos;
2977 if (!utf8)
2979 /* Use trackname as a temporay buffer. Note that trackname must
2980 * be as large as temp_buf.
2982 max = convert_m3u(temp_buf, max, sizeof(temp_buf), trackname);
2985 /* we need to format so that relative paths are correctly
2986 handled */
2987 if (format_track_path(trackname, temp_buf, sizeof(trackname), max,
2988 dir) < 0)
2990 result = -1;
2991 break;
2994 insert_pos = add_track_to_playlist(playlist, trackname, position,
2995 queue, -1);
2997 if (insert_pos < 0)
2999 result = -1;
3000 break;
3003 /* Make sure tracks are inserted in correct order if user
3004 requests INSERT_FIRST */
3005 if (position == PLAYLIST_INSERT_FIRST || position >= 0)
3006 position = insert_pos + 1;
3008 count++;
3010 if ((count%PLAYLIST_DISPLAY_COUNT) == 0)
3012 display_playlist_count(count, count_str, false);
3014 if (count == PLAYLIST_DISPLAY_COUNT &&
3015 (audio_status() & AUDIO_STATUS_PLAY) &&
3016 playlist->started)
3017 audio_flush_and_reload_tracks();
3021 /* let the other threads work */
3022 yield();
3025 close(fd);
3027 if (temp_ptr)
3028 *temp_ptr = '/';
3030 sync_control(playlist, false);
3032 cpu_boost(false);
3034 display_playlist_count(count, count_str, true);
3036 if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
3037 audio_flush_and_reload_tracks();
3039 #ifdef HAVE_DIRCACHE
3040 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
3041 #endif
3043 return result;
3047 * Delete track at specified index. If index is PLAYLIST_DELETE_CURRENT then
3048 * we want to delete the current playing track.
3050 int playlist_delete(struct playlist_info* playlist, int index)
3052 int result = 0;
3054 if (!playlist)
3055 playlist = &current_playlist;
3057 if (check_control(playlist) < 0)
3059 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
3060 return -1;
3063 if (index == PLAYLIST_DELETE_CURRENT)
3064 index = playlist->index;
3066 result = remove_track_from_playlist(playlist, index, true);
3068 if (result != -1 && (audio_status() & AUDIO_STATUS_PLAY) &&
3069 playlist->started)
3070 audio_flush_and_reload_tracks();
3072 return result;
3076 * Move track at index to new_index. Tracks between the two are shifted
3077 * appropriately. Returns 0 on success and -1 on failure.
3079 int playlist_move(struct playlist_info* playlist, int index, int new_index)
3081 int result;
3082 int seek;
3083 bool control_file;
3084 bool queue;
3085 bool current = false;
3086 int r;
3087 char filename[MAX_PATH];
3089 if (!playlist)
3090 playlist = &current_playlist;
3092 if (check_control(playlist) < 0)
3094 splash(HZ*2, ID2P(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
3095 return -1;
3098 if (index == new_index)
3099 return -1;
3101 if (index == playlist->index)
3102 /* Moving the current track */
3103 current = true;
3105 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
3106 queue = playlist->indices[index] & PLAYLIST_QUEUE_MASK;
3107 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
3109 if (get_filename(playlist, index, seek, control_file, filename,
3110 sizeof(filename)) < 0)
3111 return -1;
3113 /* We want to insert the track at the position that was specified by
3114 new_index. This may be different then new_index because of the
3115 shifting that will occur after the delete.
3116 We calculate this before we do the remove as it depends on the
3117 size of the playlist before the track removal */
3118 r = rotate_index(playlist, new_index);
3120 /* Delete track from original position */
3121 result = remove_track_from_playlist(playlist, index, true);
3123 if (result != -1)
3125 if (r == 0)
3126 /* First index */
3127 new_index = PLAYLIST_PREPEND;
3128 else if (r == playlist->amount)
3129 /* Append */
3130 new_index = PLAYLIST_INSERT_LAST;
3131 else
3132 /* Calculate index of desired position */
3133 new_index = (r+playlist->first_index)%playlist->amount;
3135 result = add_track_to_playlist(playlist, filename, new_index, queue,
3136 -1);
3138 if (result != -1)
3140 if (current)
3142 /* Moved the current track */
3143 switch (new_index)
3145 case PLAYLIST_PREPEND:
3146 playlist->index = playlist->first_index;
3147 break;
3148 case PLAYLIST_INSERT_LAST:
3149 playlist->index = playlist->first_index - 1;
3150 if (playlist->index < 0)
3151 playlist->index += playlist->amount;
3152 break;
3153 default:
3154 playlist->index = new_index;
3155 break;
3159 if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
3160 audio_flush_and_reload_tracks();
3164 #ifdef HAVE_DIRCACHE
3165 queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
3166 #endif
3168 return result;
3171 /* shuffle currently playing playlist */
3172 int playlist_randomise(struct playlist_info* playlist, unsigned int seed,
3173 bool start_current)
3175 int result;
3177 if (!playlist)
3178 playlist = &current_playlist;
3180 check_control(playlist);
3182 result = randomise_playlist(playlist, seed, start_current, true);
3184 if (result != -1 && (audio_status() & AUDIO_STATUS_PLAY) &&
3185 playlist->started)
3186 audio_flush_and_reload_tracks();
3188 return result;
3191 /* sort currently playing playlist */
3192 int playlist_sort(struct playlist_info* playlist, bool start_current)
3194 int result;
3196 if (!playlist)
3197 playlist = &current_playlist;
3199 check_control(playlist);
3201 result = sort_playlist(playlist, start_current, true);
3203 if (result != -1 && (audio_status() & AUDIO_STATUS_PLAY) &&
3204 playlist->started)
3205 audio_flush_and_reload_tracks();
3207 return result;
3210 /* returns true if playlist has been modified */
3211 bool playlist_modified(const struct playlist_info* playlist)
3213 if (!playlist)
3214 playlist = &current_playlist;
3216 if (playlist->shuffle_modified ||
3217 playlist->deleted ||
3218 playlist->num_inserted_tracks > 0)
3219 return true;
3221 return false;
3224 /* returns index of first track in playlist */
3225 int playlist_get_first_index(const struct playlist_info* playlist)
3227 if (!playlist)
3228 playlist = &current_playlist;
3230 return playlist->first_index;
3233 /* returns shuffle seed of playlist */
3234 int playlist_get_seed(const struct playlist_info* playlist)
3236 if (!playlist)
3237 playlist = &current_playlist;
3239 return playlist->seed;
3242 /* returns number of tracks in playlist (includes queued/inserted tracks) */
3243 int playlist_amount_ex(const struct playlist_info* playlist)
3245 if (!playlist)
3246 playlist = &current_playlist;
3248 return playlist->amount;
3251 /* returns full path of playlist (minus extension) */
3252 char *playlist_name(const struct playlist_info* playlist, char *buf,
3253 int buf_size)
3255 char *sep;
3257 if (!playlist)
3258 playlist = &current_playlist;
3260 strlcpy(buf, playlist->filename+playlist->dirlen, buf_size);
3262 if (!buf[0])
3263 return NULL;
3265 /* Remove extension */
3266 sep = strrchr(buf, '.');
3267 if (sep)
3268 *sep = 0;
3270 return buf;
3273 /* returns the playlist filename */
3274 char *playlist_get_name(const struct playlist_info* playlist, char *buf,
3275 int buf_size)
3277 if (!playlist)
3278 playlist = &current_playlist;
3280 strlcpy(buf, playlist->filename, buf_size);
3282 if (!buf[0])
3283 return NULL;
3285 return buf;
3288 /* Fills info structure with information about track at specified index.
3289 Returns 0 on success and -1 on failure */
3290 int playlist_get_track_info(struct playlist_info* playlist, int index,
3291 struct playlist_track_info* info)
3293 int seek;
3294 bool control_file;
3296 if (!playlist)
3297 playlist = &current_playlist;
3299 if (index < 0 || index >= playlist->amount)
3300 return -1;
3302 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
3303 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
3305 if (get_filename(playlist, index, seek, control_file, info->filename,
3306 sizeof(info->filename)) < 0)
3307 return -1;
3309 info->attr = 0;
3311 if (control_file)
3313 if (playlist->indices[index] & PLAYLIST_QUEUE_MASK)
3314 info->attr |= PLAYLIST_ATTR_QUEUED;
3315 else
3316 info->attr |= PLAYLIST_ATTR_INSERTED;
3320 if (playlist->indices[index] & PLAYLIST_SKIPPED)
3321 info->attr |= PLAYLIST_ATTR_SKIPPED;
3323 info->index = index;
3324 info->display_index = rotate_index(playlist, index) + 1;
3326 return 0;
3329 /* save the current dynamic playlist to specified file */
3330 int playlist_save(struct playlist_info* playlist, char *filename)
3332 int fd;
3333 int i, index;
3334 int count = 0;
3335 char path[MAX_PATH+1];
3336 char tmp_buf[MAX_PATH+1];
3337 int result = 0;
3338 bool overwrite_current = false;
3339 int* index_buf = NULL;
3341 if (!playlist)
3342 playlist = &current_playlist;
3344 if (playlist->amount <= 0)
3345 return -1;
3347 /* use current working directory as base for pathname */
3348 if (format_track_path(path, filename, sizeof(tmp_buf),
3349 strlen(filename)+1, getcwd(NULL, -1)) < 0)
3350 return -1;
3352 if (!strncmp(playlist->filename, path, strlen(path)))
3354 /* Attempting to overwrite current playlist file.*/
3356 if (playlist->buffer_size < (int)(playlist->amount * sizeof(int)))
3358 /* not enough buffer space to store updated indices */
3359 splash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
3360 return -1;
3363 /* in_ram buffer is unused for m3u files so we'll use for storing
3364 updated indices */
3365 index_buf = (int*)playlist->buffer;
3367 /* use temporary pathname */
3368 snprintf(path, sizeof(path), "%s_temp", playlist->filename);
3369 overwrite_current = true;
3372 if (is_m3u8(path))
3374 fd = open_utf8(path, O_CREAT|O_WRONLY|O_TRUNC);
3376 else
3378 /* some applications require a BOM to read the file properly */
3379 fd = open(path, O_CREAT|O_WRONLY|O_TRUNC, 0666);
3381 if (fd < 0)
3383 splash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
3384 return -1;
3387 display_playlist_count(count, ID2P(LANG_PLAYLIST_SAVE_COUNT), false);
3389 cpu_boost(true);
3391 index = playlist->first_index;
3392 for (i=0; i<playlist->amount; i++)
3394 bool control_file;
3395 bool queue;
3396 int seek;
3398 /* user abort */
3399 if (action_userabort(TIMEOUT_NOBLOCK))
3401 result = -1;
3402 break;
3405 control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
3406 queue = playlist->indices[index] & PLAYLIST_QUEUE_MASK;
3407 seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;
3409 /* Don't save queued files */
3410 if (!queue)
3412 if (get_filename(playlist, index, seek, control_file, tmp_buf,
3413 MAX_PATH+1) < 0)
3415 result = -1;
3416 break;
3419 if (overwrite_current)
3420 index_buf[count] = lseek(fd, 0, SEEK_CUR);
3422 if (fdprintf(fd, "%s\n", tmp_buf) < 0)
3424 splash(HZ*2, ID2P(LANG_PLAYLIST_ACCESS_ERROR));
3425 result = -1;
3426 break;
3429 count++;
3431 if ((count % PLAYLIST_DISPLAY_COUNT) == 0)
3432 display_playlist_count(count, ID2P(LANG_PLAYLIST_SAVE_COUNT),
3433 false);
3435 yield();
3438 index = (index+1)%playlist->amount;
3441 display_playlist_count(count, ID2P(LANG_PLAYLIST_SAVE_COUNT), true);
3443 close(fd);
3445 if (overwrite_current && result >= 0)
3447 result = -1;
3449 mutex_lock(playlist->control_mutex);
3451 /* Replace the current playlist with the new one and update indices */
3452 close(playlist->fd);
3453 if (remove(playlist->filename) >= 0)
3455 if (rename(path, playlist->filename) >= 0)
3457 playlist->fd = open_utf8(playlist->filename, O_RDONLY);
3458 if (playlist->fd >= 0)
3460 index = playlist->first_index;
3461 for (i=0, count=0; i<playlist->amount; i++)
3463 if (!(playlist->indices[index] & PLAYLIST_QUEUE_MASK))
3465 playlist->indices[index] = index_buf[count];
3466 count++;
3468 index = (index+1)%playlist->amount;
3471 /* we need to recreate control because inserted tracks are
3472 now part of the playlist and shuffle has been
3473 invalidated */
3474 result = recreate_control(playlist);
3479 mutex_unlock(playlist->control_mutex);
3483 cpu_boost(false);
3485 return result;
3489 * Search specified directory for tracks and notify via callback. May be
3490 * called recursively.
3492 int playlist_directory_tracksearch(const char* dirname, bool recurse,
3493 int (*callback)(char*, void*),
3494 void* context)
3496 char buf[MAX_PATH+1];
3497 int result = 0;
3498 int num_files = 0;
3499 int i;
3500 struct entry *files;
3501 struct tree_context* tc = tree_get_context();
3502 int old_dirfilter = *(tc->dirfilter);
3504 if (!callback)
3505 return -1;
3507 /* use the tree browser dircache to load files */
3508 *(tc->dirfilter) = SHOW_ALL;
3510 if (ft_load(tc, dirname) < 0)
3512 splash(HZ*2, ID2P(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));
3513 *(tc->dirfilter) = old_dirfilter;
3514 return -1;
3517 files = (struct entry*) tc->dircache;
3518 num_files = tc->filesindir;
3520 /* we've overwritten the dircache so tree browser will need to be
3521 reloaded */
3522 reload_directory();
3524 for (i=0; i<num_files; i++)
3526 /* user abort */
3527 if (action_userabort(TIMEOUT_NOBLOCK))
3529 result = -1;
3530 break;
3533 if (files[i].attr & ATTR_DIRECTORY)
3535 if (recurse)
3537 /* recursively add directories */
3538 snprintf(buf, sizeof(buf), "%s/%s",
3539 dirname[1]? dirname: "", files[i].name);
3540 result = playlist_directory_tracksearch(buf, recurse,
3541 callback, context);
3542 if (result < 0)
3543 break;
3545 /* we now need to reload our current directory */
3546 if(ft_load(tc, dirname) < 0)
3548 result = -1;
3549 break;
3552 files = (struct entry*) tc->dircache;
3553 num_files = tc->filesindir;
3554 if (!num_files)
3556 result = -1;
3557 break;
3560 else
3561 continue;
3563 else if ((files[i].attr & FILE_ATTR_MASK) == FILE_ATTR_AUDIO)
3565 snprintf(buf, sizeof(buf), "%s/%s",
3566 dirname[1]? dirname: "", files[i].name);
3568 if (callback(buf, context) != 0)
3570 result = -1;
3571 break;
3574 /* let the other threads work */
3575 yield();
3579 /* restore dirfilter */
3580 *(tc->dirfilter) = old_dirfilter;
3582 return result;