-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.py
368 lines (303 loc) · 12.6 KB
/
Client.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
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
import os
import socket
import sys
import threading
import tkinter.messagebox as tkMessageBox
import traceback
from tkinter import *
from PIL import Image
from RtpFrameGenerator import RtpPacket
__author__ = 'Tibbers'
CACHE_FILE_NAME = "cache-"
CACHE_FILE_EXT = ".jpg"
class Client:
"""
RTSP Client
"""
INIT = 0
READY = 1
PLAYING = 2
state = INIT
SETUP = 0
PLAY = 1
PAUSE = 2
TEARDOWN = 3
counter = 0
# Initiation..
def __init__(self, master, serveraddr, serverport, rtpport, filename):
self.master = master
self.master.protocol("WM_DELETE_WINDOW", self.handler)
self.serverAddr = serveraddr
self.serverPort = int(serverport)
self.rtpPort = int(rtpport)
self.fileName = filename
self.rtspSeq = 0
self.sessionId = 0
self.requestSent = -1
self.teardownAcked = 0
self.connectToServer()
self.frameNbr = 0
self.rtpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.createWidgets()
def createWidgets(self):
"""Build GUI."""
# Create Setup button
self.setup = Button(self.master, width=20, padx=3, pady=3)
self.setup["text"] = "Setup"
self.setup["command"] = self.setupMovie
self.setup.grid(row=1, column=0, padx=2, pady=2)
# Create Play button
self.start = Button(self.master, width=20, padx=3, pady=3)
self.start["text"] = "Play"
self.start["command"] = self.playMovie
self.start.grid(row=1, column=1, padx=2, pady=2)
# Create Pause button
self.pause = Button(self.master, width=20, padx=3, pady=3)
self.pause["text"] = "Pause"
self.pause["command"] = self.pauseMovie
self.pause.grid(row=1, column=2, padx=2, pady=2)
# Create Teardown button
self.teardown = Button(self.master, width=20, padx=3, pady=3)
self.teardown["text"] = "Teardown"
self.teardown["command"] = self.exitClient
self.teardown.grid(row=1, column=3, padx=2, pady=2)
# Create a label to display the movie
self.label = Label(self.master, height=19)
self.label.grid(row=0, column=0, columnspan=4, sticky=W + E + N + S, padx=5, pady=5)
def setupMovie(self):
"""Setup button handler."""
if self.state == self.INIT:
self.sendRtspRequest(self.SETUP)
def exitClient(self):
"""Teardown button handler."""
self.sendRtspRequest(self.TEARDOWN)
# self.handler()
self.master.destroy() # Close the gui window
os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video
rate = float(self.counter / self.frameNbr)
print('-' * 60 + "\nRTP Packet Loss Rate :" + str(rate) + "\n" + '-' * 60)
sys.exit(0)
def pauseMovie(self):
"""Pause button handler."""
if self.state == self.PLAYING:
self.sendRtspRequest(self.PAUSE)
def playMovie(self):
"""Play button handler."""
if self.state == self.READY:
# Create a new thread to listen for RTP packets
print("Playing Movie")
threading.Thread(target=self.listen_rtp).start()
self.playEvent = threading.Event()
self.playEvent.clear()
self.sendRtspRequest(self.PLAY)
def listen_rtp(self):
max_rtp_packet = 20480
rtp_packet = RtpPacket()
while True:
try:
data_raw, address = self.rtpSocket.recvfrom(max_rtp_packet)
if data_raw:
rtp_packet.decode(data_raw)
print("||Received Rtp Packet #" + str(rtp_packet.seqnum) + "|| ")
try:
if self.frameNbr + 1 != rtp_packet.seqnum:
self.counter += 1
print('!' * 60 + "\nPACKET LOSS\n" + '!' * 60)
currFrameNbr = rtp_packet.seqnum
# version = rtpPacket.version()
except:
print("seqNum() error")
print('-' * 60)
traceback.print_exc(file=sys.stdout)
print('-' * 60)
if currFrameNbr > self.frameNbr: # Discard the late packet
self.frameNbr = currFrameNbr
self.updateMovie(self.writeFrame(rtp_packet.getPayload()))
except:
# Stop listening upon requesting PAUSE or TEARDOWN
print("Didn`t receive data!")
if self.playEvent.isSet():
break
# Upon receiving ACK for TEARDOWN request,
# close the RTP socket
if self.teardownAcked == 1:
self.rtpSocket.shutdown(socket.SHUT_RDWR)
self.rtpSocket.close()
break
def writeFrame(self, data):
"""Write the received frame to a temp image file. Return the image file."""
cachename = CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT
try:
file = open(cachename, "wb")
except:
print("file open error")
try:
file.write(data)
except:
print("file write error")
file.close()
return cachename
def updateMovie(self, imageFile):
"""Update the image file as video frame in the GUI."""
try:
photo = PhotoImage(Image.open(imageFile)) # stuck here !!!!!!
except:
print("photo error")
print('-' * 60)
traceback.print_exc(file=sys.stdout)
print('-' * 60)
self.label.configure(image=photo, height=288)
self.label.image = photo
def connectToServer(self):
"""Connect to the Server. Start a new RTSP/TCP session."""
self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.rtspSocket.connect((self.serverAddr, self.serverPort))
except:
tkMessageBox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' % self.serverAddr)
def sendRtspRequest(self, requestCode):
"""Send RTSP request to the server."""
# -------------
# TO COMPLETE
# -------------
# Setup request
if requestCode == self.SETUP and self.state == self.INIT:
threading.Thread(target=self.recvRtspReply).start()
# Update RTSP sequence number.
# ...
self.rtspSeq = 1
# Write the RTSP request to be sent.
# request = ...
request = "SETUP " + str(self.fileName) + "\n" + str(self.rtspSeq) + "\n" + " RTSP/1.0 RTP/UDP " + str(
self.rtpPort)
self.rtspSocket.send(request)
# Keep track of the sent request.
# self.requestSent = ...
self.requestSent = self.SETUP
# Play request
elif requestCode == self.PLAY and self.state == self.READY:
# Update RTSP sequence number.
# ...
self.rtspSeq = self.rtspSeq + 1
# Write the RTSP request to be sent.
# request = ...
request = "PLAY " + "\n" + str(self.rtspSeq)
self.rtspSocket.send(request)
print('-' * 60 + "\nPLAY request sent to Server...\n" + '-' * 60)
# Keep track of the sent request.
# self.requestSent = ...
self.requestSent = self.PLAY
# Pause request
elif requestCode == self.PAUSE and self.state == self.PLAYING:
# Update RTSP sequence number.
# ...
self.rtspSeq = self.rtspSeq + 1
# Write the RTSP request to be sent.
# request = ...
request = "PAUSE " + "\n" + str(self.rtspSeq)
self.rtspSocket.send(request)
print('-' * 60 + "\nPAUSE request sent to Server...\n" + '-' * 60)
# Keep track of the sent request.
# self.requestSent = ...
self.requestSent = self.PAUSE
# Resume request
# Teardown request
elif requestCode == self.TEARDOWN and not self.state == self.INIT:
# Update RTSP sequence number.
# ...
self.rtspSeq = self.rtspSeq + 1
# Write the RTSP request to be sent.
# request = ...
request = "TEARDOWN " + "\n" + str(self.rtspSeq)
self.rtspSocket.send(request)
print('-' * 60 + "\nTEARDOWN request sent to Server...\n" + '-' * 60)
# Keep track of the sent request.
# self.requestSent = ...
self.requestSent = self.TEARDOWN
else:
return
# Send the RTSP request using rtspSocket.
# ...
def recvRtspReply(self):
"""Receive RTSP reply from the server."""
while True:
reply = self.rtspSocket.recv(1024)
if reply:
self.parseRtspReply(reply)
# Close the RTSP socket upon requesting Teardown
if self.requestSent == self.TEARDOWN:
self.rtspSocket.shutdown(socket.SHUT_RDWR)
self.rtspSocket.close()
break
def parseRtspReply(self, data):
print("Parsing Received Rtsp data...")
"""Parse the RTSP reply from the server."""
lines = data.split('\n')
seqNum = int(lines[1].split(' ')[1])
# Process only if the server reply's sequence number is the same as the request's
if seqNum == self.rtspSeq:
session = int(lines[2].split(' ')[1])
# New RTSP session ID
if self.sessionId == 0:
self.sessionId = session
# Process only if the session ID is the same
if self.sessionId == session:
if int(lines[0].split(' ')[1]) == 200:
if self.requestSent == self.SETUP:
# -------------
# TO COMPLETE
# -------------
# Update RTSP state.
print("Updating RTSP state...")
# self.state = ...
self.state = self.READY
# Open RTP port.
# self.openRtpPort()
print("Setting Up RtpPort for Video Stream")
self.openRtpPort()
elif self.requestSent == self.PLAY:
self.state = self.PLAYING
print('-' * 60 + "\nClient is PLAYING...\n" + '-' * 60)
elif self.requestSent == self.PAUSE:
self.state = self.READY
# The play thread exits. A new thread is created on resume.
self.playEvent.set()
elif self.requestSent == self.TEARDOWN:
# self.state = ...
# Flag the teardownAcked to close the socket.
self.teardownAcked = 1
def openRtpPort(self):
"""Open RTP socket binded to a specified port."""
# -------------
# TO COMPLETE
# -------------
# Create a new datagram socket to receive RTP packets from the server
# self.rtpSocket = ...
# Set the timeout value of the socket to 0.5sec
# ...
self.rtpSocket.settimeout(0.5)
# try:
# Bind the socket to the address using the RTP port given by the client user
# ...
# except:
# tkMessageBox.showwarning('Unable to Bind', 'Unable to bind PORT=%d' %self.rtpPort)
try:
# self.rtpSocket.connect(self.serverAddr,self.rtpPort)
self.rtpSocket.bind((self.serverAddr,
self.rtpPort)) # WATCH OUT THE ADDRESS FORMAT!!!!! rtpPort# should be bigger than 1024
# self.rtpSocket.listen(5)
print("Bind RtpPort Success")
except:
tkMessageBox.showwarning('Connection Failed', 'Connection to rtpServer failed...')
def handler(self):
"""Handler on explicitly closing the GUI window."""
self.pauseMovie()
if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"):
self.exitClient()
else: # When the user presses cancel, resume playing.
# self.playMovie()
print("Playing Movie")
threading.Thread(target=self.listen_rtp).start()
# self.playEvent = threading.Event()
# self.playEvent.clear()
self.sendRtspRequest(self.PLAY)