-
Notifications
You must be signed in to change notification settings - Fork 61
/
AviWriter.cs
823 lines (723 loc) · 33 KB
/
AviWriter.cs
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
using SharpAvi.Codecs;
using SharpAvi.Format;
using SharpAvi.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SharpAvi.Output
{
/// <summary>
/// Used to write an AVI file.
/// </summary>
/// <remarks>
/// After writing begin to any of the streams, no property changes or stream addition are allowed.
/// </remarks>
public class AviWriter : IDisposable, IAviStreamWriteHandler
{
private const int MAX_INDEX_ENTRIES = 15000;
private const int INDEX1_ENTRY_SIZE = 4 * sizeof(uint);
private const int RIFF_AVI_SIZE_TRESHOLD = 512 * 1024 * 1024;
private const int RIFF_AVIX_SIZE_TRESHOLD = int.MaxValue - 1024 * 1024;
private readonly BinaryWriter fileWriter;
private bool isClosed = false;
private bool startedWriting = false;
private readonly object syncWrite = new object();
private bool isFirstRiff = true;
private RiffItem currentRiff;
private RiffItem currentMovie;
private RiffItem header;
private int riffSizeTreshold;
private int riffAviFrameCount = -1;
private int index1Count = 0;
private readonly List<IAviStreamInternal> streams = new List<IAviStreamInternal>();
private StreamInfo[] streamsInfo;
/// <summary>
/// Creates a new instance of <see cref="AviWriter"/> for writing to a file.
/// </summary>
/// <param name="fileName">Path to an AVI file being written.</param>
public AviWriter(string fileName)
{
Argument.IsNotNullOrEmpty(fileName, nameof(fileName));
var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024);
fileWriter = new BinaryWriter(fileStream);
}
/// <summary>
/// Creates a new instance of <see cref="AviWriter"/> for writing to a stream.
/// </summary>
/// <param name="stream">Stream being written to.</param>
/// <param name="leaveOpen">Whether to leave the stream open when closing <see cref="AviWriter"/>.</param>
public AviWriter(Stream stream, bool leaveOpen = false)
{
Argument.Meets(stream.CanWrite, nameof(stream), "A stream is not writeable.");
Argument.Meets(stream.CanSeek, nameof(stream), "A stream is not seekable.");
fileWriter = new BinaryWriter(stream, Encoding.Default, leaveOpen);
}
/// <summary>Frame rate.</summary>
/// <remarks>
/// The value of the property is rounded to 3 fractional digits.
/// Default value is <c>1</c>.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Already started to write frames hence this information cannot be changed.
/// </exception>
public decimal FramesPerSecond
{
get { return framesPerSecond; }
set
{
Argument.IsPositive(value, nameof(value));
lock (syncWrite)
{
CheckNotStartedWriting();
framesPerSecond = Decimal.Round(value, 3);
}
}
}
private decimal framesPerSecond = 1;
private uint frameRateNumerator;
private uint frameRateDenominator;
/// <summary>
/// Whether to emit index used in AVI v1 format.
/// </summary>
/// <remarks>
/// By default, only index conformant to OpenDML AVI extensions (AVI v2) is emitted.
/// Presence of v1 index may improve the compatibility of generated AVI files with certain software,
/// especially when there are multiple streams.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Already started to write frames hence this information cannot be changed.
/// </exception>
public bool EmitIndex1
{
get { return emitIndex1; }
set
{
lock (syncWrite)
{
CheckNotStartedWriting();
emitIndex1 = value;
}
}
}
private bool emitIndex1;
/// <summary>
/// The maximum number of super index entries.
/// </summary>
/// <remarks>
/// <para>
/// This number should be known before writing starts because the space for
/// super-index entries is reserved in the file header.
/// It effectively limits the number of frames which can be written to an individual stream.
/// Each super-index entry points to a single index block which can reference up to <c>15,000</c> frames.
/// </para>
/// <para>
/// The default value is <c>256</c>. For a 60 frames/s video stream this is equivalent to a duration
/// of more than 17 hours.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Already started to write frames hence this information cannot be changed.
/// </exception>
public int MaxSuperIndexEntries
{
get { return maxSuperIndexEntries; }
set
{
Argument.IsPositive(value, nameof(value));
lock (syncWrite)
{
CheckNotStartedWriting();
maxSuperIndexEntries = value;
}
}
}
private int maxSuperIndexEntries = 256;
/// <summary>AVI streams that have been added so far.</summary>
public IReadOnlyList<IAviStream> Streams => streams;
/// <summary>Adds new video stream.</summary>
/// <param name="width">Frame's width.</param>
/// <param name="height">Frame's height.</param>
/// <param name="bitsPerPixel">Bits per pixel.</param>
/// <returns>Newly added video stream.</returns>
/// <remarks>
/// Stream is initialized to be ready for uncompressed video (bottom-up BGR) with specified parameters.
/// However, properties (such as <see cref="IAviVideoStream.Codec"/>) can be changed later if the stream is
/// to be fed with pre-compressed data.
/// </remarks>
public IAviVideoStream AddVideoStream(int width = 1, int height = 1, BitsPerPixel bitsPerPixel = BitsPerPixel.Bpp32)
{
Argument.IsPositive(width, nameof(width));
Argument.IsPositive(height, nameof(height));
Argument.IsEnumMember(bitsPerPixel, nameof(bitsPerPixel));
return AddStream<IAviVideoStreamInternal>(index =>
{
var stream = new AviVideoStream(index, this, width, height, bitsPerPixel);
var asyncStream = new AsyncVideoStreamWrapper(stream);
return asyncStream;
});
}
/// <summary>Adds new encoding video stream.</summary>
/// <param name="encoder">Encoder to be used.</param>
/// <param name="ownsEncoder">Whether encoder should be disposed with the writer.</param>
/// <param name="width">Frame's width.</param>
/// <param name="height">Frame's height.</param>
/// <returns>Newly added video stream.</returns>
/// <remarks>
/// <para>
/// Stream is initialized to be to be encoded with the specified encoder.
/// Method <see cref="IAviVideoStream.WriteFrame"/> expects data in the same format as encoders,
/// that is top-down BGR32 bitmap. It is passed to the encoder and the encoded result is written
/// to the stream.
/// Parameters <c>isKeyFrame</c> and <c>length</c> are ignored by encoding streams,
/// as encoders determine on their own which frames are keys, and the size of input bitmaps is fixed.
/// </para>
/// <para>
/// Properties <see cref="IAviVideoStream.Codec"/> and <see cref="IAviVideoStream.BitsPerPixel"/>
/// are defined by the encoder, and cannot be modified.
/// </para>
/// </remarks>
public IAviVideoStream AddEncodingVideoStream(IVideoEncoder encoder, bool ownsEncoder = true, int width = 1, int height = 1)
{
Argument.IsNotNull(encoder, nameof(encoder));
Argument.IsPositive(width, nameof(width));
Argument.IsPositive(height, nameof(height));
return AddStream<IAviVideoStreamInternal>(index =>
{
var stream = new AviVideoStream(index, this, width, height, BitsPerPixel.Bpp32);
var encodingStream = new EncodingVideoStreamWrapper(stream, encoder, ownsEncoder);
var asyncStream = new AsyncVideoStreamWrapper(encodingStream);
return asyncStream;
});
}
/// <summary>Adds new audio stream.</summary>
/// <param name="channelCount">Number of channels.</param>
/// <param name="samplesPerSecond">Sample rate.</param>
/// <param name="bitsPerSample">Bits per sample (per single channel).</param>
/// <returns>Newly added audio stream.</returns>
/// <remarks>
/// Stream is initialized to be ready for uncompressed audio (PCM) with specified parameters.
/// However, properties (such as <see cref="IAviAudioStream.Format"/>) can be changed later if the stream is
/// to be fed with pre-compressed data.
/// </remarks>
public IAviAudioStream AddAudioStream(int channelCount = 1, int samplesPerSecond = 44100, int bitsPerSample = 16)
{
Argument.IsPositive(channelCount, nameof(channelCount));
Argument.IsPositive(samplesPerSecond, nameof(samplesPerSecond));
Argument.IsPositive(bitsPerSample, nameof(bitsPerSample));
Argument.Meets(bitsPerSample % 8 == 0, nameof(bitsPerSample), "A multiple of 8 is expected.");
return AddStream<IAviAudioStreamInternal>(index =>
{
var stream = new AviAudioStream(index, this, channelCount, samplesPerSecond, bitsPerSample);
var asyncStream = new AsyncAudioStreamWrapper(stream);
return asyncStream;
});
}
/// <summary>Adds new encoding audio stream.</summary>
/// <param name="encoder">Encoder to be used.</param>
/// <param name="ownsEncoder">Whether encoder should be disposed with the writer.</param>
/// <returns>Newly added audio stream.</returns>
/// <remarks>
/// <para>
/// Stream is initialized to be to be encoded with the specified encoder.
/// Method <see cref="IAviAudioStream.WriteBlock"/> expects data in the same format as encoder (see encoder's docs).
/// The data is passed to the encoder and the encoded result is written to the stream.
/// </para>
/// <para>
/// The encoder defines the following properties of the stream:
/// <see cref="IAviAudioStream.ChannelCount"/>, <see cref="IAviAudioStream.SamplesPerSecond"/>,
/// <see cref="IAviAudioStream.BitsPerSample"/>, <see cref="IAviAudioStream.BytesPerSecond"/>,
/// <see cref="IAviAudioStream.Granularity"/>, <see cref="IAviAudioStream.Format"/>,
/// <see cref="IAviAudioStream.FormatSpecificData"/>.
/// These properties cannot be modified.
/// </para>
/// </remarks>
public IAviAudioStream AddEncodingAudioStream(IAudioEncoder encoder, bool ownsEncoder = true)
{
Argument.IsNotNull(encoder, nameof(encoder));
return AddStream<IAviAudioStreamInternal>(index =>
{
var stream = new AviAudioStream(index, this, 1, 44100, 16);
var encodingStream = new EncodingAudioStreamWrapper(stream, encoder, ownsEncoder);
var asyncStream = new AsyncAudioStreamWrapper(encodingStream);
return asyncStream;
});
}
private TStream AddStream<TStream>(Func<int, TStream> streamFactory)
where TStream : IAviStreamInternal
{
if (Streams.Count >= 100)
throw new InvalidOperationException("Cannot add more streams.");
lock (syncWrite)
{
CheckNotClosed();
CheckNotStartedWriting();
var stream = streamFactory.Invoke(Streams.Count);
streams.Add(stream);
return stream;
}
}
/// <summary>
/// Closes the writer and AVI file itself.
/// </summary>
public void Close()
{
if (!isClosed)
{
bool finishWriting;
lock (syncWrite)
{
finishWriting = startedWriting;
}
// Call FinishWriting without holding the lock
// because additional writes may be performed inside
if (finishWriting)
{
foreach (var stream in streams)
{
stream.FinishWriting();
}
}
lock (syncWrite)
{
if (startedWriting)
{
foreach (var stream in streams)
{
FlushStreamIndex(stream);
}
CloseCurrentRiff();
// Rewrite header with actual data like frames count, super index, etc.
fileWriter.BaseStream.Position = header.ItemStart;
WriteHeader();
}
fileWriter.Close();
isClosed = true;
}
foreach (var disposableStream in streams.OfType<IDisposable>())
{
disposableStream.Dispose();
}
}
}
void IDisposable.Dispose() => Close();
private void CheckNotStartedWriting()
{
if (startedWriting)
{
throw new InvalidOperationException("No stream information can be changed after starting to write frames.");
}
}
private void CheckNotClosed()
{
if (isClosed)
{
throw new ObjectDisposedException(typeof(AviWriter).Name);
}
}
private void PrepareForWriting()
{
startedWriting = true;
foreach (var stream in streams)
{
stream.PrepareForWriting();
}
AviUtils.SplitFrameRate(FramesPerSecond, out frameRateNumerator, out frameRateDenominator);
streamsInfo = streams.Select(s => new StreamInfo(KnownFourCCs.Chunks.IndexData(s.Index))).ToArray();
riffSizeTreshold = RIFF_AVI_SIZE_TRESHOLD;
currentRiff = fileWriter.OpenList(KnownFourCCs.Lists.Avi, KnownFourCCs.ListTypes.Riff);
WriteHeader();
currentMovie = fileWriter.OpenList(KnownFourCCs.Lists.Movie);
}
private void CreateNewRiffIfNeeded(int approximateSizeOfNextChunk)
{
var estimatedSize = fileWriter.BaseStream.Position + approximateSizeOfNextChunk - currentRiff.ItemStart;
if (isFirstRiff && emitIndex1)
{
estimatedSize += RiffItem.ITEM_HEADER_SIZE + index1Count * INDEX1_ENTRY_SIZE;
}
if (estimatedSize > riffSizeTreshold)
{
CloseCurrentRiff();
currentRiff = fileWriter.OpenList(KnownFourCCs.Lists.AviExtended, KnownFourCCs.ListTypes.Riff);
currentMovie = fileWriter.OpenList(KnownFourCCs.Lists.Movie);
}
}
private void CloseCurrentRiff()
{
fileWriter.CloseItem(currentMovie);
// Several special actions for the first RIFF (AVI)
if (isFirstRiff)
{
riffAviFrameCount = streams.OfType<IAviVideoStream>().Max(s => streamsInfo[s.Index].FrameCount);
if (emitIndex1)
{
WriteIndex1();
}
riffSizeTreshold = RIFF_AVIX_SIZE_TRESHOLD;
}
fileWriter.CloseItem(currentRiff);
isFirstRiff = false;
}
#region IAviStreamWriteHandler implementation
#if NET5_0_OR_GREATER
void IAviStreamWriteHandler.WriteVideoFrame(AviVideoStream stream, bool isKeyFrame, ReadOnlySpan<byte> frameData)
=> WriteStreamFrame(stream, isKeyFrame, frameData);
void IAviStreamWriteHandler.WriteAudioBlock(AviAudioStream stream, ReadOnlySpan<byte> blockData)
=> WriteStreamFrame(stream, true, blockData);
#else
void IAviStreamWriteHandler.WriteVideoFrame(AviVideoStream stream, bool isKeyFrame, byte[] frameData, int startIndex, int count)
=> WriteStreamFrame(stream, isKeyFrame, frameData, startIndex, count);
void IAviStreamWriteHandler.WriteAudioBlock(AviAudioStream stream, byte[] blockData, int startIndex, int count)
=> WriteStreamFrame(stream, true, blockData, startIndex, count);
#endif
#if NET5_0_OR_GREATER
private void WriteStreamFrame(AviStreamBase stream, bool isKeyFrame, ReadOnlySpan<byte> frameData)
#else
private void WriteStreamFrame(AviStreamBase stream, bool isKeyFrame, byte[] frameData, int startIndex, int count)
#endif
{
lock (syncWrite)
{
CheckNotClosed();
if (!startedWriting)
{
PrepareForWriting();
}
var si = streamsInfo[stream.Index];
if (ShouldFlushStreamIndex(si.StandardIndex))
{
FlushStreamIndex(stream);
}
if (si.SuperIndex.Count == maxSuperIndexEntries)
{
throw new InvalidOperationException("Cannot write more frames to this stream.");
}
var shouldCreateIndex1Entry = emitIndex1 && isFirstRiff;
#if NET5_0_OR_GREATER
var count = frameData.Length;
#endif
CreateNewRiffIfNeeded(count + (shouldCreateIndex1Entry ? INDEX1_ENTRY_SIZE : 0));
var chunk = fileWriter.OpenChunk(stream.ChunkId, count);
#if NET5_0_OR_GREATER
fileWriter.Write(frameData);
#else
fileWriter.Write(frameData, startIndex, count);
#endif
fileWriter.CloseItem(chunk);
si.OnFrameWritten(chunk.DataSize);
var dataSize = (uint)chunk.DataSize;
// Set the highest bit for non-key frames according to the OpenDML spec
if (!isKeyFrame)
{
dataSize |= 0x80000000U;
}
var newEntry = new StandardIndexEntry
{
DataOffset = chunk.DataStart,
DataSize = dataSize
};
si.StandardIndex.Add(newEntry);
if (shouldCreateIndex1Entry)
{
var index1Entry = new Index1Entry
{
IsKeyFrame = isKeyFrame,
DataOffset = (uint)(chunk.ItemStart - currentMovie.DataStart),
DataSize = dataSize
};
si.Index1.Add(index1Entry);
index1Count++;
}
}
}
void IAviStreamWriteHandler.WriteStreamHeader(AviVideoStream videoStream)
{
// See AVISTREAMHEADER structure
fileWriter.Write((uint)videoStream.StreamType);
fileWriter.Write((uint)videoStream.Codec);
fileWriter.Write(0U); // StreamHeaderFlags
fileWriter.Write((ushort)0); // priority
fileWriter.Write((ushort)0); // language
fileWriter.Write(0U); // initial frames
fileWriter.Write(frameRateDenominator); // scale (frame rate denominator)
fileWriter.Write(frameRateNumerator); // rate (frame rate numerator)
fileWriter.Write(0U); // start
fileWriter.Write((uint)streamsInfo[videoStream.Index].FrameCount); // length
fileWriter.Write((uint)streamsInfo[videoStream.Index].MaxChunkDataSize); // suggested buffer size
fileWriter.Write(0U); // quality
fileWriter.Write(0U); // sample size
fileWriter.Write((short)0); // rectangle left
fileWriter.Write((short)0); // rectangle top
short right = (short)(videoStream != null ? videoStream.Width : 0);
short bottom = (short)(videoStream != null ? videoStream.Height : 0);
fileWriter.Write(right); // rectangle right
fileWriter.Write(bottom); // rectangle bottom
}
void IAviStreamWriteHandler.WriteStreamHeader(AviAudioStream audioStream)
{
// See AVISTREAMHEADER structure
fileWriter.Write((uint)audioStream.StreamType);
fileWriter.Write(0U); // no codec
fileWriter.Write(0U); // StreamHeaderFlags
fileWriter.Write((ushort)0); // priority
fileWriter.Write((ushort)0); // language
fileWriter.Write(0U); // initial frames
fileWriter.Write((uint)audioStream.Granularity); // scale (sample rate denominator)
fileWriter.Write((uint)audioStream.BytesPerSecond); // rate (sample rate numerator)
fileWriter.Write(0U); // start
fileWriter.Write((uint)streamsInfo[audioStream.Index].TotalDataSize); // length
fileWriter.Write((uint)(audioStream.BytesPerSecond / 2)); // suggested buffer size (half-second)
fileWriter.Write(-1); // quality
fileWriter.Write(audioStream.Granularity); // sample size
fileWriter.SkipBytes(sizeof(short) * 4);
}
void IAviStreamWriteHandler.WriteStreamFormat(AviVideoStream videoStream)
{
// See BITMAPINFOHEADER structure
fileWriter.Write(40U); // size of structure
fileWriter.Write(videoStream.Width);
fileWriter.Write(videoStream.Height);
fileWriter.Write((short)1); // planes
fileWriter.Write((ushort)videoStream.BitsPerPixel); // bits per pixel
fileWriter.Write((uint)videoStream.Codec); // compression (codec FOURCC)
// 0 size is safer for uncompressed formats not to bother with stride calculation
var sizeInBytes = videoStream.Codec == CodecIds.Uncompressed
? 0
: videoStream.Width * videoStream.Height * (((int)videoStream.BitsPerPixel) / 8);
fileWriter.Write((uint)sizeInBytes); // image size in bytes
fileWriter.Write(0); // X pixels per meter
fileWriter.Write(0); // Y pixels per meter
// Writing grayscale palette for 8-bit uncompressed stream
// Otherwise, no palette
if (videoStream.BitsPerPixel == BitsPerPixel.Bpp8 && videoStream.Codec == CodecIds.Uncompressed)
{
fileWriter.Write(256U); // palette colors used
fileWriter.Write(0U); // palette colors important
for (int i = 0; i < 256; i++)
{
fileWriter.Write((byte)i);
fileWriter.Write((byte)i);
fileWriter.Write((byte)i);
fileWriter.Write((byte)0);
}
}
else
{
fileWriter.Write(0U); // palette colors used
fileWriter.Write(0U); // palette colors important
}
}
void IAviStreamWriteHandler.WriteStreamFormat(AviAudioStream audioStream)
{
// See WAVEFORMATEX structure
fileWriter.Write(audioStream.Format);
fileWriter.Write((ushort)audioStream.ChannelCount);
fileWriter.Write((uint)audioStream.SamplesPerSecond);
fileWriter.Write((uint)audioStream.BytesPerSecond);
fileWriter.Write((ushort)audioStream.Granularity);
fileWriter.Write((ushort)audioStream.BitsPerSample);
if (audioStream.FormatSpecificData != null)
{
fileWriter.Write((ushort)audioStream.FormatSpecificData.Length);
fileWriter.Write(audioStream.FormatSpecificData);
}
else
{
fileWriter.Write((ushort)0);
}
}
#endregion
#region Header
private void WriteHeader()
{
header = fileWriter.OpenList(KnownFourCCs.Lists.Header);
WriteFileHeader();
foreach (var stream in streams)
{
WriteStreamList(stream);
}
WriteOdmlHeader();
WriteJunkInsteadOfMissingSuperIndexEntries();
fileWriter.CloseItem(header);
}
private void WriteJunkInsteadOfMissingSuperIndexEntries()
{
var missingEntriesCount = streamsInfo.Sum(si => maxSuperIndexEntries - si.SuperIndex.Count);
if (missingEntriesCount > 0)
{
var junkDataSize = missingEntriesCount * sizeof(uint) * 4 - RiffItem.ITEM_HEADER_SIZE;
var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.Junk, junkDataSize);
fileWriter.SkipBytes(junkDataSize);
fileWriter.CloseItem(chunk);
}
}
private void WriteFileHeader()
{
// See AVIMAINHEADER structure
var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.AviHeader);
fileWriter.Write((uint)Decimal.Round(1000000m / FramesPerSecond)); // microseconds per frame
// TODO: More correct computation of byterate
fileWriter.Write((uint)Decimal.Truncate(FramesPerSecond * streamsInfo.Sum(s => s.MaxChunkDataSize))); // max bytes per second
fileWriter.Write(0U); // padding granularity
var flags = MainHeaderFlags.IsInterleaved | MainHeaderFlags.TrustChunkType;
if (emitIndex1)
{
flags |= MainHeaderFlags.HasIndex;
}
fileWriter.Write((uint)flags); // MainHeaderFlags
fileWriter.Write(riffAviFrameCount); // total frames (in the first RIFF list containing this header)
fileWriter.Write(0U); // initial frames
fileWriter.Write((uint)Streams.Count); // stream count
fileWriter.Write(0U); // suggested buffer size
var firstVideoStream = streams.OfType<IAviVideoStream>().First();
fileWriter.Write(firstVideoStream.Width); // video width
fileWriter.Write(firstVideoStream.Height); // video height
fileWriter.SkipBytes(4 * sizeof(uint)); // reserved
fileWriter.CloseItem(chunk);
}
private void WriteOdmlHeader()
{
var list = fileWriter.OpenList(KnownFourCCs.Lists.OpenDml);
var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.OpenDmlHeader);
fileWriter.Write(streams.OfType<IAviVideoStream>().Max(s => streamsInfo[s.Index].FrameCount)); // total frames in file
fileWriter.SkipBytes(61 * sizeof(uint)); // reserved
fileWriter.CloseItem(chunk);
fileWriter.CloseItem(list);
}
private void WriteStreamList(IAviStreamInternal stream)
{
var list = fileWriter.OpenList(KnownFourCCs.Lists.Stream);
WriteStreamHeader(stream);
WriteStreamFormat(stream);
WriteStreamName(stream);
WriteStreamSuperIndex(stream);
fileWriter.CloseItem(list);
}
private void WriteStreamHeader(IAviStreamInternal stream)
{
var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.StreamHeader);
stream.WriteHeader();
fileWriter.CloseItem(chunk);
}
private void WriteStreamFormat(IAviStreamInternal stream)
{
var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.StreamFormat);
stream.WriteFormat();
fileWriter.CloseItem(chunk);
}
private void WriteStreamName(IAviStream stream)
{
if (!string.IsNullOrEmpty(stream.Name))
{
var bytes = Encoding.ASCII.GetBytes(stream.Name);
var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.StreamName);
fileWriter.Write(bytes);
fileWriter.Write((byte)0);
fileWriter.CloseItem(chunk);
}
}
private void WriteStreamSuperIndex(IAviStream stream)
{
var superIndex = streamsInfo[stream.Index].SuperIndex;
// See AVISUPERINDEX structure
var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.StreamIndex);
fileWriter.Write((ushort)4); // DWORDs per entry
fileWriter.Write((byte)0); // index sub-type
fileWriter.Write((byte)IndexType.Indexes); // index type
fileWriter.Write((uint)superIndex.Count); // entries count
fileWriter.Write((uint)((IAviStreamInternal)stream).ChunkId); // chunk ID of the stream
fileWriter.SkipBytes(3 * sizeof(uint)); // reserved
// entries
foreach (var entry in superIndex)
{
fileWriter.Write((ulong)entry.ChunkOffset); // offset of sub-index chunk
fileWriter.Write((uint)entry.ChunkSize); // size of sub-index chunk
fileWriter.Write((uint)entry.Duration); // duration of sub-index data (number of frames it refers to)
}
fileWriter.CloseItem(chunk);
}
#endregion
#region Index
private void WriteIndex1()
{
var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.Index1);
var indices = streamsInfo.Select((si, i) => new {si.Index1, ChunkId = (uint)streams.ElementAt(i).ChunkId}).
Where(a => a.Index1.Count > 0)
.ToList();
while (index1Count > 0)
{
var minOffset = indices[0].Index1[0].DataOffset;
var minIndex = 0;
for (var i = 1; i < indices.Count; i++)
{
var offset = indices[i].Index1[0].DataOffset;
if (offset < minOffset)
{
minOffset = offset;
minIndex = i;
}
}
var index = indices[minIndex];
fileWriter.Write(index.ChunkId);
fileWriter.Write(index.Index1[0].IsKeyFrame ? 0x00000010U : 0);
fileWriter.Write(index.Index1[0].DataOffset);
fileWriter.Write(index.Index1[0].DataSize);
index.Index1.RemoveAt(0);
if (index.Index1.Count == 0)
{
indices.RemoveAt(minIndex);
}
index1Count--;
}
fileWriter.CloseItem(chunk);
}
private bool ShouldFlushStreamIndex(IList<StandardIndexEntry> index)
{
// Check maximum number of entries
if (index.Count >= MAX_INDEX_ENTRIES)
return true;
// Check relative offset
if (index.Count > 0 && fileWriter.BaseStream.Position - index[0].DataOffset > uint.MaxValue)
return true;
return false;
}
private void FlushStreamIndex(IAviStreamInternal stream)
{
var si = streamsInfo[stream.Index];
var index = si.StandardIndex;
var entriesCount = index.Count;
if (entriesCount == 0)
return;
var baseOffset = index[0].DataOffset;
var indexSize = 24 + entriesCount * 8;
CreateNewRiffIfNeeded(indexSize);
// See AVISTDINDEX structure
var chunk = fileWriter.OpenChunk(si.StandardIndexChunkId, indexSize);
fileWriter.Write((ushort)2); // DWORDs per entry
fileWriter.Write((byte)0); // index sub-type
fileWriter.Write((byte)IndexType.Chunks); // index type
fileWriter.Write((uint)entriesCount); // entries count
fileWriter.Write((uint)stream.ChunkId); // chunk ID of the stream
fileWriter.Write((ulong)baseOffset); // base offset for entries
fileWriter.SkipBytes(sizeof(uint)); // reserved
foreach (var entry in index)
{
fileWriter.Write((uint)(entry.DataOffset - baseOffset)); // chunk data offset
fileWriter.Write(entry.DataSize); // chunk data size
}
fileWriter.CloseItem(chunk);
var superIndex = streamsInfo[stream.Index].SuperIndex;
var newEntry = new SuperIndexEntry
{
ChunkOffset = chunk.ItemStart,
ChunkSize = chunk.ItemSize,
Duration = entriesCount
};
superIndex.Add(newEntry);
index.Clear();
}
#endregion
}
}