-
Notifications
You must be signed in to change notification settings - Fork 0
/
RtspTypes.pas
552 lines (493 loc) · 13.1 KB
/
RtspTypes.pas
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
unit RtspTypes;
interface
uses
Classes, SysUtils, Windows, Sockets, WinSock;
type
TRtspHeader = class;
TRtspHeaders = array of TRtspHeader;
TRtspTransportHeader = class;
TRtspResource = class
public
Name: String;
Host: TSocketHost;
Port: TSocketPort;
constructor Create(const RtspAddress: String);
procedure Parse(const RtspAddress: String);
function ToString: String;
end;
TRtspResourceCatalog = class
private
FLocker: TRTLCriticalSection;
FResources: TStrings;
public
constructor Create;
destructor Destroy; override;
procedure PrintAll;
procedure Lock;
procedure Unlock;
procedure AppendResource(const Name, RtspAddress: String);
procedure RemoveResource(const Name: String);
function GetResource(const Name: String): TRtspResource;
end;
TRtspMessage = class
private
FAddress: TSocketHost;
FPort: TSocketPort;
FResource: String;
FContent: String;
FMethod: String;
FIsResponce: Boolean;
FErrorCode: String;
FReasonPhrase: String;
FCseq: String;
FContentLength: Integer;
FHeaders: TRtspHeaders;
procedure ParsePacket(const APacket: String);
procedure ParseFirstLine(const Line: String);
procedure AddHeader(const AHeader: String; const AValue: String); overload;
procedure AddHeader(AHeader: TRtspHeader); overload;
function ExtractMessage(const APacket: String): String;
public
constructor Create(const APacket: String);
destructor Destroy; override;
function GetTransportHeader: TRtspTransportHeader;
function HeaderToString: String;
procedure ReplaceAll(const Source: String; const Dest: String);
property Method: String read FMethod;
property Address: TSocketHost read FAddress write FAddress;
property Port: TSocketPort read FPort write FPort;
property Resource: String read FResource write FResource;
property ContentLength: Integer read FContentLength;
property Content: String read FContent write FContent;
end;
TRtspHeader = class
public
Header: String;
Value: String;
function ToString: String; virtual;
end;
TRtspTransportHeader = class(TRtspHeader)
private
procedure ParsePorts(const S: String; out Port1: String; out Port2: String);
public
ClientPortData: String;
ClientPortSync: String;
ServerPortData: String;
ServerPortSync: String;
Values: array of string;
constructor Create(const AValue: String);
function ToString: String; override;
end;
ESocketError = class(Exception)
public
ErrorCode: Integer;
constructor Create; reintroduce; overload;
constructor Create(const Msg: String); overload;
end;
const
DefaultPort = '554';
RtspPrefix = 'rtsp://';
RtspVersion = 'RTSP/1.0';
HeaderCseq = 'CSeq';
HeaderContentLen = 'Content-Length';
HeaderUserAgent = 'User-Agent';
HeaderTransport = 'Transport';
var
Resources: TRtspResourceCatalog;
implementation
uses
StrUtils, Log;
{$region 'ESocketError'}
constructor ESocketError.Create;
begin
ErrorCode := WSAGetLastError;
inherited Create('');
end;
constructor ESocketError.Create(const Msg: String);
begin
ErrorCode := WSAGetLastError;
inherited;
end;
{$endregion}
{$region 'TRtspResource'}
constructor TRtspResource.Create(const RtspAddress: String);
begin
Parse(RtspAddress);
end;
procedure TRtspResource.Parse(const RtspAddress: String);
var
Index: Integer;
Address: String;
begin
if not AnsiStartsText(RtspPrefix, RtspAddress) then
raise Exception.Create('Bad RTSP address: ' + RtspAddress);
Address := Copy(RtspAddress, 8, MaxInt);
Index := Pos(':', Address);
if Index > 0 then
begin
Host := Copy(Address, 1, Index-1);
Address := Copy(Address, Index+1, MaxInt);
Index := Pos('/', Address);
if Index > 0 then
begin
Port := Copy(Address, 1, Index-1);
Name := Copy(Address, Index+1, MaxInt);
end;
end
else
begin
Port := DefaultPort;
Index := Pos('/', Address);
if Index > 0 then
begin
Host := Copy(Address, 0, Index-1);
Name := Copy(Address, Index+1, MaxInt);
end;
end;
Host := Trim(Host);
Name := Trim(Name);
// Ìû íå ìîæåì ðàáîòàòü ñ àäðåñîì * èëè ñ àäðåñîì áåç èìåíè ðåñóðñà
// (íàïðèìåð, âñòðå÷àåòñÿ òàêîå "OPTIONS 192.168.5.4:554 RTSP/1.0")
// ò.ê. â ýòîì ñëó÷àå íåâîçìîæíî îïðåäåëèòü íà êàêîé ñåðâåð
// ïåðåíàïðàâèòü çàïðîñ. Âåäü â îáùåì ñëó÷àå èõ ìîæåò áûòü íåñêîëüêî.
if (Host = '') or (Name = '') then
raise Exception.Create('Bad RTSP address: ' + RtspAddress);
end;
function TRtspResource.ToString: String;
begin
Result := Format('%s%s:%s/%s', [RtspPrefix, Host, Port, Name]);
end;
{$endregion}
{$region 'TRtspMessage'}
constructor TRtspMessage.Create(const APacket: String);
begin
FPort := DefaultPort;
ParsePacket(APacket);
end;
destructor TRtspMessage.Destroy;
var
I: Integer;
begin
for I := 0 to Length(FHeaders)-1 do
FHeaders[I].Free;
inherited;
end;
procedure TRtspMessage.ParsePacket(const APacket: String);
var
Lines: TStrings;
Packet: String;
Index: Integer;
Line, Header, Value: String;
begin
Packet := ExtractMessage(APacket);
Lines := TStringList.Create;
try
Lines.Text := Packet;
if Lines.Count > 0 then
begin
ParseFirstLine(Lines[0]);
Lines.Delete(0);
end;
for Line in Lines do
begin
Index := Pos(':', Line);
if Index = 0 then
raise Exception.Create('Invalid line in RTSP message header: ' + Line);
Header := Trim(Copy(Line, 1, Index-1));
Value := Trim(Copy(Line, Index+1, MaxInt));
if AnsiSameText(Header, HeaderCseq) then
FCseq := Value
else if AnsiSameText(Header, HeaderContentLen) then
FContentLength := StrToInt(Value)
else if AnsiSameText(Header, HeaderTransport) then
AddHeader(TRtspTransportHeader.Create(Value))
else
AddHeader(Header, Value);
end;
if Length(FContent) > FContentLength then
raise Exception.CreateFmt('Invalid content length of RTSP message. ' +
'Expected: %d bytes, got: %d bytes', [FContentLength, Length(FContent)]);
finally
Lines.Free;
end;
end;
function TRtspMessage.ExtractMessage(const APacket: String): String;
var
Index: Integer;
begin
Index := Pos(#$D#$A#$D#$A, APacket);
if Index > 0 then
begin
FContent := Copy(APacket, Index+4, MaxInt);
Result := Copy(APacket, 1, Index-1);
end
else
Result := APacket;
end;
procedure TRtspMessage.ParseFirstLine(const Line: String);
var
Index: Integer;
Source: String;
Res: TRtspResource;
begin
Source := Line;
Index := Pos(' ', Source);
if Index = 0 then
raise Exception.Create('Invalid request or status line: ' + Line);
FMethod := Copy(Source, 1, Index-1);
Source := Copy(Source, Index+1, MaxInt);
Index := Pos(' ', Source);
if Index = 0 then
raise Exception.Create('Invalid request or status line: ' + Line);
if FMethod = RtspVersion then
begin // status line
FIsResponce := True;
FErrorCode := Copy(Source, 1, Index-1);
FReasonPhrase := Copy(Source, Index+1, MaxInt);
end
else
begin // request line
Res := TRtspResource.Create(Copy(Source, 1, Index-1));
FAddress := Res.Host;
FPort := Res.Port;
FResource := Res.Name;
Res.Free;
end;
end;
procedure TRtspMessage.AddHeader(const AHeader: String; const AValue: String);
var
Header: TRtspHeader;
begin
Header := TRtspHeader.Create;
Header.Header := AHeader;
Header.Value := AValue;
AddHeader(Header);
end;
procedure TRtspMessage.AddHeader(AHeader: TRtspHeader);
var
L: Integer;
begin
L := Length(FHeaders);
SetLength(FHeaders, L+1);
FHeaders[L] := AHeader;
end;
function TRtspMessage.GetTransportHeader: TRtspTransportHeader;
var
Header: TRtspHeader;
begin
for Header in FHeaders do
if Header is TRtspTransportHeader then
begin
Result := Header as TRtspTransportHeader;
Exit;
end;
Result := nil;
end;
procedure TRtspMessage.ReplaceAll(const Source: String; const Dest: String);
var
Header: TRtspHeader;
begin
for Header in FHeaders do
Header.Value := AnsiReplaceText(Header.Value, Source, Dest);
if FContent <> '' then
FContent := AnsiReplaceText(FContent, Source, Dest);
end;
function TRtspMessage.HeaderToString: String;
var
Strs: TStrings;
Header: TRtspHeader;
begin
Strs := TStringList.Create;
try
if FIsResponce then
Strs.Append(Format('%s %s %s', [RtspVersion, FErrorCode, FReasonPhrase]))
else
begin
if (FAddress = '') or (FResource = '') then
Strs.Append(Format('%s * %s', [FMethod, RtspVersion]))
else
Strs.Append(Format('%s rtsp://%s:%s/%s %s',
[FMethod, FAddress, FPort, FResource, RtspVersion]));
end;
Strs.Append(HeaderCseq + ': ' + FCseq);
if FContent <> '' then
Strs.Append(HeaderContentLen + ': ' + IntToStr(Length(FContent)));
for Header in FHeaders do
Strs.Append(Header.ToString);
Strs.Append('');
Result := Strs.Text;
finally
Strs.Free;
end;
end;
{$endregion}
{$region 'TRtspHeader'}
function TRtspHeader.ToString: String;
begin
Result := Header + ': ' + Value;
end;
{$endregion}
{$region 'TRtspTransportHeader'}
constructor TRtspTransportHeader.Create(const AValue: String);
var
Strs: TStrings;
S: String;
L: Integer;
begin
Header := HeaderTransport;
Value := AValue;
Strs := TStringList.Create;
try
Strs.Delimiter := ';';
Strs.DelimitedText := AValue;
for S in Strs do
begin
if AnsiStartsText('client_port', S) then
ParsePorts(S, ClientPortData, ClientPortSync)
else if AnsiStartsText('server_port', S) then
ParsePorts(S, ServerPortData, ServerPortSync)
else
begin
L := Length(Values);
SetLength(Values, L+1);
Values[L] := S;
end;
end;
finally
Strs.Free;
end;
end;
procedure TRtspTransportHeader.ParsePorts(const S: String; out Port1: String; out Port2: String);
var
Index: Integer;
Ports: String;
begin
Index := Pos('=', S);
if Index > 0 then
begin
Ports := Copy(S, Index+1, MaxInt);
Index := Pos('-', Ports);
if Index > 0 then
begin
Port1 := Trim(Copy(Ports, 1, Index-1));
Port2 := Trim(Copy(Ports, Index+1, MaxInt));
Exit;
end;
end;
raise Exception.Create('Unable to extract port numbers from Transport header');
end;
function TRtspTransportHeader.ToString: String;
var
S: String;
begin
Result := HeaderTransport + ': ';
for S in Values do
begin
if AnsiStartsText('source=', S) then Continue;
if AnsiStartsText('destination=', S) then Continue;
Result := Result + S + ';';
end;
if (ClientPortData <> '') and (ClientPortSync <> '') then
Result := Result + Format('client_port=%s-%s;', [ClientPortData, ClientPortSync]);
if (ServerPortData <> '') and (ServerPortSync <> '') then
Result := Result + Format('server_port=%s-%s;', [ServerPortData, ServerPortSync]);
SetLength(Result, Length(Result)-1);
end;
{$endregion}
{$region 'TRtspResourceCatalog'}
constructor TRtspResourceCatalog.Create;
begin
InitializeCriticalSection(FLocker);
FResources := TStringList.Create;
end;
destructor TRtspResourceCatalog.Destroy;
var
I: Integer;
begin
for I := 0 to FResources.Count-1 do
FResources.Objects[I].Free;
FResources.Free;
DeleteCriticalSection(FLocker);
inherited;
end;
procedure TRtspResourceCatalog.Lock;
begin
EnterCriticalSection(FLocker);
end;
procedure TRtspResourceCatalog.Unlock;
begin
LeaveCriticalSection(FLocker);
end;
procedure TRtspResourceCatalog.AppendResource(const Name, RtspAddress: String);
var
Index: Integer;
Res: TRtspResource;
begin
Res := TRtspResource.Create(RtspAddress);
Lock;
try
Index := FResources.IndexOf(Name);
if Index < 0 then
begin
FResources.AddObject(Name, Res);
WriteLine('Resource added: %s <-> %s', [Name, Res.ToString]);
end
else
begin
FResources.Objects[Index].Free;
FResources.Objects[Index] := Res;
WriteLine('Resource updated: %s <-> %s', [Name, Res.ToString]);
end;
finally
Unlock;
end;
end;
procedure TRtspResourceCatalog.RemoveResource(const Name: String);
var
Index: Integer;
Res: TRtspResource;
begin
Lock;
try
Index := FResources.IndexOf(Name);
if Index >= 0 then
begin
Res := TRtspResource(FResources.Objects[Index]);
FResources.Delete(Index);
WriteLine('Resource removed: %s <-> %s', [Name, Res.ToString]);
Res.Free;
end;
finally
Unlock;
end;
end;
function TRtspResourceCatalog.GetResource(const Name: String): TRtspResource;
var
Index: Integer;
begin
// GetResource äîëæåí áëîêèðîâàòüñÿ ñíàðóæè, òàì ãäå îí âûçûâàåòñÿ,
// íà âñå âðåìÿ èñïîëüçîâàíèÿ ïîëó÷åííîãî ðåñóðñà
Index := FResources.IndexOf(Name);
if Index >= 0
then Result := TRtspResource(FResources.Objects[Index])
else Result := nil;
end;
procedure TRtspResourceCatalog.PrintAll;
var
I: Integer;
Res: TRtspResource;
begin
for I := 0 to FResources.Count-1 do
begin
Res := TRtspResource(FResources.Objects[I]);
WriteLn(Format('%s -> %s:%s/%s', [FResources[I], Res.Host, Res.Port, Res.Name]));
end;
if FResources.Count = 0 then
WriteLn('Resources were not added');
end;
{$endregion}
initialization
Resources := TRtspResourceCatalog.Create;
finalization
Resources.Free;
end.