-
Notifications
You must be signed in to change notification settings - Fork 0
/
MXFStream.java
905 lines (717 loc) · 27.6 KB
/
MXFStream.java
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
/*
* Copyright 2016 Richard Cartwright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tv.amwa.maj.io.mxf;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import tv.amwa.maj.exception.EndOfDataException;
import tv.amwa.maj.exception.InsufficientSpaceException;
import tv.amwa.maj.industry.MediaEngine;
import tv.amwa.maj.industry.MetadataObject;
import tv.amwa.maj.industry.PropertyValue;
import tv.amwa.maj.io.mxf.impl.CPSystemItemImpl;
import tv.amwa.maj.io.mxf.impl.EssenceElementImpl;
import tv.amwa.maj.io.mxf.impl.HeaderMetadataImpl;
import tv.amwa.maj.io.mxf.impl.PrimerPackImpl;
import tv.amwa.maj.io.mxf.impl.RandomIndexPackImpl;
import tv.amwa.maj.io.mxf.impl.ResolutionEntry;
import tv.amwa.maj.meta.ClassDefinition;
import tv.amwa.maj.model.Preface;
import tv.amwa.maj.model.impl.PrefaceImpl;
import tv.amwa.maj.record.impl.AUIDImpl;
public class MXFStream {
static final int RIP_BYTES_MAX = 262144;
public static final MXFUnit readNextUnit(
InputStream stream,
long sizeLimit)
throws IOException {
KeyAndConsumed kandc = readKey(stream);
if (kandc.getConsumed() > sizeLimit)
throw new MAJMXFStreamException("Size limit exceeded when reading key for next MXF unit.");
UnitType unitType = UnitType.typeFromKey(kandc.getKey());
switch (unitType) {
case HeaderClosedCompletePartitionPack:
case HeaderClosedIncompletePartitionPack:
case HeaderOpenCompletePartitionPack:
case HeaderOpenIncompletePartitionPack:
case FooterClosedCompletePartitionPack:
case FooterClosedIncompletePartitionPack:
case BodyClosedCompletePartitionPack:
case BodyClosedIncompletePartitionPack:
case BodyOpenCompletePartitionPack:
case BodyOpenIncompletePartitionPack:
return readPartitionPack(stream, kandc.getKey());
case HeaderMetadata:
return readHeaderMetadata(stream, kandc.getKey(), sizeLimit - kandc.getConsumed());
case ContentPackageEssenceElement:
case ContentPackagePicture:
case ContentPackageSound:
case ContentPackageData:
case GenericContainerEssenceElement:
case GenericContainerPicture:
case GenericContainerSound:
case GenericContainerData:
case GenericContainerCompound:
return readEssenceElement(stream, kandc.getKey());
case ContentPackageSystemItem:
return readCPSystemItem(stream, kandc.getKey());
case IndexTableSegment:
return readIndexTableSegment(stream, kandc.getKey());
case RandomIndexPack:
return readRandomIndexPack(stream, kandc.getKey());
case GenericContainerSystemItem: // FIXME should have a generic container system item reader
case Unknown:
default:
throw new MAJMXFStreamException("Unexpected element encountered when reading input stream, starting with key '" +
kandc.getKey().toString() + "'.");
}
}
/**
* <p>Read a {@linkplain RandomIndexPack random index pack (RIP)} from the given input stream, using the
* given size to efficiently skip to the end of the file to find the RIP. As the RIP is always located at
* the end of the file, the input stream is always closed following this operation.</p>
*
* @param stream Stream of MXF data to read and retrieve the RIP from.
* @param size Total size of the input stream measured in bytes, which must be known in advance of a call to this method.
* @return Random index pack contained in the given input stream.
*
* @throws IOException Problem occurred when reading the file or no RIP is contained within the file.
*/
public final static RandomIndexPack readRandomIndexPack(
InputStream stream,
long size)
throws IOException {
long skipBytes = (size > RIP_BYTES_MAX) ? size - RIP_BYTES_MAX : 0l;
byte[] lastBytesOfFile = new byte[RIP_BYTES_MAX];
int bytesRead;
try {
skipForward(stream, skipBytes);
bytesRead = stream.read(lastBytesOfFile);
}
finally {
if (stream != null)
stream.close();
}
if (bytesRead < 36)
throw new MAJMXFStreamException("Input stream does not contain RIP as total bytes read from file is too low.");
ByteBuffer buffer = ByteBuffer.wrap(lastBytesOfFile, 0, bytesRead);
buffer.position(buffer.limit() - 4);
int ripOffset = buffer.getInt();
if (ripOffset > buffer.limit())
throw new MAJMXFStreamException("Input stream does not contain a valid RIP offset value. File does not contain a readable RIP.");
buffer.position(buffer.limit() - ripOffset);
RandomIndexPack rip = RandomIndexPackImpl.createFromBytes(buffer);
if (rip == null)
throw new MAJMXFStreamException("Input stream does not contain a valid RIP.");
return rip;
}
public final static HeaderMetadata readHeaderMetadata(
InputStream stream,
long headerSize)
throws IOException {
KeyAndConsumed kandc = readKey(stream);
return readHeaderMetadata(stream, kandc.getKey(), headerSize - 16);
}
final static HeaderMetadata readHeaderMetadata(
InputStream stream,
UL primerKey,
long headerSize)
throws IOException {
FixedLengthPack candidatePack = null;
PrimerPack primerPack = null;
long primerSize = 0l;
try {
LengthAndConsumed landc = readBERLength(stream);
primerSize = landc.getLength();
ByteBuffer primerBytes = readValue(stream, primerSize);
headerSize -= landc.getTotal();
candidatePack = MXFBuilder.readFixedLengthPack((AUIDImpl) primerKey, primerBytes);
primerPack = (PrimerPack) candidatePack;
}
catch (EndOfDataException eode) {
throw new MAJMXFStreamException("Insufficient bytes in header bytes read from stream to create a primer pack.");
}
catch (IllegalArgumentException ioe) {
throw new MAJMXFStreamException("Insufficient bytes in header bytes read from stream to create a primer pack, " +
"detected on setting primer pack buffer limit for primer pack size '" + primerSize + "'.");
}
catch (BufferUnderflowException bue) {
throw new MAJMXFStreamException("Insufficient bytes in header bytes read from stream to create a primer length.");
}
catch (ClassCastException cce) {
throw new MAJMXFStreamException("Expected a primer pack in header metadata bytes but found an instance of '" +
candidatePack.getClass().getCanonicalName() + "'.");
}
Map<AUIDImpl, MetadataObject> referenceTable = new HashMap<AUIDImpl, MetadataObject>();
List<ResolutionEntry> resolutions = new Vector<ResolutionEntry>();
Preface preface = null;
try {
while (headerSize > 0l) {
UL metadataKey = readSingleKey(stream);
headerSize -= 16;
if (MXFBuilder.isKLVFill(metadataKey)) {
headerSize -= readPastFill(stream);
continue;
}
LengthAndConsumed landc = readBERLength(stream);
ByteBuffer headerBytes = readValue(stream, landc.getLength());
headerSize -= landc.getTotal();
MetadataObject metadataFromFile =
MXFBuilder.readLocalSet((AUIDImpl) metadataKey, headerBytes, primerPack, referenceTable, resolutions);
if (metadataFromFile instanceof Preface)
preface = (PrefaceImpl) metadataFromFile;
// if (metadataFromFile != null)
// System.out.println(XMLBuilder.toXML(metadataFromFile));
}
}
catch (Exception e) {
throw new MAJMXFStreamException("Problem reading header metadata from file, caused by a " + e.getClass().getName() + ": " +
e.getMessage() + ".",
e);
}
if (preface == null)
throw new MAJMXFStreamException("No preface local set found in MXF header metadata.");
// Resolve references
for ( ResolutionEntry resolutionEntry : resolutions ) {
resolutionEntry.resolve(referenceTable);
}
return new HeaderMetadataImpl(primerPack, preface);
}
public final static PartitionPack readPartitionPack(
InputStream stream)
throws IOException {
KeyAndConsumed kandc = readKey(stream);
return readPartitionPack(stream, kandc.getKey());
}
final static PartitionPack readPartitionPack(
InputStream stream,
UL key)
throws IOException {
long size = readBERLength(stream).getLength();
if (size > 4096l)
throw new MAJMXFStreamException("Extremely unlikely size for a partition pack '" + size + "' when reading a stream.");
ByteBuffer packValue = readValue(stream, size);
FixedLengthPack candidatePack = null;
try {
candidatePack = MXFBuilder.readFixedLengthPack(key, packValue);
}
catch (EndOfDataException eode) {
throw new MAJMXFStreamException("Insufficient bytes read from stream to create a valid partition pack.");
}
try {
return (PartitionPack) candidatePack;
}
catch (ClassCastException cce) {
throw new MAJMXFStreamException("Value read from stream was not a partition pack as expected, but rather an instance of '" +
candidatePack.getClass().getCanonicalName() + "'.");
}
}
public final static EssenceElement readEssenceElement(
InputStream stream)
throws IOException {
KeyAndConsumed kandc = readKey(stream);
return readEssenceElement(stream, kandc.getKey());
}
final static EssenceElement readEssenceElement(
InputStream stream,
UL essenceKey)
throws IOException {
long size = readBERLength(stream).getLength();
byte[] elementData = new byte[(int) size];
if (stream.read(elementData, 0, (int) size) < size) {
throw new MAJMXFStreamException("Failed to read complete essence element into memory.");
}
if (!EssenceElementImpl.isEssenceElement(essenceKey))
throw new MAJMXFStreamException("Expected essence element key but found '" + essenceKey.toString() + "'.");
return EssenceElementImpl.make(essenceKey, ByteBuffer.wrap(elementData));
}
public final static int readEssenceElementWithTrackID(
InputStream stream,
byte[] elementData)
throws IOException {
KeyAndConsumed kandc = readKey(stream);
return readEssenceElementWithTrackID(stream, kandc.getKey(), elementData);
}
final static int readEssenceElementWithTrackID(
InputStream stream,
UL essenceElementKey,
byte[] elementData)
throws IOException {
long size = readBERLength(stream).getLength();
if (elementData.length < size)
throw new MAJMXFStreamException("Insufficient space in element data array to read in an essence element.");
// FIXME handle bufferred streams, as for readEssenceElementWithBytesRead
if (stream.read(elementData, 0, (int) size) < size) {
throw new MAJMXFStreamException("Failed to read complete essence element into memory.");
}
if (!EssenceElementImpl.isEssenceElement(essenceElementKey))
throw new MAJMXFStreamException("Expected essence element key but found '" + essenceElementKey.toString() + "'.");
byte[] keyBytes = essenceElementKey.getUniversalLabel();
int essenceTrackID = ((keyBytes[12] & 0xff) << 24) | ((keyBytes[13] & 0xff) << 16) |
((keyBytes[14] & 0xff) << 8) | (keyBytes[15] & 0xff);
return essenceTrackID;
}
public final static int readEssenceElementWithBytesRead(
InputStream stream,
byte[] elementData)
throws IOException {
KeyAndConsumed kandc = readKey(stream);
return readEssenceElementWithBytesRead(stream, kandc.getKey(), elementData);
}
final static int readEssenceElementWithBytesRead(
InputStream stream,
UL essenceElementKey,
byte[] elementData)
throws IOException {
long size = readBERLength(stream).getLength();
if (elementData.length < size)
throw new MAJMXFStreamException("Insufficient space in element data array to read in an essence element.");
int totalBytesRead = 0;
while (totalBytesRead < size) {
int bytesRead = stream.read(elementData, totalBytesRead, (int) (size - totalBytesRead));
if (bytesRead <= -0) break;
totalBytesRead += bytesRead;
}
if (totalBytesRead < size) {
throw new MAJMXFStreamException("Failed to read complete essence element into memory.");
}
if (!EssenceElementImpl.isEssenceElement(essenceElementKey))
throw new MAJMXFStreamException("Expected essence element key but found '" + essenceElementKey.toString() + "'.");
return totalBytesRead;
}
public final static void writeEssenceElement(
OutputStream stream,
int essenceTrackID,
byte[] elementData)
throws IOException {
byte[] essenceElementBase = ((UL) EssenceElement.essenceElementBase).getUniversalLabel();
stream.write(essenceElementBase, 0, 12);
byte[] essenceTrackIDBytes = ByteBuffer.allocate(4).putInt(essenceTrackID).array();
stream.write(essenceTrackIDBytes);
writeBERLength(stream, elementData.length, 8);
stream.write(elementData);
}
public final static void writeEssenceElement(
OutputStream stream,
int essenceTrackID,
byte[] elementData,
int offset,
int length)
throws IOException {
byte[] essenceElementBase = ((UL) EssenceElement.essenceElementBase).getUniversalLabel();
stream.write(essenceElementBase, 0, 12);
byte[] essenceTrackIDBytes = ByteBuffer.allocate(4).putInt(essenceTrackID).array();
stream.write(essenceTrackIDBytes);
writeBERLength(stream, length, 8);
stream.write(elementData, offset, length);
}
public final static CPSystemItem readCPSystemItem(
InputStream stream)
throws IOException {
KeyAndConsumed kandc = readKey(stream);
return readCPSystemItem(stream, kandc.getKey());
}
final static CPSystemItem readCPSystemItem(
InputStream stream,
UL cpSystemItemKey)
throws IOException {
long size = readBERLength(stream).getLength();
byte[] cpSystemItemBytes = new byte[(int) size];
if (stream.read(cpSystemItemBytes, 0, (int) size) < size)
throw new MAJMXFStreamException("Failed to read complete CP system item into memory.");
if (!cpSystemItemKey.equals(CPSystemItemImpl.key))
throw new MAJMXFStreamException("Expected a CP system item key but found '" + cpSystemItemKey.toString() + "'.");
CPSystemItem cpSystemItem = CPSystemItemImpl.make(ByteBuffer.wrap(cpSystemItemBytes));
return cpSystemItem;
}
public final static IndexTableSegment readIndexTableSegment(
InputStream stream)
throws IOException {
KeyAndConsumed kandc = readKey(stream);
return readIndexTableSegment(stream, kandc.getKey());
}
final static IndexTableSegment readIndexTableSegment(
InputStream stream,
UL key)
throws IOException {
// TODO check the key?
long size = readBERLength(stream).getLength();
ByteBuffer indexValue = readValue(stream, size);
Map<AUIDImpl, MetadataObject> referenceTable = new HashMap<AUIDImpl, MetadataObject>();
List<ResolutionEntry> resolutions = new Vector<ResolutionEntry>();
try {
MetadataObject candidateSegment =
MXFBuilder.readLocalSet(key, indexValue, IndexTable.indexPrimer, referenceTable, resolutions);
return (IndexTableSegment) candidateSegment;
}
catch (Exception e) {
throw new MAJMXFStreamException(e.getClass().getName() + " throw when trying to read an index table segment.", e);
}
}
public final static RandomIndexPack readRandomIndexPack(
InputStream stream)
throws IOException {
KeyAndConsumed kandc = readKey(stream);
return readRandomIndexPack(stream, kandc.getKey());
}
final static RandomIndexPack readRandomIndexPack(
InputStream stream,
UL key)
throws IOException {
// TODO check the key?
long size = readBERLength(stream).getLength();
ByteBuffer ripBytes = readValue(stream, size);
try {
RandomIndexPack rip = RandomIndexPackImpl.createFromBytes(ripBytes);
return rip;
}
catch (BufferUnderflowException bue) {
throw new MAJMXFStreamException("Insufficient bytes in buffer to read a complete random index pack.");
}
}
public final static HeaderMetadata readFooterHeaderMetadata(
InputStream inputStream,
int pag)
throws IOException {
// TODO
return null;
}
public final static HeaderMetadata readFooterHeaderMetadata(
InputStream inputStream,
long footerPartitionOffset)
throws IOException {
// TODO
return null;
}
public final static void writePartitionPack(
OutputStream stream,
PartitionPack pack)
throws IOException {
long partitionPackSize = pack.getEncodedSize();
ByteBuffer partitionBytes = ByteBuffer.allocate((int) partitionPackSize);
try {
MXFBuilder.writeFixedLengthPack((FixedLengthPack) pack, partitionBytes);
}
catch (InsufficientSpaceException ise) {
throw new MAJMXFStreamException("Unexpetedly, insufficient space for partition pack in buffer.", ise);
}
ClassDefinition theClass = MediaEngine.getClassDefinition(pack);
writeKey(stream, (UL) theClass.getAUID());
writeBERLength(stream, partitionPackSize, 4);
writeValue(stream, partitionBytes);
}
public final static void writeHeaderMetadata(
OutputStream stream,
Preface preface)
throws IOException {
PrimerPack primerPack = new PrimerPackImpl();
primerPack.addLocalTagEntry(MXFConstants.InstanceTag, MXFConstants.InstanceUID);
long lengthOfAllSets = PrimerPackImpl.addPropertiesForObject(primerPack, preface);
ByteBuffer primerAndPreface = ByteBuffer.allocate((int) (lengthOfAllSets + PrimerPackImpl.lengthAsBytes(primerPack)));
try {
primerAndPreface.rewind();
PrimerPackImpl.writeAsBytes(primerPack, primerAndPreface);
List<PropertyValue> stillToWrite = new ArrayList<PropertyValue>();
MXFBuilder.writeLocalSet(preface, primerAndPreface, primerPack, stillToWrite);
while (stillToWrite.size() > 0) {
PropertyValue headItem = stillToWrite.remove(0);
MXFBuilder.writeLocalSet(headItem, primerAndPreface, primerPack, stillToWrite);
}
//System.out.println(primerPack);
}
catch (InsufficientSpaceException ise) {
throw new MAJMXFStreamException("Unxepectedly, insufficient space to write primer pack and local sets.", ise);
}
catch (BufferOverflowException boe) {
throw new MAJMXFStreamException("Unxepectedly, insufficient space to write primer pack and local sets.", boe);
}
writeValue(stream, primerAndPreface);
}
public final static void writeIndexTableSegment(
OutputStream stream,
IndexTableSegment indexTableSegment)
throws IOException {
long indexSegmentSize = MXFBuilder.lengthOfLocalSet(indexTableSegment);
ByteBuffer indexBuffer = ByteBuffer.allocate((int) (indexSegmentSize + 20));
try {
indexBuffer.rewind();
MXFBuilder.writeLocalSet(indexTableSegment, indexBuffer, IndexTable.indexPrimer, new ArrayList<PropertyValue>());
indexBuffer.rewind();
}
catch (InsufficientSpaceException ise) {
throw new MAJMXFStreamException("Unxepectedly, insufficient space to write index table segment local set.", ise);
}
catch (BufferOverflowException boe) {
throw new MAJMXFStreamException("Unxepectedly, insufficient space to write index table segment local set.", boe);
}
writeValue(stream, indexBuffer);
}
public final static void writeRandomIndexPack(
OutputStream stream,
RandomIndexPack rip)
throws IOException {
writeKey(stream, RandomIndexPack.ripKeyValue);
writeBERLength(stream, 12 * rip.count() + 4, 4);
for ( RandomIndexItem item : rip.getPartitionIndex() ) {
int bodySID = item.getBodySID();
stream.write(ByteBuffer.allocate(4).putInt(bodySID).array());
long byteOffset = item.getByteOffset();
stream.write(ByteBuffer.allocate(8).putLong(byteOffset).array());
}
stream.write(ByteBuffer.allocate(4).putInt(rip.getLength()).array());
}
public final static KeyAndConsumed readKey(
InputStream stream)
throws IOException {
byte[] keyBytes = new byte[16];
int bytesRead = stream.read(keyBytes);
if (bytesRead < 0)
throw new MAJMXFStreamException("Unexpectedly reached the end of the stream in the middle of reading a key.");
if (bytesRead < 16)
throw new MAJMXFStreamException("Insufficient bytes remaing in stream to read a complete key.");
long consumed = 16l;
while (bytesRead == 16) {
byte[] keySwap = new byte[16];
for ( int x = 0 ; x < 8 ; x++ ) {
keySwap[x] = keyBytes[x + 8];
keySwap[x + 8] = keyBytes[x];
}
UL readKey = new AUIDImpl(keySwap);
if (!MXFBuilder.isKLVFill(readKey)) {
return new KeyAndConsumed(readKey, consumed);
}
consumed += readPastFill(stream);
bytesRead = stream.read(keyBytes);
consumed += bytesRead;
}
throw new MAJMXFStreamException("Insufficient bytes remaing in stream to read a complete key.");
}
public final static UL readSingleKey(
InputStream stream)
throws IOException {
byte[] keyBytes = new byte[16];
int bytesRead = stream.read(keyBytes);
if (bytesRead < 0)
throw new MAJMXFStreamException("Unexpectedly reached the end of the stream in the middle of reading a key.");
if (bytesRead < 16)
throw new MAJMXFStreamException("Insufficient bytes remaing in stream to read a complete key.");
byte[] keySwap = new byte[16];
for ( int x = 0 ; x < 8 ; x++ ) {
keySwap[x] = keyBytes[x + 8];
keySwap[x + 8] = keyBytes[x];
}
UL readKey = new AUIDImpl(keySwap);
return readKey;
}
public static class KeyAndConsumed {
private UL key;
private long consumed;
public KeyAndConsumed(
UL key,
long consumed) {
this.key = key;
this.consumed = consumed;
}
public UL getKey() {
return key;
}
public long getConsumed() {
return consumed;
}
}
public final static LengthAndConsumed readBERLength(
InputStream stream)
throws IOException {
int first = stream.read();
if (first == -1)
throw new MAJMXFStreamException("Unexpectedly readed the end of the stream when reading a length.");
if (first < 128) // top bit set not set
return new LengthAndConsumed((long) first, 1l);
int berTailLength = (int) (first & 0x7f);
byte[] lengthData = new byte[berTailLength];
int bytesRead = stream.read(lengthData);
while (bytesRead < berTailLength) {
System.out.println("Bytes read less than BER tail length when reading length, with bytesRead = " + bytesRead +
" and berTailLength = " + berTailLength + " and input stream " + stream.getClass().getCanonicalName());
if (bytesRead < 0)
throw new MAJMXFStreamException("Unexpectedly reached the end of the stream after the first byte when reading a length.");
bytesRead += stream.read(lengthData, bytesRead, berTailLength - bytesRead);
}
// int bytesRead = stream.read(lengthData);
//
// if (bytesRead < 0)
// throw new MAJMXFStreamException("Unexpectedly reached the end of the stream after the first byte when reading a length.");
// if (bytesRead < berTailLength)
// throw new MAJMXFStreamException("Insufficient bytes available in a stream when reading a length.");
long lengthValue = 0l;
for ( int u = 0 ; u < lengthData.length ; u++ )
lengthValue = (lengthValue << 8) |
(((lengthData[u]) >= 0) ? lengthData[u] : 256 + lengthData[u]);
return new LengthAndConsumed(lengthValue, 1l + berTailLength);
}
public final static class LengthAndConsumed {
private long length;
private long consumed;
public LengthAndConsumed(
long length,
long consumed) {
this.length = length;
this.consumed = consumed;
}
public long getLength() {
return length;
}
public long getConsumed() {
return consumed;
}
public long getTotal() {
return length + consumed;
}
}
public final static ByteBuffer readValue(
InputStream stream,
long size)
throws IOException {
if (size > Runtime.getRuntime().freeMemory()) {
Runtime.getRuntime().gc();
if (size > Runtime.getRuntime().freeMemory())
throw new MAJMXFStreamException("Insufficient memory to read stream content value of size '" + size +
"' into a byte buffer.");
}
if (size > Integer.MAX_VALUE) {
throw new MAJMXFStreamException("MAJ can only work with values up to '" + Integer.MAX_VALUE + "' in length.");
}
byte[] valueBytes = new byte[(int) size];
int bytesRead = stream.read(valueBytes);
while (bytesRead < size) {
System.out.println("Bytes read less than size on value read, with bytesRead = " + bytesRead + " and size = " + size + ".");
if (bytesRead == -1)
throw new MAJMXFStreamException("Unexpectedly reached the end of the stream when reading a value.");
bytesRead += stream.read(valueBytes, bytesRead, (int) (size - bytesRead));
}
return ByteBuffer.wrap(valueBytes);
}
public final static void writeKey(
OutputStream stream,
UL key)
throws IOException {
if (stream == null)
throw new NullPointerException("Cannot write a key to a null stream.");
if (key == null)
throw new NullPointerException("Cannot write a null key to a stream.");
byte[] keyBytes = key.getUniversalLabel();
// Fix up class identifiers
if ((keyBytes[4] == 0x02) && (keyBytes[5] == 0x06) && (keyBytes[6] == 0x01))
keyBytes[5] = 0x53;
stream.write(keyBytes);
}
public final static void writeBERLength(
OutputStream stream,
long length,
int encodedBytes)
throws IOException {
if (stream == null)
throw new NullPointerException("Cannot write a BER length to a null stream.");
if (length < 0)
throw new IllegalArgumentException("Cannot write a negative length value.");
if ((encodedBytes < 1) || (encodedBytes > 9))
throw new IllegalArgumentException("The number of encoded bytes must be between 1 and 9.");
if (encodedBytes == 1) {
if (length > 127)
throw new IllegalArgumentException("The number of encoded bytes is 1 but the length is greater than 127.");
stream.write((byte) length);
return;
}
encodedBytes--;
long maxValue = 2l << (encodedBytes * 8);
if (length >= maxValue)
throw new IllegalArgumentException("The given length of " + length + " is greater than the maximum value for the given number of bytes to encode at " + maxValue + ".");
// Write the length byte
stream.write(0x80 + encodedBytes);
for ( int x = (encodedBytes - 1) ; x >= 0 ; x-- ) {
long mask = 0xff << (x * 8);
stream.write((int) ((length & mask) >> (x * 8)));
}
}
public final static void writeValue(
OutputStream stream,
ByteBuffer buffer)
throws IOException {
buffer.rewind();
if (buffer.hasArray()) {
stream.write(buffer.array());
}
else {
while(buffer.hasRemaining()) {
stream.write(buffer.get());
}
buffer.rewind();
}
}
final static byte[] zeroBytes = new byte[4096];
static {
for ( int x = 0 ; x < zeroBytes.length ; x++ )
zeroBytes[x] = (byte) 0;
}
public final static void writeFill(
OutputStream stream,
long totalLength)
throws IOException {
if (stream == null)
throw new NullPointerException("Cannot write a KLV fill item into a null stream.");
if (totalLength < 20l)
throw new IllegalArgumentException("Cannot write a fill value less than 20 bytes and '" + totalLength + "' is requested.");
writeKey(stream, (UL) MXFConstants.KLVFill);
int encodedLength = (totalLength < (2 << 24)) ? 4 : 8;
totalLength -= (16 + encodedLength);
writeBERLength(stream, totalLength, encodedLength);
long bytesWritten = 0l;
for ( long x = zeroBytes.length ; x < totalLength ; x += zeroBytes.length ) {
stream.write(zeroBytes);
bytesWritten += zeroBytes.length;
}
stream.write(zeroBytes, 0, (int) (totalLength - bytesWritten));
}
public final static long readPastFill(
InputStream stream)
throws IOException {
LengthAndConsumed landc = readBERLength(stream);
skipForward(stream, landc.getLength());
return landc.getTotal();
}
public final static long skipForward(
InputStream sourceStream,
long bytesToSkip)
throws IOException {
long bytesSkipped = 0l;
long bytesSkippedThisTime = 0l;
while (bytesSkipped < bytesToSkip) {
bytesSkippedThisTime = sourceStream.skip(bytesToSkip - bytesSkipped);
if (bytesSkippedThisTime <= 0l)
break;
bytesSkipped += bytesSkippedThisTime;
}
return bytesSkipped;
}
}