forked from Malric/NMPS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathltunez-server.py
259 lines (247 loc) · 9.21 KB
/
ltunez-server.py
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
###
#
# LTunez Server
#
###
import sys
import argparse
import socket
import threading
import select
import os
import shutil
import RTSP
import sdp
import playlist
import time
import scp
import random
import helpers
import plp
import signal
import statistics
server_ip = ""
stats = statistics.Statistics()
def listen(PORT):
""" Create listening socket """
HOST = None # Symbolic name meaning all available interfaces
PORT = PORT
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error as msg:
print 'Server: ',msg
s = None
continue
try:
s.bind(sa)
except socket.error as msg:
print 'Server: ',msg
s.close()
s = None
continue
try:
s.listen(5)
except socket.error as msg:
print 'Server: ',msg
s.close()
s = None
continue
break
return s
def startANDconnect(file_name):
""" This function starts streamer process for the given file (song) if not exists """
file_path = 'Wavs/' + file_name
socket_path = 'Sockets/' + file_name
if not os.path.exists(socket_path):
pid = os.fork()
if pid < 0:
return None
elif pid == 0:
os.execlp('python','python','streamer.py',file_path,socket_path)
print 'Server: Forked'
time.sleep(2)
temp_path = os.tmpnam()
try:
unixsocket = socket.socket(socket.AF_UNIX,socket.SOCK_DGRAM)
except socket.error as msg:
print 'RTSP thread unix socket creation',msg
return None
try:
unixsocket.bind(temp_path)
except socket.error as msg:
print 'RTSP thread unix socket bind',msg
return None
try:
unixsocket.connect(socket_path)
except socket.error as msg:
print 'RTSP thread unix socket connect',msg
return None
return unixsocket
class Accept_PL(threading.Thread):
""" Thread class. Each thread handles playlist request/reply for specific connection. """
def __init__(self, conn, addr, port_rtsp, playlistLen):
""" Initialize with socket and address. """
threading.Thread.__init__(self)
self.conn = conn
self.addr = addr
self.port_rtsp = port_rtsp
self.playlistLen = playlistLen
def run(self):
""" Override base class run() function. """
global stats
data = self.conn.recv(1024)
if data is None:
print "Playlist Server: No data"
plpmessage = plp.PLPMessage()
plpmessage.parse(data)
if plpmessage.command == "GET PLAYLIST" and plpmessage.program =="LTunez-Client":
stats.playlists += 1
pl = playlist.getPlaylist(self.playlistLen, server_ip, self.port_rtsp)
reply = plpmessage.createServerOkResponse("LTunez-Server", pl)
print "Playlist Server: Sending playlist reply:\r\n" + reply
self.conn.sendall(reply)
else:
#print "Playlist Server: Invalid request from client"
reply = plpmessage.createServerFailureResponse("LTunez-Server")
self.conn.sendall(reply)
self.conn.close()
class Accept_RTSP(threading.Thread):
""" Thread class. Each thread handles RTSP message request/reply for specific connection. """
def __init__(self,conn,addr):
""" Initialize with socket and address. """
threading.Thread.__init__(self)
self.conn = conn
self.addr = addr
def run(self):
""" Override base class run() function. """
global stats
data = ''
unixsocket = None
p = RTSP.RTSPMessage(None)
# RTSP Commands:
funcPointer = dict()
funcPointer["OPTIONS"] = p.createOptionsReplyMessage
funcPointer["DESCRIBE"] = p.createDescriptionReplyMessage
funcPointer["SETUP"] = p.createSetupReplyMessage
funcPointer["TEARDOWN"] = p.createTeardownReplyMessage
funcPointer["PLAY"] = p.createPlayReplyMessage
funcPointer["PAUSE"] = p.createPauseReplyMessage
session = random.randint(0,1000)
s = sdp.SDPMessage("LTunez", "LTunez", session)
# SCP Commands:
u = scp.SCPMessage()
ffuncPointer = dict()
ffuncPointer["SETUP"] = u.createSetup
ffuncPointer["TEARDOWN"] = u.createTeardown
ffuncPointer["PLAY"] = u.createPlay
ffuncPointer["PAUSE"] = u.createPause
while True:
data = self.conn.recv(1024)
p.fromstring(data)
p.dumpMessage()
if p.parse() is False:
self.conn.close()
break
else:
if p.rtspCommand == "SETUP":
unixsocket = startANDconnect(p.pathname)
if unixsocket is None:
self.conn.close()
break
stats.songs += 1
if p.rtspCommand != "DESCRIBE" and p.rtspCommand != "OPTIONS":
try:
""" Controlling the streamers is basically done as converting RTSP requests to SCP requests."""
r1,r2 = p.clientport.split('-')
unixsocket.send(ffuncPointer[p.rtspCommand](self.addr[0],r1,r2))
except socket.error as msg:
print 'IPC: ',msg
if p.rtspCommand == "SETUP" or "PLAY":
reply = unixsocket.recv(1024)
u.parse(reply)
if p.rtspCommand == "SETUP":
s.setPort(u.clientRtpPort)
s.setRtpmap()
s.setMode("sendonly")
if p.rtspCommand == "DESCRIBE":
s.setPort(0)
s.setRtpmap()
s.setMode("sendonly")
try:
""" Sending RTSP replies to clients"""
self.conn.sendall(funcPointer[p.rtspCommand](p.cseq,p.URI,s.getMessage(),p.transport,p.clientport,u.clientRtpPort+'-'+u.clientRtcpPort,str(session), u.sequence, u.rtptime))
except socket.error as msg:
print 'RTSP thread ',msg
p.dumpMessage()
if p.rtspCommand == "TEARDOWN":
self.conn.close()
break
def server(port_rtsp, port_playlist, playlistLen):
""" This function waits for RTSP/Playlist request and starts new thread. """
global stats
global server_ip
playlistLen = playlistLen
server_ip = helpers.tcpLocalIp()
print "Server: My IP: " + server_ip
helpers.createDir("Wavs")
helpers.createDir("Sockets")
playlist.initSongs()
inputs = []
rtspsocket = listen(port_rtsp)
if rtspsocket is None:
sys.exit(1)
playlistsocket = listen(port_playlist)
if playlistsocket is None:
rtspsocket.close()
sys.exit(1)
inputs.append(rtspsocket)
inputs.append(playlistsocket)
while True:
try:
inputready,outputready,exceptready = select.select(inputs,[],[])
except KeyboardInterrupt:
print '\r\nInterrupted by user'
inputs.remove(rtspsocket)
inputs.remove(playlistsocket)
rtspsocket.close()
playlistsocket.close()
shutil.rmtree(os.getcwd() + '/Sockets', ignore_errors=True) # remove "Sockets" dir
shutil.rmtree(os.getcwd() + '/Wavs', ignore_errors=True) # remove "Wavs" dir
stats.printStats()
os.kill(os.getpid(), signal.SIGTERM) # terminate itself
for option in inputready:
if option is rtspsocket:
try:
conn, addr = rtspsocket.accept()
except socket.error as msg:
print 'Server: RTSP ',msg
continue
print 'Server: RTSP connection from ', addr
r = Accept_RTSP(conn,addr)
r.start()
elif option is playlistsocket:
try:
conn,addr = playlistsocket.accept()
except socket.error as msg:
print 'Server: Playlist ',msg
continue
print 'Server: Playlist request from ', addr
p = Accept_PL(conn,addr,port_rtsp, playlistLen)
p.start()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--playlist", help="playlist server port", type=int)
parser.add_argument("-r", "--rtsp", help="rtsp server port", type=int)
parser.add_argument("-pl", "--playlistLen", help="Amount of items in playlist messages", type=int)
args = parser.parse_args()
playlistLen = 3
if args.playlistLen is not None:
if args.playlistLen >0 and args.playlistLen <sys.maxint:
playlistLen = args.playlistLen
else:
playlistLen = 3
server_ip = helpers.sockLocalIp()
server(args.rtsp,args.playlist, playlistLen)