-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathManager.cs
More file actions
1595 lines (1335 loc) · 52.3 KB
/
Manager.cs
File metadata and controls
1595 lines (1335 loc) · 52.3 KB
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
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using System.Configuration;
namespace JMS.DVB.TS
{
/// <summary>
/// A single transport stream.
/// </summary>
public class Manager : IDisposable, IStreamConsumer2
{
/// <summary>
/// Die Voreinstellung für die Größe des Zwischenspeichers beim Schreiben in Dateien.
/// </summary>
public const int DefaultBufferSize = 2000000;
/// <summary>
/// Delegate to receive any data in process.
/// </summary>
public Action<byte[]> InProcessConsumer = null;
/// <summary>
/// The delay the created PCR advances the corresponding PTS of
/// a video sequence header.
/// </summary>
/// <remarks>
/// The default value <i>90 * 1000</i> lets the PCR run one second
/// before the PTS since the reference clock is 90kHz.
/// </remarks>
public static long PCRDelay = 90000;
/// <summary>
/// Kann gesetzt werden, um zu verhindern, dass die Systemzeit (PCR) aus dem
/// H.264 Bildsignal abgeleitet wird.
/// </summary>
public static bool DisablePCRForHDTV = false;
/// <summary>
/// Kann gesetzt werden, um zu verhindern, dass die Systemzeit (PCR) aus dem
/// MPEG2 Bildsignal abgeleitet wird.
/// </summary>
public static bool DisablePCRForSDTV = false;
/// <summary>
/// The video delay to use.
/// </summary>
/// <remarks>
/// The default is <i>-90 * 666</i> which makes up 2 /3 seconds
/// on the 90kHz PTS clock. A negative value makes sure that video
/// data will be available before the corresponding audio data is
/// put into the transport stream.
/// </remarks>
public static long VideoDelay = -60000;
/// <summary>
/// If active the PES length of video packets will be calculated.
/// </summary>
public static bool SetVideoLength = true;
/// <summary>
/// Set the service identification for EPG injection.
/// </summary>
public SourceIdentifier EPGMapping = null;
/// <summary>
/// Just in case we send EPG data into the stream.
/// </summary>
private int m_EPGCounter = 0;
/// <summary>
/// The number of hops multicasting can use - the default is <i>1</i>
/// restricting multicast packets to the local network.
/// </summary>
public static readonly int MulticastTTL = 1;
/// <summary>
/// Maximale Anzahl von aufgestauten UDP Paketen - etwa 10 MByte pro
/// TS Datenstrom.
/// </summary>
public static readonly int MaxUDPQueueLength = 1250;
/// <summary>
/// Delay for this transport stream - will be doubled for HDTV.
/// </summary>
private long m_PCRDelay;
/// <summary>
/// Wird gesetzt um zu verhindern, dass aus dem H.264 Datenstrom die Zeitbasis (PCR)
/// abgeleitet wird.
/// </summary>
private bool m_NoHDTVPCR;
/// <summary>
/// Wird gesetzt um zu verhindern, dass aus dem MPEG2 Datenstrom die Zeitbasis (PCR)
/// abgeleitet wird.
/// </summary>
private bool m_NoSDTVPCR;
/// <summary>
/// Delay for this transport stream - will be doubled for HDTV.
/// </summary>
private long m_VideoDelay;
private UDPStreaming m_UDPStream = new UDPStreaming(MulticastTTL, MaxUDPQueueLength);
/// <summary>
/// Set as soon as the first PCR arrived.
/// </summary>
private int m_PCRAvailable = 0;
/// <summary>
/// Collects full PES packets per stream.
/// </summary>
/// <remarks>
/// The map is indexed with the transport stream identifier.
/// </remarks>
private Hashtable m_Buffers = new Hashtable();
/// <summary>
/// The <see cref="PVASplitter"/> needs a PTS guidance since PVA
/// only works with 32-Bit PTS.
/// </summary>
private PVASplitter m_Splitter = null;
/// <summary>
/// The stream which guides the <see cref="PVASplitter"/> to use
/// the correct PTS.
/// </summary>
private short m_GuidePID = 0;
/// <summary>
/// Helper buffer holding <i>0xff</i> padding bytes for a whole transport stream
/// packet.
/// </summary>
private static byte[] Padding = new byte[PacketSize];
/// <summary>
/// Full size of a transport stream packet - 188 bytes.
/// </summary>
public const int FullSize = 4 + PacketSize;
/// <summary>
/// Maximum payload size for a transport stream packet - 184 bytes.
/// </summary>
public const int PacketSize = 184;
/// <summary>
/// All our streams.
/// </summary>
private ArrayList m_Streams = new ArrayList();
/// <summary>
/// The <see cref="Tables.PAT"/> for this transport stream - there can be only
/// a single program in it.
/// </summary>
private Tables.PAT ProgramAssociation;
/// <summary>
/// Next transport stream identifier for automatic generation.
/// <seealso cref="AddStream"/>
/// </summary>
public short NextPID = 0x0200;
/// <summary>
/// The <see cref="Tables.PMT"/> for the only program in this transport stream.
/// </summary>
private Tables.PMT ProgramMap;
/// <summary>
/// The service description for the only program included.
/// </summary>
private Tables.SDT ServiceDescription;
/// <summary>
/// Number of bytes processed.
/// </summary>
private long m_Length = 0;
/// <summary>
/// Number of Audio/Video bytes processed.
/// </summary>
private long m_AVLength = 0;
/// <summary>
/// The number of transport stream packets sent after the last PAT/PMT.
/// </summary>
private int PacketCounter = 0;
/// <summary>
/// Set when the PAT/PMT have been sent - reset after 1000 other packets are
/// added to the transport stream.
/// </summary>
private bool PATSent = false;
/// <summary>
/// The output stream - typically a disk file.
/// </summary>
private Stream Target;
/// <summary>
/// Das aktuelle Ziel für alle Schreiboperationen.
/// </summary>
private DoubleBufferedFile BufferedTarget;
/// <summary>
/// Eine neue Datei, in die bei der nächsten Schreiboperation umgeschaltet werden soll.
/// </summary>
private DoubleBufferedFile PendingTarget;
/// <summary>
/// Currently active operation
/// </summary>
private IAsyncResult m_Writer = null;
/// <summary>
/// For the moment a synchronizer only.
/// </summary>
private object m_Queue = new object();
/// <summary>
/// Set when a HDTV video stream is added.
/// </summary>
private bool m_IsHDTV = false;
/// <summary>
/// Wird aktiviert, sobald die Systemuhr in eine Datei geschrieben wird.
/// </summary>
public Action<string, long, byte[]> OnWritingPCR;
/// <summary>
/// Die Größe des Zwischenspeichers für das Schreiben in Dateien.
/// </summary>
private int m_BufferSize = DefaultBufferSize;
/// <summary>
/// When set no data will be accepted in the corresponding streams.
/// </summary>
public bool IgnoreInput = false;
/// <summary>
/// Initialisiert statische Daten der Klasse.
/// </summary>
static Manager()
{
// Create padding
for (int i = Padding.Length; i-- > 0;)
Padding[i] = 0xff;
// Check settings
var videoLength = ConfigurationManager.AppSettings["TS.SetVideoLength"];
var noHDTVPCR = ConfigurationManager.AppSettings["TS.DisableHDTVPCR"];
var noSDTVPCR = ConfigurationManager.AppSettings["TS.DisableSDTVPCR"];
var maxUDPQueue = ConfigurationManager.AppSettings["TS.MaxUDPQueue"];
var videoDelay = ConfigurationManager.AppSettings["TS.VideoDelay"];
var multiTTL = ConfigurationManager.AppSettings["Multicast.TTL"];
var pcrDelay = ConfigurationManager.AppSettings["TS.PCRDelay"];
// Overwrite
if (!string.IsNullOrEmpty(pcrDelay))
PCRDelay = long.Parse(pcrDelay);
if (!string.IsNullOrEmpty(videoDelay))
VideoDelay = long.Parse(videoDelay);
if (!string.IsNullOrEmpty(multiTTL))
MulticastTTL = int.Parse(multiTTL);
if (!string.IsNullOrEmpty(videoLength))
SetVideoLength = bool.Parse(videoLength);
if (!string.IsNullOrEmpty(maxUDPQueue))
MaxUDPQueueLength = int.Parse(maxUDPQueue);
if (!string.IsNullOrEmpty(noHDTVPCR))
DisablePCRForHDTV = bool.Parse(noHDTVPCR);
if (!string.IsNullOrEmpty(noSDTVPCR))
DisablePCRForSDTV = bool.Parse(noSDTVPCR);
}
/// <summary>
/// Create a transport stream with no attached physical file.
/// </summary>
public Manager()
: this((Stream)null)
{
}
/// <summary>
/// Create a transport stream on a <see cref="Stream"/>.
/// </summary>
/// <param name="target">Typically a disk file.</param>
public Manager(Stream target)
: this(target, 0)
{
}
/// <summary>
/// Erzeugt einen neuen Datenstrom.
/// </summary>
/// <param name="path">Optional der volle Pfad zu einer Datei.</param>
public Manager(string path)
: this(path, 0)
{
}
/// <summary>
/// Create a transport stream on a file.
/// </summary>
/// <param name="path">Path to the file.</param>
/// <param name="nextPID">Optional initial PID counter.</param>
public Manager(string path, short nextPID)
: this(path, nextPID, DefaultBufferSize)
{
}
/// <summary>
/// Erzeugt einen neuen Datenstrom.
/// </summary>
/// <param name="path">Optional der volle Pfad zu einer Datei.</param>
/// <param name="nextPID">Die als nächstes zu verwendende Datenstromkennung.</param>
/// <param name="bufferSize">Die Größe des zu verwendenden Zwischenspeichers.</param>
/// <exception cref="ArgumentOutOfRangeException">Der Zwischenspeicher muss mindestens 1.000 Bytes groß sein.</exception>
public Manager(string path, short nextPID, int bufferSize)
: this((Stream)null, nextPID)
{
// Validate
if (bufferSize <= 1000)
throw new ArgumentOutOfRangeException("bufferSize");
// Remember
m_BufferSize = bufferSize;
// Open the file
if (path != null)
BufferedTarget = CreateBuffered(path);
}
/// <summary>
/// Erzeugt einen neuen, doppelt gepufferten Bereich für das Schreiben in eine Datei.
/// </summary>
/// <param name="filePath">Der volle Pfad zur Datei.</param>
/// <returns>Der gewünschte Speicherbereich.</returns>
private DoubleBufferedFile CreateBuffered(string filePath)
{
// Process
return new DoubleBufferedFile(filePath, m_BufferSize);
}
/// <summary>
/// Prüft, ob eine nahtlose Auftrennung der Aufzeichnungsdatei unterstützt wird.
/// </summary>
public bool CanSplitFile
{
get
{
// Check mode of operation
if (BufferedTarget != null)
if (Target == null)
return true;
// Nope
return false;
}
}
/// <summary>
/// Beginnt bei nächster Gelegenheit mit dem Beschreiben einer neuen Datei.
/// </summary>
/// <param name="newFilePath">Der volle Pfad zur gewünschten Zieldatei.</param>
/// <exception cref="ArgumentNullException">Es wurde keine Zieldatei angegeben.</exception>
public void SplitFile(string newFilePath)
{
// Validate
if (string.IsNullOrEmpty(newFilePath))
throw new ArgumentNullException("newFilePath");
// Check mode of operation
if (!CanSplitFile)
throw new InvalidOperationException();
// Create new file and install it
using (Interlocked.Exchange(ref PendingTarget, CreateBuffered(newFilePath)))
{
// The new target is now installed and the previous one will be discarded unused - if any existed
}
}
/// <summary>
/// Create a transport stream on a <see cref="Stream"/>.
/// </summary>
/// <param name="target">Typically a disk file.</param>
/// <param name="nextPID">Optional initial PID counter.</param>
public Manager(Stream target, short nextPID)
{
// Fix delay
m_NoHDTVPCR = DisablePCRForHDTV;
m_NoSDTVPCR = DisablePCRForSDTV;
m_VideoDelay = VideoDelay;
m_PCRDelay = PCRDelay;
// Use
if ((nextPID >= 0x200) && (nextPID <= 0xf80))
NextPID = nextPID;
// Remember
Target = target;
// Create helper
ProgramAssociation = new Tables.PAT();
// Configure
ProgramAssociation.ProgramStream = NextPID++;
ProgramAssociation.ProgramNumber = NextPID++;
// Create helper
ProgramMap = new Tables.PMT(ProgramAssociation.ProgramStream, ProgramAssociation.ProgramNumber);
ServiceDescription = new Tables.SDT(ProgramAssociation.NetworkIdentifier, ProgramAssociation.ProgramNumber);
}
/// <summary>
/// Allow us to enforce changes on the PAT version stamp.
/// </summary>
public int PATVersion
{
get
{
// Forward
return ProgramAssociation.TableVersion;
}
set
{
// Update
ProgramAssociation.TableVersion = value;
}
}
/// <summary>
/// Send PAT/PMT to the transport stream if necessary.
/// </summary>
private void SendPAT()
{
// Must synchronize
lock (m_Queue)
{
// Already done
if (PATSent) return;
// Reset
PacketCounter = 0;
PATSent = true;
// Forward
ProgramAssociation.Send(this);
ProgramMap.Send(this);
//ServiceDescription.Send(this);
}
}
/// <summary>
/// Send a table to the transport stream.
/// </summary>
/// <param name="counter">Individual packet counter.</param>
/// <param name="pid">Transport stream identifier to use.</param>
/// <param name="buffer">Full table data.</param>
public void SendTable(ref int counter, int pid, byte[] buffer)
{
// Get the chunks
int packs = (buffer.Length + PacketSize - 1) / PacketSize;
int rest = buffer.Length % PacketSize;
// Forward
Send(ref counter, pid, buffer, 0, packs, true, (0 == rest) ? PacketSize : rest, true, -1);
}
/// <summary>
/// Create a new video stream and add it to this transport stream.
/// </summary>
/// <param name="encoding">Encoding of the video stream.</param>
/// <returns>The newly created video stream instance.</returns>
public VideoStream AddVideo(byte encoding)
{
// Forward
return AddVideo(encoding, false);
}
/// <summary>
/// Create a new video stream and add it to this transport stream.
/// </summary>
/// <param name="encoding">Encoding of the video stream.</param>
/// <param name="noPCR">Set to disable PCR generation.</param>
/// <returns>The newly created video stream instance.</returns>
public VideoStream AddVideo(byte encoding, bool noPCR)
{
// Check mode
var isH264 = (encoding == (byte)EPG.StreamTypes.H264);
var forbidPCR = (m_NoHDTVPCR && isH264) || (m_NoSDTVPCR && !isH264);
// Run
bool isPCR;
short pid = AddStream(StreamTypes.Video, encoding, noPCR || forbidPCR, false, null, null, out isPCR);
// Create the correct type of stream
VideoStream video;
if (isH264)
{
// Remember
m_IsHDTV = true;
// H.264
video = new HDTVStream(this, pid, isPCR);
}
else
{
// MPEG-2
video = new VideoStream(this, pid, isPCR);
}
// Remember
m_Streams.Add(video);
// Report
return video;
}
/// <summary>
/// Report if this Transport Stream includes a H.264 video stream.
/// </summary>
public bool HasHDTVVideo => m_IsHDTV;
/// <summary>
/// Create a new audio stream and add it to this transport stream.
/// </summary>
/// <param name="name">The ISO name of the language for this audio stream.</param>
/// <returns>The newly created audio stream instance.</returns>
public AudioStream AddAudio(string name) => AddAudio(name, null);
/// <summary>
/// Create a new audio stream and add it to this transport stream.
/// </summary>
/// <param name="name">The ISO name of the language for this audio stream.</param>
/// <param name="aac">Optional AAC Profile, level and type.</param>
/// <returns>The newly created audio stream instance.</returns>
public AudioStream AddAudio(string name, ushort? aac)
{
// Flag
bool isPCR;
// Run
short pid = AddStream(StreamTypes.Audio, 255, false, false, null, aac, out isPCR);
// Set the name of the language
if (!string.IsNullOrEmpty(name)) ProgramMap.SetAudioLanguage(pid, name);
// Create
AudioStream audio = new AudioStream(this, pid, isPCR);
// Remember
m_Streams.Add(audio);
// Make it the guide
if ((null != m_Splitter) && (0 == m_GuidePID)) m_GuidePID = pid;
// Report
return audio;
}
/// <summary>
/// Add a new Dolby Digital Audio Stream to this <i>Transport Stream</i>.
/// </summary>
/// <returns>The new data stream.</returns>
public DolbyStream AddDolby() => AddDolby(null);
/// <summary>
/// Create a new Dobly Digital (AC3) audio stream and add it to this transport stream.
/// </summary>
/// <returns>The newly created AC3 audio stream instance.</returns>
public DolbyStream AddDolby(string name)
{
// Flag
bool isPCR;
// Run
short pid = AddStream(StreamTypes.Private, 255, false, false, null, null, out isPCR);
// Set the name of the language
if (!string.IsNullOrEmpty(name)) ProgramMap.SetAudioLanguage(pid, name);
// Create
DolbyStream dolby = new DolbyStream(this, pid, isPCR);
// Remember
m_Streams.Add(dolby);
// Make it the guide
if ((null != m_Splitter) && (0 == m_GuidePID)) m_GuidePID = pid;
// Report
return dolby;
}
/// <summary>
/// Create a new teletext stream and add it to this transport stream.
/// </summary>
/// <returns>The newly created teletext stream instance.</returns>
public TTXStream AddTeleText()
{
// Flag
bool isPCR;
// Run
short pid = AddStream(StreamTypes.TeleText, 255, false, true, null, null, out isPCR);
// Create
TTXStream ttx = new TTXStream(this, pid, isPCR);
// Remember
m_Streams.Add(ttx);
// Make it the guide
if ((null != m_Splitter) && (0 == m_GuidePID)) m_GuidePID = pid;
// Report
return ttx;
}
/// <summary>
/// Create a new stream holding DVB subtitles.
/// </summary>
/// <param name="info">Information on the contents of this subtitle stream.</param>
/// <returns>The new subtitle stream.</returns>
public SubtitleStream AddSubtitles(EPG.SubtitleInfo[] info)
{
// Flag
bool isPCR;
// Run
short pid = AddStream(StreamTypes.SubTitles, 255, false, true, info, null, out isPCR);
// Create
SubtitleStream sub = new SubtitleStream(this, pid, isPCR);
// Remember
m_Streams.Add(sub);
// Make it the guide
if ((null != m_Splitter) && (0 == m_GuidePID)) m_GuidePID = pid;
// Report
return sub;
}
/// <summary>
/// Create a new transport stream identifier for a new stream
/// in this transport stream.
/// </summary>
/// <param name="type">Type of the stream.</param>
/// <param name="encoding">Encoding type of the stream.</param>
/// <param name="isPCR">Set if the stream will be the PCR reference.</param>
/// <param name="noPTS">Set if the stream should not participate in PTS synchronisation.</param>
/// <param name="info">Information on the contents of a subtitle stream.</param>
/// <param name="aac">Optional AAC profile, level and type.</param>
/// <param name="noPCR">Set to disable PCR from PTS generation.</param>
/// <returns>A randomly choosen but unique transport stream identifier.</returns>
private short AddStream(StreamTypes type, byte encoding, bool noPCR, bool noPTS, EPG.SubtitleInfo[] info, ushort? aac, out bool isPCR)
{
// Create pid
short pid = NextPID++;
// Make key
int keyPID = pid;
// Forward
isPCR = ProgramMap.Add(type, encoding, pid, noPCR, info, aac);
// Reload
lock (m_Queue)
{
// Force PAT change
PATSent = false;
// Load
Packet buffers = (Packet)m_Buffers[keyPID];
// Create new
if (null == buffers)
{
// Create new
buffers = new Packet(this, keyPID);
// Remember
m_Buffers[keyPID] = buffers;
}
// Set up
if (StreamTypes.Video == type)
buffers.SetAudioVideo(true);
else if ((StreamTypes.Audio == type) || (StreamTypes.Private == type))
buffers.SetAudioVideo(false);
// May disable PTS synchronisation (e.g. for TeleText streams)
buffers.IgnorePTS = noPTS;
}
// Report
return pid;
}
/// <summary>
/// Send a PCR to the transport stream.
/// </summary>
/// <param name="counter">Individual packet counter which will not be incremented.</param>
/// <param name="pid">Related transport stream identifier.</param>
/// <param name="pts">The PTS from a PES header used for PCR.</param>
void IStreamConsumer.SendPCR(int counter, int pid, long pts)
{
// Remember
if (0 == m_PCRAvailable)
m_PCRAvailable = -pid;
// See if its time to send the PAT and PMT
SendPAT();
// Validate
if ((counter < 0) || (counter > 0xf))
throw new ArgumentOutOfRangeException("counter", counter, "only four bits allowed");
if ((pid < 0) || (pid >= 0x1fff))
throw new ArgumentOutOfRangeException("pid", pid, "only 13 bits allowed");
// Correct a bit (90kHz)
long pcr = pts - m_PCRDelay;
// Correct
if (pcr < 0)
pcr += Packet.PTSOverrun;
else if (pcr >= Packet.PTSOverrun)
pcr -= Packet.PTSOverrun;
// Split
byte pidh = (byte)(pid >> 8);
byte pidl = (byte)(pid & 0xff);
// Allocate data
byte[] ts = new byte[FullSize];
// Process the header
ts[0] = 0x47;
ts[1] = pidh;
ts[2] = pidl;
ts[3] = (byte)(0x20 | ((counter - 1) & 0x0f));
// Process adaption control
ts[4] = 0xb7;
ts[5] = 0x10;
ts[6] = (byte)((pcr >> 25) & 0xff);
ts[7] = (byte)((pcr >> 17) & 0xff);
ts[8] = (byte)((pcr >> 9) & 0xff);
ts[9] = (byte)((pcr >> 1) & 0xff);
ts[10] = (byte)(128 * (pcr & 0x01));
ts[11] = 0x00;
// Pad the rest
Array.Copy(Padding, 0, ts, 12, ts.Length - 12);
// Enqueue to writer
Enqueue(ts, pid, false, true, pts);
}
/// <summary>
/// Rekonstruiert die Systemuhr aus einem elementaren Paket. Das Paket
/// wird nicht auf Konsistenz geprüft.
/// </summary>
/// <param name="packet">Ein elementares Paket.</param>
/// <returns>Die gewünschte Systemzeit.</returns>
public static TimeSpan GetPCR(byte[] packet)
{
// Load parts
long b0 = packet[6];
long b1 = packet[7];
long b2 = packet[8];
long b3 = packet[9];
long b4 = (packet[10] >> 7);
// Merge
long clockTicks = b4 + 2 * (b3 + 256 * (b2 + 256 * (b1 + 256 * b0)));
// Calculate back from 90kHz clock
return new TimeSpan(clockTicks * 1000 / 9);
}
/// <summary>
/// Report if a PCR has been sent to the stream.
/// </summary>
bool IStreamConsumer.PCRAvailable
{
get
{
// Report
return (m_PCRAvailable > 0);
}
}
/// <summary>
/// Reports if all input should be discarded.
/// </summary>
bool IStreamConsumer2.IgnoreInput
{
get
{
// Forward
return IgnoreInput;
}
}
/// <summary>
/// Send some data to the transport stream.
/// </summary>
/// <remarks>
/// Padding will be done after the payload by simply filling the transport packing with
/// <i>0xff</i>. Although this should be identical to using adaption fields just before
/// the payloads some tools are not able to decode tables padded this way.
/// </remarks>
/// <param name="counter">The corresponding packet counter which will be updated.</param>
/// <param name="pid">The transport stream identifier to use.</param>
/// <param name="buffer">Data source.</param>
/// <param name="start">First byte to send.</param>
/// <param name="packs">Number of transport stream packets to send.</param>
/// <param name="isFirst">Set if the first byte is the first byte of a PES header.</param>
/// <param name="sizeOfLast">Number of bytes in the last packet - which may be padded.</param>
/// <param name="pts">If not negative this is the PES headers PTS - <i>isFirst</i> will be set.</param>
void IStreamConsumer.Send(ref int counter, int pid, byte[] buffer, int start, int packs, bool isFirst, int sizeOfLast, long pts)
{
// Forward
Send(ref counter, pid, buffer, start, packs, isFirst, sizeOfLast, false, pts);
}
/// <summary>
/// Send some data to the transport stream.
/// </summary>
/// <param name="counter">The corresponding packet counter which will be updated.</param>
/// <param name="pid">The transport stream identifier to use.</param>
/// <param name="buffer">Data source.</param>
/// <param name="start">First byte to send.</param>
/// <param name="packs">Number of transport stream packets to send.</param>
/// <param name="isFirst">Set if the first byte is the first byte of a PES header.</param>
/// <param name="sizeOfLast">Number of bytes in the last packet - which may be padded.</param>
/// <param name="standardPadding">Set if padding will be done using an adpation field
/// just before the payload data.</param>
/// <param name="pts">If not negative this is the PES headers PTS - <i>isFirst</i> will be set.</param>
private void Send(ref int counter, int pid, byte[] buffer, int start, int packs, bool isFirst, int sizeOfLast, bool standardPadding, long pts)
{
// Inform the splitter as soon as possible
if ((pts >= 0) && (pid == m_GuidePID) && (null != m_Splitter))
m_Splitter.GuidePTS = pts;
// See if its time to send the PAT and PMT
SendPAT();
// Validate
if ((counter < 0) || (counter > 0xf))
throw new ArgumentOutOfRangeException("counter", counter, "only four bits allowed");
if ((pid < 0) || (pid >= 0x1fff))
throw new ArgumentOutOfRangeException("pid", pid, "only 13 bits allowed");
if (null == buffer)
throw new ArgumentNullException("buffer");
if ((start < 0) || (start > buffer.Length))
throw new ArgumentOutOfRangeException("start", start, "exceeds buffer size");
if ((packs < 0) || (packs > (buffer.Length / PacketSize + 1)))
throw new ArgumentOutOfRangeException("packs", packs, "exceeds buffer size");
if ((sizeOfLast < 0) || (sizeOfLast > PacketSize))
throw new ArgumentOutOfRangeException("sizeOfLast", sizeOfLast, "exceeds packet size");
// Done
if (0 == packs)
return;
// Check mode
bool mustPad = (sizeOfLast < PacketSize);
// Padding mode
bool useSafePadding = (mustPad && !standardPadding && (sizeOfLast <= (PacketSize - 2)));
// Calculate
int end = start + (mustPad ? (packs - 1) : packs) * PacketSize + (mustPad ? sizeOfLast : 0);
// Validate
if (end > buffer.Length)
throw new ArgumentOutOfRangeException("packs", packs, "exceeds buffer size");
// Allocate data
byte[] ts = new byte[packs * FullSize];
// Split
byte pidh = (byte)(pid >> 8);
byte pidl = (byte)(pid & 0xff);
// Flag
if (isFirst)
pidh |= 0x40;
// Fill buffers
for (int tsi = 0; start < end; start += PacketSize, tsi += PacketSize)
{
// Process the header
ts[tsi++] = 0x47;
ts[tsi++] = pidh;
ts[tsi++] = pidl;
ts[tsi++] = (byte)(0x10 | counter++);
// Reset
if (4 == tsi)
pidh &= 0x1f;
// Correct
counter &= 0x0f;
// Check rest
int rest = end - start;
// Special mode
bool last = (rest < PacketSize);
// Check mode
if (last && useSafePadding)
{
// Activate adaption
ts[tsi - 1] |= 0x20;
// Padding size
int pad = PacketSize - rest - 2;
// Add adaption
ts[tsi + 0] = (byte)(pad + 1);
ts[tsi + 1] = 0x00;
// Pad first
Array.Copy(Padding, 0, ts, tsi + 2, pad);
// Data last
Array.Copy(buffer, start, ts, tsi + 2 + pad, rest);
}
else
{
// Move in
Array.Copy(buffer, start, ts, tsi, (rest >= PacketSize) ? PacketSize : rest);
// Pad
if (last)
Array.Copy(Padding, 0, ts, tsi + rest, PacketSize - rest);
}
}
// Must synchronize
lock (m_Queue)
{
// Enqueue to writer
Enqueue(ts, pid, isFirst, false, pts);
// Count
PacketCounter += packs;
// Must resend
if (PacketCounter > 200)
PATSent = false;
}
}
/// <summary>
/// Send all buffered data to the transport stream.
/// </summary>
/// <param name="pid"></param>
/// <param name="withPCR">Set to flush PCR, too.</param>
private void Flush(int pid, bool withPCR)
{
// Move full packet to synchronizer queue
Enqueue(pid, withPCR);
// Cleanup as much as possible
for (bool processed = true; processed; processed = false)
{
// First get rid of all streams with no PTS or no data at all
foreach (Packet buffers in m_Buffers.Values)
if (buffers.DequeueNoPTS())
processed = true;
// Process as long as there are packets in each stream
for (bool find = true; find;)
{
// The minium PTS packet
Packet minHolder = null;
// Process all streams
foreach (Packet buffers in m_Buffers.Values)
if (!buffers.HasQueue)
{
// Can safely continue if this stream provides no PTS or we are not synchronizing this stream
if (buffers.PTSMissing || buffers.IgnorePTS)
continue;
// Can safely continue if this stream is currently not active
if (!buffers.IsActive)