forked from DiHuang92/Streaming-Video-Server-and-Client
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Client.py
285 lines (241 loc) · 9.05 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
from Tkinter import *
import tkMessageBox
from PIL import Image, ImageTk
import socket, threading, sys, traceback, os
from RtpPacket import RtpPacket
CACHE_FILE_NAME = "cache-"
CACHE_FILE_EXT = ".jpg"
class Client:
INIT = 0
READY = 1
PLAYING = 2
state = INIT
SETUP = 0
PLAY = 1
PAUSE = 2
TEARDOWN = 3
# Initiation..
def __init__(self, master, serveraddr, serverport, rtpport, filename):
self.master = master
self.master.protocol("WM_DELETE_WINDOW", self.handler)
self.createWidgets()
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
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.master.destroy() # Close the gui window
os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video
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
threading.Thread(target=self.listenRtp).start()
self.playEvent = threading.Event()
self.playEvent.clear()
self.sendRtspRequest(self.PLAY)
def listenRtp(self):
"""Listen for RTP packets."""
while True:
try:
data = self.rtpSocket.recv(20480)
if data:
rtpPacket = RtpPacket()
rtpPacket.decode(data)
currFrameNbr = rtpPacket.seqNum()
print "Current Seq Num: " + str(currFrameNbr)
if currFrameNbr > self.frameNbr: # Discard the late packet
self.frameNbr = currFrameNbr
self.updateMovie(self.writeFrame(rtpPacket.getPayload()))
except:
# Stop listening upon requesting PAUSE or TEARDOWN
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
file = open(cachename, "wb")
file.write(data)
file.close()
return cachename
def updateMovie(self, imageFile):
"""Update the image file as video frame in the GUI."""
photo = ImageTk.PhotoImage(Image.open(imageFile))
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 = self.rtspSeq + 1
# Write the RTSP request to be sent.
# request = ...
request = "%s %s %s\nCSeq: %d\nTransport: %s; client_port = %d" % (self.SETUP_STR, self.fileName, self.RTSP_VER, self.rtspSeq, self.TRANSPORT, self.rtpPort)
# 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 = "%s %s %s\nCSeq: %d\nSession: %d" % (self.PLAY_STR, self.fileName, self.RTSP_VER, self.rtspSeq, self.sessionId)
# 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 = "%s %s %s\nCSeq: %d\nSession: %d" % (self.PAUSE_STR, self.fileName, self.RTSP_VER, self.rtspSeq, self.sessionId)
# Keep track of the sent request.
# self.requestSent = ...
self.requestSent = self.PAUSE
# Teardown request
# ...
elif requestCode == self.TEARDOWN:
# Update RTSP sequence number.
# ...
self.rtspSeq = self.rtspSeq + 1
# Write the RTSP request to be sent.
# request = ...
request = "%s %s %s\nCSeq: %d\nSession: %d" % (self.TEARDOWN_STR, self.fileName, self.RTSP_VER, self.rtspSeq, self.sessionId)
# Keep track of the sent request.
# self.requestSent = ...
self.requestSent = self.TEARDOWN
else:
return
# Send the RTSP request using rtspSocket.
# ...
self.rtspSocket.send(request)
print '\nData sent:\n' + request
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):
"""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
#-------------
# TO COMPLETE
#-------------
# Update RTSP state and other variables if needed
#...
if self.sessionId == session and int(lines[0].split(' ')[1]) == 200:
if self.requestSent == self.SETUP:
self.state = self.READY
self.openRtpPort()
elif self.requestSent == self.PLAY:
self.state=self.PLAYING
elif self.requestSent == self.PAUSE:
self.state=self.READY
self.playEvent.set()
elif self.requestSent == self.TEARDOWN:
self.state=self.INIT
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 = ...
self.rtpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 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
# ...
self.state = self.READY
self.rtpSocket.bind(('',self.rtpPort))
except:
tkMessageBox.showwarning('Unable to Bind', 'Unable to bind PORT=%d' %self.rtpPort)
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()