aboutsummaryrefslogtreecommitdiff
path: root/src/github/daneren2005/dsub/util/ShufflePlayBuffer.java
blob: b92945c4fc0723ccc8fab1ee2af45f394dc46c5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/*
 This file is part of Subsonic.

 Subsonic is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 Subsonic is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with Subsonic.  If not, see <http://www.gnu.org/licenses/>.

 Copyright 2009 (C) Sindre Mehus
 */
package github.daneren2005.dsub.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import github.daneren2005.dsub.domain.MusicDirectory;
import github.daneren2005.dsub.service.MusicService;
import github.daneren2005.dsub.service.MusicServiceFactory;
import github.daneren2005.dsub.util.FileUtil;

/**
 * @author Sindre Mehus
 * @version $Id$
 */
public class ShufflePlayBuffer {

    private static final String TAG = ShufflePlayBuffer.class.getSimpleName();
    private static final String CACHE_FILENAME = "shuffleBuffer.ser";
    private static final int CAPACITY = 50;
    private static final int REFILL_THRESHOLD = 40;

    private final ScheduledExecutorService executorService;
	private boolean firstRun = true;
    private final ArrayList<MusicDirectory.Entry> buffer = new ArrayList<MusicDirectory.Entry>();
	private int lastCount = -1;
    private Context context;
    private int currentServer;
	private String currentFolder = "";
	
	private String genre = "";
	private String startYear = "";
	private String endYear = "";

    public ShufflePlayBuffer(Context context) {
        this.context = context;
        
        executorService = Executors.newSingleThreadScheduledExecutor();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
				refill();
			}
        };
        executorService.scheduleWithFixedDelay(runnable, 1, 10, TimeUnit.SECONDS);
    }

    public List<MusicDirectory.Entry> get(int size) {
        clearBufferIfnecessary();

        List<MusicDirectory.Entry> result = new ArrayList<MusicDirectory.Entry>(size);
        synchronized (buffer) {
        	boolean removed = false;
            while (!buffer.isEmpty() && result.size() < size) {
                result.add(buffer.remove(buffer.size() - 1));
                removed = true;
            }
            
            // Re-cache if anything is taken out
            if(removed) {
				FileUtil.serialize(context, buffer, CACHE_FILENAME);
            }
        }
        Log.i(TAG, "Taking " + result.size() + " songs from shuffle play buffer. " + buffer.size() + " remaining.");
        return result;
    }

    public void shutdown() {
        executorService.shutdown();
    }

    private void refill() {

        // Check if active server has changed.
        clearBufferIfnecessary();

        if (buffer != null && (buffer.size() > REFILL_THRESHOLD || (!Util.isNetworkConnected(context) && !Util.isOffline(context)) || lastCount == 0)) {
            return;
        }

        try {
            MusicService service = MusicServiceFactory.getMusicService(context);
            int n = CAPACITY - buffer.size();
			String folder = Util.getSelectedMusicFolderId(context);
            MusicDirectory songs = service.getRandomSongs(n, folder, genre, startYear, endYear, context, null);

            synchronized (buffer) {
                buffer.addAll(songs.getChildren());
                Log.i(TAG, "Refilled shuffle play buffer with " + songs.getChildrenSize() + " songs.");
				lastCount = songs.getChildrenSize();
				
				// Cache buffer
				FileUtil.serialize(context, buffer, CACHE_FILENAME);
            }
        } catch (Exception x) {
            Log.w(TAG, "Failed to refill shuffle play buffer.", x);
        }
    }

    private void clearBufferIfnecessary() {
        synchronized (buffer) {
			final SharedPreferences prefs = Util.getPreferences(context);
            if (currentServer != Util.getActiveServer(context)
				|| (currentFolder != null && !currentFolder.equals(Util.getSelectedMusicFolderId(context)))
				|| (genre != null && !genre.equals(prefs.getString(Constants.PREFERENCES_KEY_SHUFFLE_GENRE, "")))
				|| (startYear != null && !startYear.equals(prefs.getString(Constants.PREFERENCES_KEY_SHUFFLE_START_YEAR, "")))
				|| (endYear != null && !endYear.equals(prefs.getString(Constants.PREFERENCES_KEY_SHUFFLE_END_YEAR, "")))) {
				lastCount = -1;
                currentServer = Util.getActiveServer(context);
				currentFolder = Util.getSelectedMusicFolderId(context);
				genre = prefs.getString(Constants.PREFERENCES_KEY_SHUFFLE_GENRE, "");
				startYear = prefs.getString(Constants.PREFERENCES_KEY_SHUFFLE_START_YEAR, "");
				endYear = prefs.getString(Constants.PREFERENCES_KEY_SHUFFLE_END_YEAR, "");
                buffer.clear();

				if(firstRun) {
					ArrayList cacheList = FileUtil.deserialize(context, CACHE_FILENAME, ArrayList.class);
					if(cacheList != null) {
						buffer.addAll(cacheList);
					}
					firstRun = false;
				} else {
					// Clear cache
					File file = new File(context.getCacheDir(), CACHE_FILENAME);
					file.delete();
				}
            }
        }
    }
}