-
Notifications
You must be signed in to change notification settings - Fork 86
/
siprtmp_gevent.py
1516 lines (1354 loc) · 75.8 KB
/
siprtmp_gevent.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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2011, Kundan Singh. All rights reserved. see README for details.
# CAUTION: This module is not well tested.
'''
This is higher-performance re-write of rtmp.py and siprtmp.py.
Intead of the multitask module, it uses gevent project.
It support SIP-RTMP gateway.
It support RTMP streaming.
BUT
It does not support file recording/playback.
Please see
http://p2p-sip.blogspot.com/2011/04/performance-of-siprtmp-multitask-vs.html
for details on the performance improvement and measurement result.
The conclusion of my measurement is as follows. The SIP-RTMP gateway software
using gevent takes about 2/3 the CPU cycles than using multitask, and the RTMP
server software using gevent takes about 1/2 the CPU cycles than using multitask.
After the improvements, on a dual-core 2.13 GHz CPU machine, a single audio
call going though gevent-based siprtmp using Speex audio codec at 8Hz sampling
takes about 3.1% CPU, and hence in theory can support about 60 active calls
in steady state. Another way to look at it is that the software requires CPU
cycles of about 66 MHz per audio call.
'''
try:
import gevent
except ImportError:
print 'Please install gevent and its dependencies'
import sys
sys.exit(1)
from gevent import monkey, Greenlet, GreenletExit
monkey.patch_socket()
from gevent.server import StreamServer
from gevent.queue import Queue, Empty
from gevent.coros import Semaphore
import os, sys, traceback, time, struct, socket, random, amf, hashlib, hmac, random
from struct import pack, unpack
from rtmp import Header, Message, Command, App, getfilename, Protocol, FLV as baseFLV
try:
from std import rfc3261, rfc3264, rfc3550, rfc2396, rfc4566, rfc2833, kutil
from app.voip import MediaSession
from siprtmp import MediaContext
sip = True
except:
print 'warning: disabling SIP. To enable please include p2p-sip src directory in your PYTHONPATH before starting this application'
sip = False
# sys.exit(1)
try: import audiospeex, audioop
except: audiospeex = None
_debug = _debugAll = False
def truncate(data, max=100):
return data and len(data)>max and data[:max] + '...(%d)'%(len(data),) or data
# -----------------------------------------------------------------------------
# Borrowed from rtmp.py after changing to multitask to asyncore/gevent
# -----------------------------------------------------------------------------
class Stream(object):
def __init__(self):
self.id, self.name = 0, ''
# self.recordfile, self.playfile = None, None
def close(self):
# if self.recordfile is not None:
# self.recordfile.close()
# self.recordfile = None
# if self.playfile is not None:
# self.playfile.close()
# self.playfile = None
pass
class FlashClient(object):
'''Represents a single Flash connection and client.'''
PING_SIZE, DEFAULT_CHUNK_SIZE, HIGH_WRITE_CHUNK_SIZE, PROTOCOL_CHANNEL_ID = 1536, 128, 4096, 2 # constants
READ_WIN_SIZE, WRITE_WIN_SIZE = 1000000L, 1073741824L
CHANNEL_MASK = 0x3F
crossdomain = '''<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" to-ports="1935" secure='false'/>
</cross-domain-policy>'''
def __init__(self, server, sock):
self.server, self.sock, self.state, self.buffer = server, sock, 'idle', ''
self.bytesRead = self.bytesWritten = 0
self.lastReadHeaders, self.incompletePackets, self.lastWriteHeaders = dict(), dict(), dict()
self.readChunkSize = self.writeChunkSize = self.DEFAULT_CHUNK_SIZE
self.readWinSize0, self.readWinSize, self.writeWinSize0, self.writeWinSize = 0L, self.READ_WIN_SIZE, 0L, self.WRITE_WIN_SIZE
self.nextChannelId = self.PROTOCOL_CHANNEL_ID + 1
self._time0 = time.time()
self.path, self.agent, self.streams, self._nextCallId, self._nextStreamId, self.objectEncoding, self._rpc = \
None, None, {}, 2, 1, 0.0, Message.RPC
self._write_lock = Semaphore()
@property
def relativeTime(self):
return int(1000*(time.time() - self._time0))
def send(self, data):
if self.sock is not None and data is not None:
self._write_lock.acquire()
try:
self.sock.sendall(data)
except:
if _debug: traceback.print_exc()
finally:
self._write_lock.release()
def received(self, data):
self.buffer += data
self.bytesRead += len(data)
while len(self.buffer) > 0:
size, buffer = len(self.buffer), self.buffer
if self.state == 'idle': # no handshake done yet
if size >= 23 and buffer.startswith('<policy-file-request/>\x00'):
self.send(self.crossdomain)
raise RuntimeError, 'closed'
if size < self.PING_SIZE+1: return
self.buffer = buffer[self.PING_SIZE+1:]
response = Protocol.handshakeResponse(buffer[:self.PING_SIZE+1])
self.send(response)
self.state = 'handshake'
elif self.state == 'handshake':
if size < self.PING_SIZE: return
self.buffer = buffer[self.PING_SIZE:]
self.state = 'active'
elif self.state == 'active':
if size < 1: return # at least one byte needed
hdrsize, offset = ord(buffer[0]), 1
channel = hdrsize & self.CHANNEL_MASK
if channel == 0: # we need one more byte
if size < 2: return
channel, offset = 64 + ord(buffer[1:2]), 2
elif channel == 1: # we need two more bytes
if size < 3: return
channel, offset = 64 + ord(buffer[1:2]) + 256 * ord(buffer[2:3]), 3
hdrtype = hdrsize & Header.MASK # read header type byte
if hdrtype == Header.FULL or not self.lastReadHeaders.has_key(channel):
header = Header(channel)
self.lastReadHeaders[channel] = header
else:
header = self.lastReadHeaders[channel]
if hdrtype < Header.SEPARATOR: # time or delta has changed
if size < offset+3: return
header.time, offset = struct.unpack('!I', '\x00' + buffer[offset:offset+3])[0], offset+3
if hdrtype < Header.TIME: # size and type also changed
if size < offset+4: return
header.size, header.type, offset = struct.unpack('!I', '\x00' + buffer[offset:offset+3])[0], ord(buffer[offset+3:offset+4]), offset+4
if hdrtype < Header.MESSAGE: # streamId also changed
if size < offset+4: return
header.streamId, offset = struct.unpack('<I', buffer[offset:offset+4])[0], offset+4
if header.time == 0xFFFFFF: # if we have extended timestamp, read it
if size < offset+4: return
header.extendedTime, offset = struct.unpack('!I', buffer[offset:offset+4])[0], offset+4
if _debug: print 'extended time stamp', '%x'%(header.extendedTime,)
else:
header.extendedTime = None
if hdrtype == Header.FULL:
header.currentTime = header.extendedTime or header.time
header.hdrtype = hdrtype
elif hdrtype in (Header.MESSAGE, Header.TIME):
header.hdrtype = hdrtype
# if _debug: print 'R', header, header.currentTime, header.extendedTime, '0x%x'%(hdrsize,)
data = self.incompletePackets.get(channel, '') # are we continuing an incomplete packet?
count = min(header.size - (len(data)), self.readChunkSize) # how much more
if size < offset+count: return
data, offset = data + buffer[offset:offset+count], offset+count
if size == offset:
self.buffer = ''
else:
self.buffer = buffer[offset:]
# check if we need to send Ack
if self.readWinSize is not None:
if self.bytesRead > (self.readWinSize0 + self.readWinSize):
self.readWinSize0 = self.bytesRead
ack = Message()
ack.time, ack.type, ack.data = self.relativeTime, Message.ACK, struct.pack('>L', self.readWinSize0)
self.writeMessage(ack)
if len(data) < header.size: # we don't have all data
self.incompletePackets[channel] = data
else: # we have all data
if hdrtype in (Header.MESSAGE, Header.TIME):
header.currentTime = header.currentTime + (header.extendedTime or header.time)
elif hdrtype == Header.SEPARATOR:
if header.hdrtype in (Header.MESSAGE, Header.TIME):
header.currentTime = header.currentTime + (header.extendedTime or header.time)
if len(data) == header.size:
if channel in self.incompletePackets:
del self.incompletePackets[channel]
else:
data, self.incompletePackets[channel] = data[:header.size], data[header.size:]
hdr = Header(channel=header.channel, time=header.currentTime, size=header.size, type=header.type, streamId=header.streamId)
msg = Message(hdr, data)
# if _debug: print 'rtmp.parseMessage msg=', msg
if channel == self.PROTOCOL_CHANNEL_ID:
self.protocolMessage(msg)
else:
self.messageReceived(msg)
def writeMessage(self, message, stream=None):
# if _debug: print 'rtmp.writeMessage msg=', message
if stream is not None:
message.streamId = stream.id
# get the header stored for the stream
if self.lastWriteHeaders.has_key(message.streamId):
header = self.lastWriteHeaders[message.streamId]
else:
if self.nextChannelId <= self.PROTOCOL_CHANNEL_ID:
self.nextChannelId = self.PROTOCOL_CHANNEL_ID+1
header, self.nextChannelId = Header(self.nextChannelId), self.nextChannelId + 1
self.lastWriteHeaders[message.streamId] = header
if message.type < Message.AUDIO:
header = Header(self.PROTOCOL_CHANNEL_ID)
# now figure out the header data bytes
if header.streamId != message.streamId or header.time == 0 or message.time <= header.time:
header.streamId, header.type, header.size, header.time, header.delta = message.streamId, message.type, message.size, message.time, message.time
control = Header.FULL
elif header.size != message.size or header.type != message.type:
header.type, header.size, header.time, header.delta = message.type, message.size, message.time, message.time-header.time
control = Header.MESSAGE
else:
header.time, header.delta = message.time, message.time-header.time
control = Header.TIME
hdr = Header(channel=header.channel, time=header.delta if control in (Header.MESSAGE, Header.TIME) else header.time, size=header.size, type=header.type, streamId=header.streamId)
assert message.size == len(message.data)
data = ''
while len(message.data) > 0:
data += hdr.toBytes(control) # gather header bytes
count = min(self.writeChunkSize, len(message.data))
data += message.data[:count]
message.data = message.data[count:]
control = Header.SEPARATOR # incomplete message continuation
if data:
self.send(data)
def protocolMessage(self, msg):
if msg.type == Message.ACK: # update write window size
self.writeWinSize0 = struct.unpack('>L', msg.data)[0]
elif msg.type == Message.CHUNK_SIZE: # update read chunk size
self.readChunkSize = struct.unpack('>L', msg.data)[0]
elif msg.type == Message.WIN_ACK_SIZE: # update read window size
self.readWinSize, self.readWinSize0 = struct.unpack('>L', msg.data)[0], self.bytesRead
elif msg.type == Message.USER_CONTROL:
type, data = struct.unpack('>H', msg.data[:2])[0], msg.data[2:]
if type == 3: # client expects a response when it sends set buffer length
streamId, bufferTime = struct.unpack('>II', data)
response = Message()
response.time, response.type, response.data = self.relativeTime, Message.USER_CONTROL, struct.pack('>HI', 0, streamId)
self.writeMessage(response)
else:
if _debug: print 'ignoring protocol message type', msg.type
def messageReceived(self, msg):
if (msg.type == Message.RPC or msg.type == Message.RPC3) and msg.streamId == 0:
cmd = Command.fromMessage(msg)
# if _debug: print 'rtmp.messageReceived cmd=', cmd
if cmd.name == 'connect':
self.agent = cmd.cmdData
self.objectEncoding = self.agent.objectEncoding if hasattr(self.agent, 'objectEncoding') else 0.0
self._rpc = Message.RPC
self.onConnect(cmd.args) # new connection
elif cmd.name == 'createStream':
self.rpc = Message.RPC if self.objectEncoding == 0.0 else Message.RPC3
response = Command(name='_result', id=cmd.id, tm=self.relativeTime, type=self._rpc, args=[self._nextStreamId])
self.writeMessage(response.toMessage())
stream = self.createStream()
self.onCreateStream(stream) # also notify others of our new stream
elif cmd.name == 'closeStream':
self.rpc = Message.RPC if self.objectEncoding == 0.0 else Message.RPC3
assert msg.streamId in self.streams
self.onCloseStream(self.streams[msg.streamId]) # notify closing to others
del self.streams[msg.streamId]
else:
# if _debug: print 'Client.messageReceived cmd=', cmd
self.onCommand(cmd) # RPC call
else: # this has to be a message on the stream
assert msg.streamId != 0
assert msg.streamId in self.streams
# if _debug: print self.streams[msg.streamId], 'recv'
stream = self.streams[msg.streamId]
if not stream.client: stream.client = self
if msg.type == Message.RPC or msg.type == Message.RPC3:
cmd = Command.fromMessage(msg)
if _debug: print 'stream received cmd=', cmd
if cmd.name == 'publish':
self.onStreamPublish(stream, cmd)
elif cmd.name == 'play':
self.onStreamPlay(stream, cmd)
elif cmd.name == 'closeStream':
self.onCloseStream(stream)
# TODO: Flash Player does not send createStream again when it publish/play for same NetStream
# Hence do not delete the stream from our record.
# del self.streams[msg.streamId]
# elif cmd.name == 'seek':
# self.onStreamSeek(stream, cmd)
else: # audio or video message
self.onStreamMessage(stream, msg)
def accept(self):
'''Method to accept an incoming client.'''
response = Command()
response.id, response.name, response.type = 1, '_result', self._rpc
if _debug: print 'rtmp.accept() objectEncoding=', self.objectEncoding
arg = amf.Object(level='status', code='NetConnection.Connect.Success',
description='Connection succeeded.', fmsVer='rtmplite/8,2')
if hasattr(self.agent, 'objectEncoding'):
arg.objectEncoding = self.objectEncoding
response.setArg(arg)
self.writeMessage(response.toMessage())
def rejectConnection(self, reason=''):
'''Method to reject an incoming client.'''
response = Command()
response.id, response.name, response.type = 1, '_error', self._rpc
response.setArg(amf.Object(level='status', code='NetConnection.Connect.Rejected',
description=reason, fmsVer='rtmplite/8,2', details=None))
self.writeMessage(response.toMessage())
def redirectConnection(self, url, reason='Connection failed'):
'''Method to redirect an incoming client to the given url.'''
response = Command()
response.id, response.name, response.type = 1, '_error', self._rpc
extra = dict(code=302, redirect=url)
response.setArg(amf.Object(level='status', code='NetConnection.Connect.Rejected',
description=reason, fmsVer='rtmplite/8,2', details=None, ex=extra))
self.writeMessage(response.toMessage())
def call(self, method, *args):
'''Call a (callback) method on the client.'''
cmd = Command()
cmd.id, cmd.time, cmd.name, cmd.type = self._nextCallId, self.relativeTime, method, self._rpc
cmd.args, cmd.cmdData = args, None
self._nextCallId += 1
if _debug: print 'rtmp.call method=', method, 'args=', args, ' msg=', cmd.toMessage()
self.writeMessage(cmd.toMessage())
def createStream(self):
''' Create a stream on the server side'''
stream = Stream()
stream.client = self
stream.id = self._nextStreamId
self.streams[stream.id] = stream
self._nextStreamId += 1
return stream
def onConnect(self, args):
if _debug: print 'client connection received', args
if self.objectEncoding != 0 and self.objectEncoding != 3:
self.rejectConnection(reason='Unsupported encoding ' + str(self.objectEncoding) + '. Please use NetConnection.defaultObjectEncoding=ObjectEncoding.AMF0')
return
self.path = str(self.agent.app) if hasattr(self.agent, 'app') else str(self.agent['app']) if isinstance(self.agent, dict) else None
if not self.path:
self.rejectConnection(reason='Missing app path')
return
name, ignore, scope = self.path.partition('/')
if '*' not in self.server.apps and name not in self.server.apps:
self.rejectConnection(reason='Application not found: ' + name)
return
# create application instance as needed and add in our list
if _debug: print 'name=', name, 'name in apps', str(name in self.server.apps)
app = self.server.apps[name] if name in self.server.apps else self.server.apps['*'] # application class
if self.path in self.server.clients: inst = self.server.clients[self.path][0]
else: inst = app()
win_ack = Message()
win_ack.time, win_ack.type, win_ack.data = self.relativeTime, Message.WIN_ACK_SIZE, struct.pack('>L', self.writeWinSize)
self.writeMessage(win_ack)
# set_peer_bw = Message()
# set_peer_bw.time, set_peer_bw.type, set_peer_bw.data = self.relativeTime, Message.SET_PEER_BW, struct.pack('>LB', client.writeWinSize, 1)
# self.writeMessage(set_peer_bw)
try:
result = inst.onConnect(self, *args)
except:
if _debug: print sys.exc_info()
self.rejectConnection(reason='Exception on onConnect');
return
if not (result is True or result is None):
self.rejectConnection(reason='Rejected in onConnect')
return
if self.path not in self.server.clients:
self.server.clients[self.path] = [inst]; inst._clients=self.server.clients[self.path]
self.server.clients[self.path].append(self)
if result is True:
self.accept()
self.connected = True
def onCommand(self, cmd):
inst = self.server.clients[self.path][0]
if inst:
if cmd.name == '_error':
if hasattr(inst, 'onStatus'):
inst.onStatus(self, cmd.args[0])
elif cmd.name == '_result':
if hasattr(inst, 'onResult'):
inst.onResult(self, cmd.args[0])
else:
res, code, result = Command(), '_result', None
try:
result = inst.onCommand(self, cmd.name, *cmd.args)
except:
if _debug: print 'Client.call exception', (sys and sys.exc_info() or None)
code = '_error'
args = (result,) if result is not None else dict()
res.id, res.time, res.name, res.type = cmd.id, self.relativeTime, code, self._rpc
res.args, res.cmdData = args, None
if _debug: print 'rtmp.call method=', code, 'args=', args, ' msg=', res.toMessage()
self.writeMessage(res.toMessage())
def closed(self): # client disconnected
# client is disconnected, clear our state for application instance.
if _debug: print 'cleaning up client', self.path
if self.path in self.server.clients:
inst = self.server.clients[self.path][0]
self.server.clients[self.path].remove(self)
for stream in self.streams.values(): # for all streams of this client
self.onCloseStream(stream)
self.streams.clear() # and clear the collection of streams
inst = None
if self.path in self.server.clients and len(self.server.clients[self.path]) == 1: # no more clients left, delete the instance.
if _debug: print 'removing the application instance'
inst = self.server.clients[self.path][0]
inst._clients = None
del self.server.clients[self.path]
if inst is not None:
inst.onDisconnect(self)
def onCreateStream(self, stream):
pass
def onCloseStream(self, stream):
'''A stream is closed explicitly when a closeStream command is received from given client.'''
inst = self.server.clients[self.path][0]
if inst:
if stream.name in inst.publishers and inst.publishers[stream.name] == stream: # clear the published stream
inst.onClose(self, stream)
del inst.publishers[stream.name]
if stream.name in inst.players and stream in inst.players[stream.name]:
inst.onStop(self, stream)
inst.players[stream.name].remove(stream)
if len(inst.players[stream.name]) == 0:
del inst.players[stream.name]
stream.close()
def onStreamPublish(self, stream, cmd):
'''A new stream is published. Store the information in the application instance.'''
try:
stream.mode = 'live' if len(cmd.args) < 2 else cmd.args[1] # live, record, append
stream.name = cmd.args[0]
if _debug: print 'publishing stream=', stream.name, 'mode=', stream.mode
inst = self.server.clients[self.path][0]
if (stream.name in inst.publishers):
raise ValueError, 'Stream name already in use'
inst.publishers[stream.name] = stream # store the client for publisher
inst.onPublish(self, stream)
# path = getfilename(self.path, stream.name, self.server.root)
# if stream.mode in ('record', 'append'):
# stream.recordfile = FLV().open(path, stream.mode)
if stream.mode in ('record', 'append'):
raise ValueError, 'Recording not implemented'
# elif stream.mode == 'live': FLV().delete(path) # TODO: this is commented out to avoid accidental delete
response = Command(name='onStatus', id=cmd.id, tm=self.relativeTime, args=[amf.Object(level='status', code='NetStream.Publish.Start', description='', details=None)])
self.writeMessage(response.toMessage(), stream)
except ValueError, E: # some error occurred. inform the app.
if _debug: print 'error in publishing stream', str(E)
response = Command(name='onStatus', id=cmd.id, tm=self.relativeTime, args=[amf.Object(level='error',code='NetStream.Publish.BadName',description=str(E),details=None)])
self.writeMessage(response.toMessage(), stream)
def onStreamPlay(self, stream, cmd):
'''A new stream is being played. Just updated the players list with this stream.'''
try:
inst = self.server.clients[self.path][0]
name = stream.name = cmd.args[0] # store the stream's name
start = cmd.args[1] if len(cmd.args) >= 2 else -2
if name not in inst.players:
inst.players[name] = [] # initialize the players for this stream name
if stream not in inst.players[name]: # store the stream as players of this name
inst.players[name].append(stream)
# if start >= 0 or start == -2 and name not in inst.publishers:
# path = getfilename(self.path, stream.name, self.server.root)
# if os.path.exists(path):
# stream.playfile = FLV().open(path)
# if start > 0: stream.playfile.seek(start)
# stream.playfile.reader(stream)
# elif start >= 0: raise ValueError, 'Stream name not found'
if start >= 0: raise ValueError, 'Stream name not found'
if _debug: print 'playing stream=', name, 'start=', start
inst.onPlay(self, stream)
# Default chunk size is 128. It is pretty small when we stream high audio and video quality.
# So, send the choosen chunk size to flash client.
self.writeChunkSize = self.HIGH_WRITE_CHUNK_SIZE
m0 = Message() # SetChunkSize
m0.time, m0.type, m0.data = self.relativeTime, Message.CHUNK_SIZE, struct.pack('>L', self.writeChunkSize)
self.writeMessage(m0)
# m1 = Message() # UserControl/StreamIsRecorded
# m1.time, m1.type, m1.data = self.relativeTime, Message.USER_CONTROL, struct.pack('>HI', 4, stream.id)
# self.writeMessage(m1)
m2 = Message() # UserControl/StreamBegin
m2.time, m2.type, m2.data = self.relativeTime, Message.USER_CONTROL, struct.pack('>HI', 0, stream.id)
self.writeMessage(m2)
#self.writeMessage(Message(hdr=Header(time=self.relativeTime, type=Message.USER_CONTROL), data=struct.pack('>HI', 0, stream.id)));
response = Command(name='onStatus', id=cmd.id, tm=self.relativeTime, args=[amf.Object(level='status',code='NetStream.Play.Start', description=stream.name, details=None)])
self.writeMessage(response.toMessage(), stream)
except ValueError, E: # some error occurred. inform the app.
if _debug: print 'error in playing stream', str(E)
response = Command(name='onStatus', id=cmd.id, tm=self.relativeTime, args=[amf.Object(level='error',code='NetStream.Play.StreamNotFound',description=str(E),details=None)])
self.writeMessage(response.toMessage(), stream)
# def onStreamSeek(self, stream, cmd):
# '''A stream is seeked to a new position. This is allowed only for play from a file.'''
# try:
# offset = cmd.args[0]
# if stream.playfile is None or stream.playfile.type != 'read':
# raise ValueError, 'Stream is not seekable'
# stream.playfile.seek(offset)
# response = Command(name='onStatus', id=cmd.id, tm=self.relativeTime, args=[amf.Object(level='status',code='NetStream.Seek.Notify', description=stream.name, details=None)])
# self.writeMessage(response, stream)
# except ValueError, E: # some error occurred. inform the app.
# if _debug: print 'error in seeking stream', str(E)
# response = Command(name='onStatus', id=cmd.id, tm=self.relativeTime, args=[amf.Object(level='error',code='NetStream.Seek.Failed',description=str(E),details=None)])
# self.writeMessage(response, stream)
def onStreamMessage(self, stream, message):
'''Handle incoming media on the stream, by sending to other stream in this application instance.'''
if stream.client is not None:
inst = self.server.clients[self.path][0]
result = inst.onPublishData(self, stream, message)
if result:
for s in (inst.players.get(stream.name, [])):
#if _debug: print 'D', stream.name, s.name
m = message.dup()
result = inst.onPlayData(s.client, s, m)
if result:
s.client.writeMessage(m, s)
# if stream.recordfile is not None:
# stream.recordfile.write(message)
class FLV(baseFLV):
'''Only the reader() task is changed to gevent instead of multitask from base class rtmp.FLV'''
def __init__(self):
baseFLV.__init__(self)
def reader(self, client, stream):
'''A gevent task that periodically reads the file and sends media in the stream to this client.'''
if _debug: print 'reader started'
try:
while self.fp is not None:
bytes = self.fp.read(11)
if len(bytes) == 0:
response = Command(name='onStatus', id=stream.id, tm=client.relativeTime, args=[amf.Object(level='status',code='NetStream.Play.Stop', description='File ended', details=None)])
client.writeMessage(response.toMessage(), stream)
break
type, len0, len1, ts0, ts1, ts2, sid0, sid1 = struct.unpack('>BBHBHBBH', bytes)
length = (len0 << 16) | len1; ts = (ts0 << 16) | (ts1 & 0x0ffff) | (ts2 << 24)
body = self.fp.read(length); ptagsize, = struct.unpack('>I', self.fp.read(4))
if ptagsize != (length+11):
if _debug: print 'invalid previous tag-size found:', ptagsize, '!=', (length+11),'ignored.'
if stream is None or stream.client is None: break # if it is closed
#hdr = Header(3 if type == Message.AUDIO else 4, ts if ts < 0xffffff else 0xffffff, length, type, stream.id)
hdr = Header(0, ts, length, type, stream.id)
msg = Message(hdr, body)
# if _debug: print 'FLV.read() length=', length, 'hdr=', hdr
# if hdr.type == Message.AUDIO: print 'r', hdr.type, hdr.time
if type == Message.DATA: # metadata
amfReader = amf.AMF0(body) # TODO: use AMF3 if needed
name = amfReader.read()
obj = amfReader.read()
if _debug: print 'FLV.read()', name, repr(obj)
client.writeMessage(msg, stream)
if ts > self.tsp:
diff, self.tsp = ts - self.tsp, ts
if _debug: print 'FLV.read() sleep', diff
gevent.sleep(diff / 1000.0)
except gevent.GreenletExit:
if _debug: print 'closing the reader'
except:
if _debug: print 'closing the reader', (sys and sys.exc_info() or None)
if self.fp is not None:
try: self.fp.close()
except: pass
self.fp = None
class Timer(object):
'''Timer object used by SIP (rfc3261.Stack) and RTP (rfc3550.Session) among others.'''
def __init__(self, app):
self.app = app
self.delay, self.running, self.gen = 0, False, None
def start(self, delay=None):
if self.running: self.stop() # stop previous one first.
if delay is not None:
self.delay = delay # set the new delay
self.running = True
self.gen = gevent.spawn_later(self.delay / 1000.0, self.app.timedout, self)
def stop(self):
if self.running:
self.running = False
if self.gen:
try: self.gen.kill()
except: pass
self.gen = None
# -----------------------------------------------------------------------------
# Borrowed from voip.py after changing multitask to gevent
# -----------------------------------------------------------------------------
class User(object):
'''The User object provides a layer between the application and the SIP stack.'''
def __init__(self, sock, start=False):
'''Construct a new User on given bound socket for SIP signaling. Starts listening for messages if start is set.
'''
self.sock, self.sockaddr = sock, kutil.getlocaladdr(sock)
self._userListenerTask = self._userQueue = None
self.address = self.username = self.password = self.proxy = None
self.transport = rfc3261.TransportInfo(self.sock)
self.stack = rfc3261.Stack(self, self.transport) # create a SIP stack instance
self.reg = None # registration UAC
if _debug: print 'User created on listening=', sock.getsockname(), 'advertised=', self.sockaddr
if start:
self.start()
def __del__(self):
'''Destroy other internal references to Stack, etc.'''
self.stop()
self.reg = None
if self.stack: self.stack.app = None # TODO: since self.stack has a reference to this, __del__will never get called.
self.sock = self.stack = None
def start(self):
'''Start the listener, if not already started.'''
if self._userListenerTask is None:
self._userListenerTask = gevent.spawn(self._listener)
return self
def stop(self):
'''Stop the listener, if already present'''
if self._userListenerTask is not None:
self._userListenerTask.kill()
self._userListenerTask = None
return self
def _listener(self, maxsize=1500):
'''Listen for transport messages on the signaling socket. The default maximum
packet size to receive is 1500 bytes.'''
try:
while self.sock and self.stack:
data, remote = self.sock.recvfrom(maxsize)
if _debug: print 'received[%d] from %s\n%s'%(len(data),remote,data)
self.stack.received(data, remote)
except GreenletExit: pass
except: print 'User._listener exception', (sys and sys.exc_info() or None); traceback.print_exc(); raise
if _debug: print 'terminating User._listener()'
self._userListenerTask = None
#-------------------- binding related ---------------------------------
def bind(self, address, username=None, password=None, interval=180, refresh=False, update=False):
'''Register the local address with the server to receive incoming requests.
This is a generator function, and returns either ('success', None) for successful
registration or ('failed', 'reason') for a failure. The username and password
arguments are used to authenticate the registration. The interval argument
controls how long the registration is valid, and refresh if set to True causes
automatic refresh of registration before it expires.
If update is set to True then also update the self.transport.host with local address.uri.host.'''
if self.reg:
return ('failed', 'Already bound')
address = self.address = rfc2396.Address(str(address))
if not address.uri.scheme: address.uri.scheme = 'sip' # default scheme
self.username, self.password = username or self.username or address.uri.user, password or self.password
if update: self.transport.host = kutil.getintfaddr(address.uri.host)
reg = self.reg = self.createClient()
reg.queue = Queue()
result, reason = self._bind(interval=interval, refresh=refresh, wait=False)
if _debug: print 'received response', result
if result == 'failed': self.reg = None
return (result, reason)
def close(self):
'''Close the binding by unregistering with the SIP server.'''
if not self.reg:
return ('failed', 'not bound')
reg = self.reg
if reg.gen: reg.gen.kill(); reg.gen = None
result, reason = self._bind(interval=0, refresh=False, wait=False)
return (result, reason)
def _bind(self, interval, refresh, wait):
'''Internal function to perform bind and wait for response, and schedule refresh.'''
try:
if wait:
gevent.sleep(interval - min(interval*0.05, 5)) # refresh about 5 seconds before expiry
reg = self.reg
reg.sendRequest(self._createRegister(interval))
while True:
response = reg.queue.get()
if response.CSeq.method == 'REGISTER':
if response.is2xx: # success
if refresh: # install automatic refresh
if response.Expires:
interval = int(response.Expires.value)
if interval > 0:
reg.gen = gevent.spawn(self._bind, interval, refresh, True) # generator for refresh
return ('success', None)
elif response.isfinal: # failed
self.reg.gen = None; self.reg = None
return ('failed', str(response.response) + ' ' + response.responsetext)
except GreenletExit:
return ('failed', 'Greenlet closed')
def _createRegister(self, interval):
'''Create a REGISTER Message and populate the Expires and Contact headers. It assumes
that self.reg is valid.'''
if self.reg:
ua = self.reg
m = ua.createRegister(ua.localParty)
m.Contact = rfc3261.Header(str(self.stack.uri), 'Contact')
m.Contact.value.uri.user = ua.localParty.uri.user
m.Expires = rfc3261.Header(str(interval), 'Expires')
return m
else: return None
#-------------------------- Session related methods -------------------
def connect(self, dest, sdp=None, provisional=False):
'''Invite a remote destination to a session. This is a generator function, which
returns a (session, None) for successful connection and (None, reason) for failure.
Either mediasock or sdp must be present. If mediasock is present, then session is negotiated
for that mediasock socket, without SDP. Otherwise, the given sdp (rfc4566.SDP) is used
to negotiate the session. On success the returned Session object has mysdp and yoursdp
properties storing rfc4566.SDP objects in the offer and answer, respectively.'''
dest = rfc2396.Address(str(dest))
if not dest.uri:
return (None, 'invalid dest URI')
ua = self.createClient(dest)
ua.queue = Queue() # to receive responses
m = ua.createRequest('INVITE')
if sdp is not None:
m.body, local = str(sdp), None
m['Content-Type'] = rfc3261.Header('application/sdp', 'Content-Type')
else:
return (None, 'sdp must be supplied')
ua.sendRequest(m)
session, reason = self.continueConnect((ua, dest, sdp), provisional=provisional)
return (session, reason)
def continueConnect(self, context, provisional):
ua, dest, sdp = context
while True:
try:
response = ua.queue.get()
except GreenletExit: # connect was cancelled
ua.sendCancel()
raise
if response.response == 180 or response.response == 183:
context = (ua, dest, sdp)
return (context, "%d %s"%(response.response, response.responsetext))
if response.is2xx: # success
session = Session(user=self, dest=dest)
session.ua = hasattr(ua, 'dialog') and ua.dialog or ua
session.mysdp, session.yoursdp = sdp, None
if response.body and response['Content-Type'] and response['Content-Type'].value.lower() == 'application/sdp':
session.yoursdp = rfc4566.SDP(response.body)
session.start(True)
return (session, None)
elif response.isfinal: # some failure
return (None, str(response.response) + ' ' + response.responsetext)
def accept(self, arg, sdp=None):
'''Accept a incoming connection from given arg (dest, ua). The arg is what is supplied
in the 'connect' notification from recv() method's return value.'''
dest, ua = arg
m = ua.createResponse(200, 'OK')
ua.queue = Queue()
if sdp is not None:
m.body, local = str(sdp), None
m['Content-Type'] = rfc3261.Header('application/sdp', 'Content-Type')
else:
return (None, 'sdp must be supplied')
ua.sendResponse(m)
try:
while True:
request = ua.queue.get(timeout=5) # wait for 5 seconds for ACK
if request.method == 'ACK':
session, incoming = Session(user=self, dest=dest), ua.request
session.ua = hasattr(ua, 'dialog') and ua.dialog or ua
session.mysdp, session.yoursdp, session.local = sdp, None, local
session.remote= [(x.value.split(':')[0], int(x.value.split(':')[1])) for x in incoming.all('Candidate')] # store remote candidates
if incoming.body and incoming['Content-Type'] and incoming['Content-Type'].value.lower() == 'application/sdp':
session.yoursdp = rfc4566.SDP(incoming.body)
session.start(False)
return (session, None)
except Empty: pass
except GreenletExit: pass
return (None, 'didnot receive ACK')
def reject(self, arg, reason='486 Busy here'):
dest, ua = arg
code, sep, phrase = reason.partition(' ')
if code:
try: code = int(code)
except: pass
if not isinstance(code, int):
code = 603 # decline
phrase = reason
ua.sendResponse(ua.createResponse(code, phrase))
def sendIM(self, dest, message):
'''Send a paging-mode instant message to the destination and return ('success', None)
or ('failed', 'reason')'''
ua = self.createClient(dest)
ua.queue = Queue() # to receive responses
m = ua.createRequest('MESSAGE')
m['Content-Type'] = rfc3261.Header('text/plain', 'Content-Type')
m.body = str(message)
ua.sendRequest(m)
while True:
response = ua.queue.get()
if response.is2xx:
return ('success', None)
elif response.isfinal:
return ('failed', str(response.response) + ' ' + response.responsetext)
#-------------------------- generic event receive ---------------------
def recv(self, timeout=None):
if self._userQueue is None: self._userQueue = Queue()
return self._userQueue.get(timeout=timeout)
#-------------------------- Interaction with SIP stack ----------------
# Callbacks invoked by SIP Stack
def createServer(self, request, uri, stack):
'''Create a UAS if the method is acceptable. If yes, it also adds additional attributes
queue and gen in the UAS.'''
ua = request.method in ['INVITE', 'BYE', 'ACK', 'MESSAGE'] and rfc3261.UserAgent(self.stack, request) or None
if ua: ua.queue = ua.gen = None
if _debug: print 'createServer', ua
return ua
def createClient(self, dest=None):
'''Create a UAC and add additional attributes: queue and gen.'''
ua = rfc3261.UserAgent(self.stack)
ua.queue = ua.gen = None
ua.localParty = self.address and self.address.dup() or None
ua.remoteParty = dest and dest.dup() or self.address and self.address.dup() or None
ua.remoteTarget= dest and dest.uri.dup() or self.address and self.address.uri.dup() or None
ua.routeSet = self.proxy and [rfc3261.Header(str(self.proxy), 'Route')] or None
if ua.routeSet and not ua.routeSet[0].value.uri.user: ua.routeSet[0].value.uri.user = ua.remoteParty.uri.user
if _debug: print 'createClient', ua
return ua
def sending(self, ua, message, stack):
pass
def receivedRequest(self, ua, request, stack):
'''Callback when received an incoming request.'''
if _debug: print 'receivedRequest method=', request.method, 'ua=', ua, ' for ua', (ua.queue is not None and 'with queue' or 'without queue')
if hasattr(ua, 'queue') and ua.queue is not None:
ua.queue.put(request)
elif request.method == 'INVITE': # a new invitation
if self._userQueue is not None:
self._userQueue.put(('connect', (str(request.From.value), ua)))
else:
ua.sendResponse(405, 'Method not allowed')
elif request.method == 'MESSAGE': # a paging-mode instant message
if request.body and self._userQueue:
ua.sendResponse(200, 'OK') # blindly accept the message
self._userQueue.put(('send', (str(request.From.value), request.body)))
else:
ua.sendResponse(405, 'Method not allowed')
elif request.method == 'CANCEL':
# TODO: non-dialog CANCEL comes here. need to fix rfc3261 so that it goes to cancelled() callback.
if ua.request.method == 'INVITE': # only INVITE is allowed to be cancelled.
self._userQueue.put(('close', (str(request.From.value), ua)))
else:
ua.sendResponse(405, 'Method not allowed')
def receivedResponse(self, ua, response, stack):
'''Callback when received an incoming response.'''
if _debug: print 'receivedResponse response=', response.response, ' for ua', (ua.queue is not None and 'with queue' or 'without queue')
if hasattr(ua, 'queue') and ua.queue is not None: # enqueue it to the ua's queue
ua.queue.put(response)
if _debug: print 'response put in the ua queue'
else:
if _debug: print 'ignoring response', response.response
def cancelled(self, ua, request, stack):
'''Callback when given original request has been cancelled by remote.'''
if hasattr(ua, 'queue') and ua.queue is not None:
ua.queue.put(request)
elif self._userQueue is not None and ua.request.method == 'INVITE': # only INVITE is allowed to be cancelled.
self._userQueue.put(('close', (str(request.From.value), ua)))
def dialogCreated(self, dialog, ua, stack):
dialog.queue = ua.queue
dialog.gen = ua.gen
ua.dialog = dialog
if _debug: print 'dialogCreated from', ua, 'to', dialog
# else ignore this since I don't manage any dialog related ua in user
def authenticate(self, ua, obj, stack):
'''Provide authentication information to the UAC or Dialog.'''
obj.username, obj.password = self.username, self.password
return bool(obj.username and obj.password)
def createTimer(self, app, stack):
'''Callback to create a timer object.'''
return Timer(app)
# rfc3261.Transport related methods
def send(self, data, addr, stack):
'''Send data to the remote addr.'''
if _debug: print 'sending[%d] to %s\n%s'%(len(data), addr, data)
if self.sock:
try: self.sock.sendto(data, addr)
except socket.error:
if _debug: print 'socket error in sending'
class Session(object):
'''The Session object represents a single session or call between local User and remote
dest (Address).'''
def __init__(self, user, dest):
self.user, self.dest = user, dest
self.ua = self.local = self.remote = self._sessionRunTask = self.remotemediaaddr = None
self._sessionQueue = Queue()
def start(self, outgoing):
'''A generator function to initiate the connectivity check and then start the run
method to receive messages on this ua.'''
self._sessionRunTask = gevent.spawn(self._run)
def send(self, message):
if self.ua:
ua = self.ua
m = ua.createRequest('MESSAGE')
m['Content-Type'] = rfc3261.Header('text/plain', 'Content-Type')
m.body = str(message)
ua.sendRequest(m)
def recv(self, timeout=None):
return self._sessionQueue.get(timeout=timeout)
def close(self, outgoing=True):
'''Close the call and terminate any generators.'''
self.local = self.remote = None
if self._sessionRunTask is not None: # close the generator
try:
self._sessionRunTask.kill()
except GreenletExit:
pass
self._sessionRunTask = None
if self.ua: