-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream_manager.js
240 lines (184 loc) · 8.02 KB
/
stream_manager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
var Storage = require('./storage.js'),
_ = require('underscore');
var StreamPlayback = (function() {
var MIN_PLAYBACK_TIME = 5 * 60 * 1000; // 5 minutes
function getPlaylistCycleData(playlist) {
var full_cycle_time = 0,
song_start_times = [];
for (var i = 0; i < playlist.length; i++) {
song_start_times.push(full_cycle_time);
full_cycle_time += playlist[i].duration * 1000;
}
return {
full_cycle_time: full_cycle_time,
song_start_times: song_start_times
};
}
function getSongIndexById(playlist, song_id) {
for (var i = 0; i < playlist.length; i++) {
if (playlist[i].aid == song_id) {
return i;
}
}
}
function getPlayingSongIndex(playlist, playdata, now) {
var current_cycle_playtime = (now - playdata.start_time) % playdata.full_cycle_time,
sorted_index = _.sortedIndex(playdata.song_start_times, current_cycle_playtime);
return sorted_index - 1;
}
function getCurrentCycleStartTime(playlist, playdata, now) {
var full_cycles = Math.floor( (now - playdata.start_time) / playdata.full_cycle_time );
return playdata.start_time + playdata.full_cycle_time * full_cycles;
}
return {
isPlaying: function(stream) {
return stream.playdata !== undefined;
},
startPlaying: function(stream, song_id, now) {
var song_index = getSongIndexById(stream.playlist, song_id);
if (song_index == undefined) {
// песни с таким id нет в плейлисте
console.log("Warning");
return;
}
// вычисляем параметры проигрывания
var playlist_cycle_data = getPlaylistCycleData(stream.playlist);
// вычисляем точку отсчета для плейлиста
var playlist_start_time = now - playlist_cycle_data.song_start_times[song_index];
stream.playdata = _.extend(playlist_cycle_data, {
start_time: playlist_start_time
});
},
stopPlaying: function(stream) {
if (this.isPlaying(stream)) {
delete stream.playdata;
}
},
updateActivePlaylist: function(stream, new_playlist, now) {
if (!this.isPlaying(stream)) {
console.log("Warning");
return;
}
// достаём песню, которая проигрывается в данный момент
var current_song_index = getPlayingSongIndex(stream.playlist, stream.playdata, now);
var current_song = stream.playlist[current_song_index];
// находим её в новом плейлисте
var new_song_index = getSongIndexById(new_playlist, current_song.aid);
if (new_song_index == undefined) {
/* если в новом плейлисте нет текущей песни - прекращаем проигрывание */
this.stopPlaying(stream);
return;
}
// вычисляем параметры проигрывания для нового плейлиста
var new_playlist_cycle_data = getPlaylistCycleData(new_playlist);
// время начала проигрывания текущей песни должно остаться прежним для нового плейлиста
var current_cycle_start_time = getCurrentCycleStartTime(stream.playlist, stream.playdata, now);
var song_start_time = current_cycle_start_time + stream.playdata.song_start_times[current_song_index];
var new_playlist_start_time = song_start_time - new_playlist_cycle_data.song_start_times[new_song_index];
// вносим изменения в stream
stream.playdata = _.extend(new_playlist_cycle_data, {
start_time: new_playlist_start_time
});
stream.playlist = new_playlist;
},
getPlayback: function(stream, now) {
if (!this.isPlaying(stream)) {
console.log("Warning");
return;
}
var songs = [];
var playing_song_index = getPlayingSongIndex(stream.playlist, stream.playdata, now),
current_cycle_start_time = getCurrentCycleStartTime(stream.playlist, stream.playdata, now);
var playing_song_start_time =
current_cycle_start_time +
stream.playdata.song_start_times[playing_song_index];
var total_playback_time = 0,
playing_song_offset = now - playing_song_start_time;
function need_more_songs() {
if (songs.length < 2) {
return true; // как минимум еще одна песня должна отсылаться для кэширования
}
if (total_playback_time - playing_song_offset < MIN_PLAYBACK_TIME) {
return true; // total playback time must be long enough
}
return false;
}
var song_start_time = playing_song_start_time,
song_index = playing_song_index;
while (need_more_songs()) {
var song = _.extend(
{
start_time: song_start_time
},
stream.playlist[song_index]);
song.stop_time = song_start_time + song.duration * 1000;
songs.push(song);
song_index = (song_index + 1) % stream.playlist.length;
total_playback_time += song.duration * 1000;
song_start_time += song.duration * 1000;
}
return { songs: songs, server_time: now };
}
};
})();
exports.streamPlayback = StreamPlayback;
exports.getPlaylist = function(stream_id, callback) {
Storage.getStream(stream_id, function(stream) {
if (stream) {
callback(stream.playlist);
} else {
callback([]);
}
});
}
exports.savePlaylist = function(stream_id, playlist, callback) {
var now = new Date().getTime();
Storage.getStream(stream_id, function(stream) {
if (stream) {
/* обновляем существующий стрим */
if (StreamPlayback.isPlaying(stream)) {
StreamPlayback.updateActivePlaylist(stream, playlist, now);
} else {
stream.playlist = playlist;
}
Storage.saveStream(stream_id, stream);
} else {
/* создаем новый стрим */
Storage.saveStream(stream_id, {
stream_id: stream_id,
playlist: playlist
});
}
callback();
});
};
exports.playSong = function(stream_id, song_id, callback) {
var now = new Date().getTime();
Storage.getStream(stream_id, function(stream) {
if (stream) {
StreamPlayback.startPlaying(stream, song_id, now);
Storage.saveStream(stream_id, stream);
}
callback();
});
};
exports.stopPlaying = function(stream_id, callback) {
Storage.getStream(stream_id, function(stream) {
if (stream) {
StreamPlayback.stopPlaying(stream);
Storage.saveStream(stream_id, stream);
}
callback();
});
};
exports.getPlayback = function(stream_id, callback) {
var now = new Date().getTime();
Storage.getStream(stream_id, function(stream) {
if (stream && StreamPlayback.isPlaying(stream)) {
var playback = StreamPlayback.getPlayback(stream, now);
callback(playback);
} else {
callback();
}
});
};