-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmediaplayer.js
257 lines (232 loc) · 7.7 KB
/
mediaplayer.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
const argv = require('yargs-parser')(process.argv);
const path = require('path');
const fs = require('fs');
const m3uParser = require('m3u8-parser');
//*=============Requires ffmpeg to run===================================================*\\
module.exports = function mediaPlayer(io,repeat,playlistUrl) {
const videoTypes = new Set(['.ogv', '.mp4']);
const audioTypes = new Set(['.mp3', '.flac', '.oga', '.wav']);
const ambiguousTypes = new Set(['.webm', '.ogg']); // These can be either audio or video
this.io = io;
this.mediaIndex = 0;
this.mediaTypes = [];
this.startTime = null;
this.elapsedTime = null;
this.filesProcessed = 0;
this.playlistCount = 0;
this.clientCount = 0;
function importM3U(file) {
const parser = new m3uParser.Parser();
let parsedFile = fs.readFileSync(file).toString();
parser.push(parsedFile);
parser.end();
return parser.manifest.segments;
}
this.processM3U = (file) => {
//check file duration
if (file.duration) {
//check for a file uri
if (file.uri) {
//get the name of the file which will be the title of the media
let name = path.parse(file.uri).name;
return {
duration:file.duration,
url: file.uri,
name: name,
};
}
console.warn(`Weird. Somehow one of your files in your playlist is missing a path`);
}
else {
if (file.uri) {
//get the name of the file which will be the title of the media
let name = path.parse(file.uri).name;
const shellCommand = 'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1';
const execute = require('child_process').execSync;
let duration = execute(`${shellCommand} "./public${file.uri}"`).toString();
//return an object with relevant information
return {
duration: parseFloat(duration),
url: file.uri,
name: name,
};
}
console.warn(`one of your files in your playlist ${file.uri} is missing a duration`);
}
};
//do something diff with m3u
if (argv.m3u) {
this.playlist = importM3U(argv.m3u).map(this.processM3U).filter(isValidMediaFile);
}
else {
this.playlist = fs.readdirSync('./public/media').filter(isValidMediaFile).map(function(file){
return '/media/'+file;
});
}
console.log("Loaded playlist:", this.playlist);
this.mediaLengths = new Array(this.playlist.length);
function isValidMediaFile (file) {
let validExtensions = new Set([...videoTypes, ...audioTypes, ...ambiguousTypes]);
let extension = path.parse('./'+ file).ext.toLowerCase();
//if file happens to be an object and has the property url, parse it differently.
if (file.hasOwnProperty('url')) {
validExtensions = new Set([...videoTypes, ...audioTypes]);
extension = path.parse('./'+ file.url).ext.toLowerCase();
if(validExtensions.has(extension)) {
return file;
}
else {
console.warn(`file ${file.url} has an unsupported file extension. skipping...`);
}
}
return (validExtensions.has(extension));
}
//this is for playist
this.getPlaylistMediaTypes = () => {
//m3u playlists will not support ambiguous file types for the moment.
this.playlist.forEach((file)=>{
let extension = path.parse(file.url).ext.toLowerCase();
if (audioTypes.has(extension)) this.mediaTypes.push('audio');
else if (videoTypes.has(extension)) this.mediaTypes.push('video');
});
};
// Determine whether files are audio, video, or unsupported
this.getMediaTypes = () => {
this.playlist.forEach((url) => {
let relativeUrl = './public' + url;
let extension = path.parse(relativeUrl).ext.toLowerCase();
if (audioTypes.has(extension)) this.mediaTypes.push('audio');
else if (videoTypes.has(extension)) this.mediaTypes.push('video');
else if (ambiguousTypes.has(extension)) {
const shellCommand = `ffmpeg -i "${relativeUrl}" -hide_banner 2>&1 | grep `;
const executeSync = require('child_process').execSync;
try {
executeSync(shellCommand + 'Video:'); // Check if ogg or webm file is video
this.mediaTypes.push('video');
}
catch (videoError) {
try {
executeSync(shellCommand + 'Audio:'); // Check if ogg or webm file is audio
this.mediaTypes.push('audio');
}
catch (audioError) {
throw Error(`${url} has no video or audio content`);
}
}
}
else throw Error(`${url} is an unsuported file type`);
});
};
// Compute video end times
// Compute video end times
this.previous = function() {
console.log("previous");
this.mediaIndex--;
if(this.mediaIndex < 0){
this.mediaIndex = this.playlist.length - 1;
}
this.emitNewMediaEvent() ;
};
this.next = () => {
console.log("next");
this.mediaIndex++;
if(this.mediaIndex >= this.playlist.length){
this.mediaIndex = 0;
this.playlistCount++;
}
this.emitNewMediaEvent();
};
this.emitNewMediaEvent = () => {
this.startTime = new Date();
let url = `${playlistUrl}${this.playlist[this.mediaIndex]}`;
//if were in m3u mode were passing an object so we have to fetch the url from the object
if (argv.m3u) {
//check the url for a remote http string
if (this.playlist[this.mediaIndex]['url'].startsWith('http')) {
url = `${this.playlist[this.mediaIndex]['url']}`;
}
else {
//else its a local file
url = `${playlistUrl}${this.playlist[this.mediaIndex]['url']}`;
}
}
const mediaType = this.mediaTypes[this.mediaIndex];
const duration = this.mediaLengths[this.mediaIndex];
const data = {
url: url,
duration: duration,
mediaType: mediaType
};
this.io.sockets.emit('newMedia', data);
};
this.startTimers = () => {
this.startTime = new Date(); // Start main timer
};
this.tick = () => {
this.elapsedTime = (new Date() - this.startTime)/1000;
if (this.elapsedTime >= this.mediaLengths[this.mediaIndex]) {
this.startTime = new Date();
this.next();
}
};
this.restartTimers = () => {
this.startTimers();
};
// Extract media duration. Documentation: https://ffmpeg.org/ffprobe.html
this.getMediaLength = (url, index) => {
const shellCommand = 'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1';
const execute = require('child_process').exec;
execute(`${shellCommand} "./public${url}"`, (err, stdout) => {
let duration = stdout.split('\n')[0]; // Remove \n
this.mediaLengths[index] = parseFloat(duration);
this.filesProcessed++;
if (this.filesProcessed === this.mediaLengths.length) {
this.startTimers();
}
});
};
//register media lengths from M3U playlist
this.registerMediaLength = (file, index) => {
this.mediaLengths[index] = file.duration;
this.filesProcessed++;
if (this.filesProcessed === this.mediaLengths.length) {
this.startTimers();
}
};
// Initialize by parsing media
this.init = () => {
if (argv.m3u) {
this.getPlaylistMediaTypes();
this.playlist.forEach((file, index)=>{
this.registerMediaLength(file,index);
});
}
else {
this.getMediaTypes();
this.playlist.forEach((fileUrl, index) => {
this.getMediaLength(fileUrl, index);
});
}
};
this.getTimestamp = () => {
this.elapsedTime = (new Date() - this.startTime)/1000;
let timestamp = this.elapsedTime;
//if were in m3u mode were passing an object so we have to fetch the url from the object
if (argv.m3u) {
//check if the url is remote
if (this.playlist[this.mediaIndex]['url'].startsWith('http')) {
console.log(`watching file ${this.playlist[this.mediaIndex]['url']}; ${timestamp}s`);
}
//else include localhost for the person watching the backend of this app.
else console.log(`watching file ${playlistUrl}${this.playlist[this.mediaIndex]['url']}; ${timestamp}s`);
}
else {
console.log(`watching file ${playlistUrl}${this.playlist[this.mediaIndex]}; ${timestamp}s`);
}
return timestamp;
};
setInterval(()=>{
this.tick();
},500);
this.init();
};