summaryrefslogtreecommitdiff
path: root/bin/session.php
blob: 81582ee64e71bf5b850114be372b9a772bc31ef9 (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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<?php

function sessioncreate($type, $url, $mode)
{
	global $httppath, $ffmpegpath, $segmenterpath, $quality, $maxencodingprocesses, $ffmpegdebug, $ffmpegdebugfile;

	addlog("Creating a new session for \"" .$url ."\" (" .$type .", " .$mode .")");

	// Check url
	if (!isurlvalid($url, $type))
		return "";

	// Check that the max number of session is not reached yet
	$nbencprocess = exec("find ../ram/ -name segmenter.pid | wc | awk '{ print $1 }'");
	if ($nbencprocess >= $maxencodingprocesses)
	{
		addlog("Error: Cannot create sesssion, too much sessions already encoding");
		return "";
	}

	// Get a free session
	$i=0;
	for ($i=0; $i<1000; $i++)
	{
		$session = "session" .$i;
		if (!file_exists('../ram/' .$session))
			break;
	}

	if ($i == 1000)
	{
		addlog("Error: Cannot find a new session name");
		return "";
	}

	// Default
	$qparams = $quality['3g'];

	// Get parameters
	foreach ($quality as $qn => $qp)
	{
		if ($qn == $mode)
		{
			$qparams = $qp;
			break;
		}
	}

	// Create session
	addlog("Creating new session dir ram/" .$session);
	exec('mkdir ../ram/' .$session);
	// Extract $channame if needed
        switch ($type)
        {
                case 'tv':
                        $urlarray = explode("/", $url);
                        $channum = $urlarray[count($urlarray)-1];
                        $channame = vdrgetchanname($channum);
                        break;
                case 'rec':
                        list($channame, $title, $desc, $recorded) = vdrgetrecinfo($url);
                        break;
                default:
                        $channame = "";
                        break;
        }

	// Create logo
        if ($type == 'vid')
                generatelogo($type, $url, '../ram/' .$session .'/thumb.png');
        else
                generatelogo($type, $channame, '../ram/' .$session .'/thumb.png');

	// FFMPEG debug
	if ($ffmpegdebug)
		$ffdbg = $ffmpegdebugfile;
	else
		$ffdbg = "";

	// Start encoding
	$url = str_replace("\\'", "'", $url);
	switch ($type)
	{
		case 'tv':
			$cmd = "./istream.sh \"" .$url ."\" " .$qparams ." " .$httppath ." 2 " .$ffmpegpath ." " .$segmenterpath ." " .$session ." \"" .$ffdbg ."\" \"\" >/dev/null &";
			break;
		case 'rec':
			$cmd = "./istream.sh - " .$qparams ." " .$httppath ." 1260 " .$ffmpegpath ." " .$segmenterpath ." " .$session ." \"" .$ffdbg ."\" \"cat \\\"" .$url ."/\\\"/0* |\" >/dev/null &";
			break;
		case 'vid':
			$cmd = "./istream.sh \"" .$url ."\" " .$qparams ." " .$httppath ." 1260 " .$ffmpegpath ." " .$segmenterpath ." " .$session ." \"" .$ffdbg ."\" \"\" >/dev/null &";
                        break;
		default:
			$cmd = "";
	}
	
	addlog("Sending encoding command: " .$cmd);

	$cmd = str_replace('%', '%%', $cmd);
	exec ($cmd);

	// Write streaminfo
	writeinfostream($session, $type, $mode, $url, $channame);

	return $session;
}

function sessiondelete($session)
{
	$ret = array();
	
	if ($session == 'all')
	{
		$dir_handle = @opendir('../ram/');
		if ($dir_handle)
		{
			while ($session = readdir($dir_handle))
			{
				if($session == "." || $session == ".." || $session == 'lost+found')
					continue;

				if (!is_dir('../ram/' .$session))
					continue;

				// Get info
				list($type, $mode, $url, $channame) = readinfostream($session);

				if ($type != "none")
					sessiondeletesingle($session);
			}
		}
	}
	else
		sessiondeletesingle($session);

	$ret['status'] = "ok";
	$ret['message'] = "Successfully stopped broadcast";

	return $ret;

}

function sessiongetinfo($session)
{
	$info = array();

	addlog("Getting info for session " .$session);

	// Get some info
	list($type, $mode, $url, $channame) = readinfostream($session);
	
	// Fill common info
	$info['session'] = $session;
	$info['type'] = $type;
	$info['mode'] = $mode;

	// Get info
	$getid3 = new getID3;
	$fileinfo = $getid3->analyze('../ram/' .$session .'/thumb.png');
	$info['thumbwidth'] = $fileinfo['video']['resolution_x'];
	$info['thumbheight'] = $fileinfo['video']['resolution_y']; 

	// Type info
	switch ($type)
	{
		case 'tv':
			$info['name'] = $channame;
			$channum = vdrgetchannum($channame);
			list($date, $info['now_time'], $info['now_title'], $info['now_desc']) = vdrgetepgat($channum, "now");
			list($date, $info['next_time'], $info['next_title'], $info['next_desc']) = vdrgetepgat($channum, "next");
			break;
		case 'rec':
			$info['channel'] = $channame;
			list($channame, $info['name'], $info['desc'], $info['recorded']) = vdrgetrecinfo($url);
			break;
		case 'vid':
			$infovid = mediagetinfostream($url);
			$info['name'] = basename($url);
			$info['desc'] = $infovid['desc'];
			$info['duration'] = $infovid['duration'];
			$info['format'] = $infovid['format'];
			$info['video'] = $infovid['video'];
			$info['audio'] = $infovid['audio'];
			$info['resolution'] = $infovid['resolution'];
			break;
	}

	return $info;
}


function sessiondeletesingle($session)
{
	addlog("Deleting session " .$session);

	$ram = "../ram/" .$session ."/";
	$cmd = "";

	// First kill ffmpeg
	if (file_exists($ram ."ffmpeg.pid"))
		$cmd .= " kill `cat " .$ram ."ffmpeg.pid`; rm " .$ram ."ffmpeg.pid; ";

	// Then kill segmenter
	if (file_exists($ram ."segmenter.pid"))
		$cmd .= " kill `cat " .$ram ."segmenter.pid`; rm " .$ram ."segmenter.pid; ";

	addlog("Sending session kill command: " .$cmd);

	$cmd .= "rm -rf " .$ram;
	exec ($cmd);
}

function getstreamingstatus($session)
{
	global $maxencodingprocesses, $httppath;

	$status = array();

	$path = '../ram/' .$session;

	// Check that session exists
	if (!count(glob($path)))
	{
		$status['status'] = "error";

	        $nbencprocess = exec("find ../ram/ -name segmenter.pid | wc | awk '{ print $1 }'");
	        if ($nbencprocess >= $maxencodingprocesses)
			$status['message'] = "<b>Error: too much sessions</b>";
	        else
			$status['message'] = "<b>Error: could not create session folder</b>";
	}
	else
	{
		// Get stream info
		list($type, $mode, $url, $channame) = readinfostream($session);

		if (count(glob($path . '/*.ts')) < 2)
		{
			if (!file_exists($path .'/segmenter.pid'))
			{
				$status['status'] = "error";
				$status['message'] = "<b>Error: segmenter did not start correclty</b>";
			}
			else
			{
				$status['status'] = "wait";
				switch ($type)
				{
					case 'tv':
						$status['message'] = "<b>Live: requesting " .$channame ."</b>";
						break;
					case 'rec':
						$status['message'] = "<b>Rec: requesting " .$channame ."</b>";
						break;
					case 'vid':
						$status['message'] = "<b>Vid: requesting " .$url ."</b>";
						break;
				}

				$status['message'] .= "<br>";

                               
				$status['message'] .= "<br>  * FFmpeg: ";
				if (file_exists($path .'/ffmpeg.pid'))
					$status['message'] .= "<i>running</i>";
				else
					$status['message'] .= "<i>stopped</i>";
				$status['message'] .= "<br>  * Segmenter: ";
				if (file_exists($path .'/segmenter.pid'))
				{
					$status['message'] .= "<i>running</i> (";
					$status['message'] .= count(glob($path . '/*.ts')) ."/2)</i>";
				}
				else
					$status['message'] .= "<i>stopped</i>";
				
			}
		}
		else
		{
			$status['status'] = "ready";

			$status['message'] = "<b>Broadcast ready</b><br>";

			$status['message'] .= "<br>  * Quality: <i>" .$mode ."</i>";
			$status['message'] .= "<br>  * Status: ";
			if (file_exists($path .'/segmenter.pid'))
				$status['message'] .= "<i>encoding...</i>";
			else
				$status['message'] .= "<i>fully encoded</i>";

			$status['url'] = $httppath ."ram/" .$session ."/stream.m3u8";

		}
	}

	return $status;
}

function sessiongetstatus($session, $prevmsg)
{
	$time = time();

	// Check if we need to timeout on the sesssion creation */
	$checkstart = preg_match("/requesting/", $prevmsg);
	
	while((time() - $time) < 29)
	{

		// Get current status
		$status = getstreamingstatus($session);
	
		// Alway return ready
		if ($status['status'] == "ready")
		{
			addlog("Returning status: " .$status['message']);
			return $status;
		}

		// Status change
		if ($status['message'] != $prevmsg)
		{
			addlog("Returning status: " .$status['message']);
			return $status;
		}

		// Check session creation timeout
		if ($checkstart && ((time() - $time) >= 10))
		{
			$status['status'] = "error";
			$status['message'] = "Error: session could not start";

			addlog("Returning status: " .$status['message']);
			return $status;
		}

		usleep(10000);
	}

	/* Time out */
	$status['status'] = "wait";
	$status['message'] = $prevmsg;

	addlog("Returning status: " .$status['message']);
	return $status;
}

function sessiongetlist()
{
	$sessions = array();

	addlog("Listing sessions");

	$dir_handle = @opendir('../ram/');
	if ($dir_handle)
	{
		while ($session = readdir($dir_handle))
		{
			if($session == "." || $session == ".." || $session == 'lost+found')
				continue;

			if (!is_dir('../ram/' .$session))
				continue;

			// Get info
			list($type, $mode, $url, $channame) = readinfostream($session);
			if ($type == "none")
				continue;

			// Get status
			$status = getstreamingstatus($session);

			$newsession = array();
			$newsession['session'] = substr($session, strlen("session"));
			$newsession['type'] = $type;
			if ($type == "vid")
				$newsession['name'] = basename($url);
			else
				$newsession['name'] = $channame;

			if ($status['status'] == "error")
				$newsession['name'] = "Error: " .$newsession['name'];

			// Check if encoding
			if (file_exists('../ram/' .$session .'/segmenter.pid') && ($status['status'] != "error"))
				$newsession['encoding'] = 1;
			else
				$newsession['encoding'] = 0;

			$sessions[] = $newsession;
		}
	}

	return $sessions;
}

function streammusic($path, $file)
{
	global $httppath;

	addlog("Streaming music from path \"" .$path ."\"");

	if (!isurlvalid($path, "media"))
		return array();

	$files = array();

	// Create all symlinks
	exec('mkdir ../playlist');
        exec('rm ../playlist/*');
        exec('ln -s ' .addcslashes(quotemeta($path), " &'") .'/* ../playlist');

	// Generate files

	// Get listing
	$filelisting = filesgetlisting($path);
	
	$addfiles = 0;
	
	foreach ($filelisting as $f)
	{
		if ($f['type'] != 'audio')
			continue;

		if ($f['name'] == $file)
			$addfiles = 1;

		if ($addfiles)
		{
			$newfile = array();
			$newfile['file'] = $httppath ."playlist/" . $f['name'];
			$files[] = $newfile;
		}
	}

	return $files;
}

?>