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
|
/*
Copyright (c) 2004-2011, John Hurst
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*! \file MPEG2_Parser.cpp
\version $Id$
\brief AS-DCP library, MPEG2 raw essence reader implementation
*/
#include <KM_fileio.h>
#include <MPEG.h>
#include <KM_log.h>
using Kumu::DefaultLogSink;
using namespace ASDCP;
using namespace ASDCP::MPEG2;
// data will be read from a VES file in chunks of this size
const ui32_t VESReadSize = 4 * Kumu::Kilobyte;
//------------------------------------------------------------------------------------------
namespace ASDCP {
namespace MPEG2
{
//
enum ParserState_t {
ST_INIT,
ST_SEQ,
ST_PIC,
ST_GOP,
ST_EXT,
ST_SLICE,
};
const char*
StringParserState(ParserState_t state)
{
switch ( state )
{
case ST_INIT: return "INIT";
case ST_SEQ: return "SEQ";
case ST_PIC: return "PIC";
case ST_GOP: return "GOP";
case ST_EXT: return "EXT";
case ST_SLICE: return "SLICE";
}
return "*UNKNOWN*";
}
//
class h__ParserState
{
ParserState_t m_State;
ASDCP_NO_COPY_CONSTRUCT(h__ParserState);
public:
h__ParserState() : m_State(ST_INIT) {}
~h__ParserState() {}
inline bool Test_SLICE() { return m_State == ST_SLICE; }
inline void Reset() { m_State = ST_INIT; }
//
inline Result_t Goto_SEQ()
{
switch ( m_State )
{
case ST_INIT:
case ST_EXT:
m_State = ST_SEQ;
return RESULT_OK;
default:
break;
}
DefaultLogSink().Error("SEQ follows %s\n", StringParserState(m_State));
return RESULT_STATE;
}
//
inline Result_t Goto_SLICE()
{
switch ( m_State )
{
case ST_PIC:
case ST_EXT:
m_State = ST_SLICE;
return RESULT_OK;
default:
break;
}
DefaultLogSink().Error("Slice follows %s\n", StringParserState(m_State));
return RESULT_STATE;
}
//
inline Result_t Goto_PIC()
{
switch ( m_State )
{
case ST_INIT:
case ST_SEQ:
case ST_GOP:
case ST_EXT:
m_State = ST_PIC;
return RESULT_OK;
default:
break;
}
DefaultLogSink().Error("PIC follows %s\n", StringParserState(m_State));
return RESULT_STATE;
}
//
inline Result_t Goto_GOP()
{
switch ( m_State )
{
case ST_EXT:
case ST_SEQ:
m_State = ST_GOP;
return RESULT_OK;
default:
break;
}
DefaultLogSink().Error("GOP follows %s\n", StringParserState(m_State));
return RESULT_STATE;
}
//
inline Result_t Goto_EXT()
{
switch ( m_State )
{
case ST_PIC:
case ST_EXT:
case ST_SEQ:
case ST_GOP:
m_State = ST_EXT;
return RESULT_OK;
default:
break;
}
DefaultLogSink().Error("EXT follows %s\n", StringParserState(m_State));
return RESULT_STATE;
}
};
//------------------------------------------------------------------------------------------
// This is a parser delagate that reads the stream params from a
// sequence header and sequence extension header. The parser is
// commanded to return after processing the sequence extension
// header.
class StreamParams : public VESParserDelegate
{
h__ParserState m_State;
ASDCP_NO_COPY_CONSTRUCT(StreamParams);
public:
VideoDescriptor m_VDesc;
StreamParams()
{
m_VDesc.ContainerDuration = 0;
m_VDesc.ComponentDepth = 8;
}
~StreamParams() {}
//
Result_t Sequence(VESParser*, const byte_t* b, ui32_t)
{
Result_t result = m_State.Goto_SEQ();
if ( ASDCP_FAILURE(result) )
return result;
Accessor::Sequence SEQ(b);
m_VDesc.AspectRatio = SEQ.AspectRatio();
m_VDesc.FrameRate = SEQ.FrameRate();
m_VDesc.StoredWidth = SEQ.HorizontalSize();
m_VDesc.StoredHeight = SEQ.VerticalSize();
m_VDesc.BitRate = SEQ.BitRate();
m_VDesc.EditRate = SEQ.Pulldown() ? Rational(SEQ.FrameRate() * 1000, 1001) : Rational(SEQ.FrameRate(), 1);
m_VDesc.SampleRate = m_VDesc.EditRate;
return RESULT_OK;
}
//
Result_t Extension(VESParser*, const byte_t* b, ui32_t)
{
Result_t result = m_State.Goto_EXT();
if ( ASDCP_FAILURE(result) )
return result;
Accessor::SequenceEx SEQX(b);
m_VDesc.ProfileAndLevel = SEQX.ProfileAndLevel();
m_VDesc.FrameLayout = SEQX.Progressive() ? 0 : 1;
m_VDesc.CodedContentType = SEQX.Progressive() ? 1 : 2;
m_VDesc.LowDelay = SEQX.LowDelay();
m_VDesc.HorizontalSubsampling = SEQX.ChromaFormat() == 3 ? 1 : 2;
m_VDesc.VerticalSubsampling = SEQX.ChromaFormat() >= 3 ? 1 : 2;
if ( ( m_VDesc.HorizontalSubsampling == 2 ) && ( m_VDesc.VerticalSubsampling == 2 ) )
m_VDesc.ColorSiting = 3; // 4:2:0
else if ( ( m_VDesc.HorizontalSubsampling == 2 ) && ( m_VDesc.VerticalSubsampling == 1 ) )
m_VDesc.ColorSiting = 4; // 4:2:2
else if ( ( m_VDesc.HorizontalSubsampling == 1 ) && ( m_VDesc.VerticalSubsampling == 1 ) )
m_VDesc.ColorSiting = 0; // 4:4:4
// TODO: get H&V size and bit rate extensions
return RESULT_FALSE;
}
Result_t GOP(VESParser*, const byte_t*, ui32_t) { return RESULT_FALSE; }
Result_t Picture(VESParser*, const byte_t*, ui32_t) { return RESULT_FALSE; }
Result_t Slice(VESParser*, byte_t) { return RESULT_FALSE; }
Result_t Data(VESParser*, const byte_t*, i32_t) { return RESULT_OK; }
};
//------------------------------------------------------------------------------------------
// This is a parser delagate that reads a VES stream and sets public
// instance variables to indicate state. It is used below to read an
// entire frame into a buffer. The delegate retains metadata about the
// frame for later access.
//
class FrameParser : public VESParserDelegate
{
h__ParserState m_State;
ASDCP_NO_COPY_CONSTRUCT(FrameParser);
public:
ui32_t m_FrameSize;
bool m_CompletePicture;
bool m_HasGOP;
bool m_ClosedGOP;
ui8_t m_TemporalRef;
ui32_t m_PlaintextOffset;
FrameType_t m_FrameType;
FrameParser()
{
Reset();
}
~FrameParser() {}
void Reset()
{
m_FrameSize = 0;
m_HasGOP = m_ClosedGOP = false;
m_CompletePicture = false;
m_TemporalRef = 0;
m_PlaintextOffset = 0;
m_FrameType = FRAME_U;
m_State.Reset();
}
Result_t Sequence(VESParser*, const byte_t*, ui32_t s)
{
if ( m_State.Test_SLICE() )
{
m_CompletePicture = true;
return RESULT_FALSE;
}
m_FrameSize += s;
return m_State.Goto_SEQ();
}
Result_t Picture(VESParser*, const byte_t* b, ui32_t s)
{
if ( m_State.Test_SLICE() )
{
m_CompletePicture = true;
return RESULT_FALSE;
}
Accessor::Picture pic(b);
m_TemporalRef = pic.TemporalRef();
m_FrameType = pic.FrameType();
m_FrameSize += s;
return m_State.Goto_PIC();
}
Result_t Slice(VESParser*, byte_t slice_id)
{
if ( slice_id == FIRST_SLICE )
{
m_PlaintextOffset = m_FrameSize;
return m_State.Goto_SLICE();
}
return m_State.Test_SLICE() ? RESULT_OK : RESULT_FAIL;
}
Result_t Extension(VESParser*, const byte_t*, ui32_t s)
{
m_FrameSize += s;
return m_State.Goto_EXT();
}
Result_t GOP(VESParser*, const byte_t* b, ui32_t s)
{
Accessor::GOP GOP(b);
m_ClosedGOP = GOP.Closed();
m_HasGOP = true;
m_FrameSize += s;
return m_State.Goto_GOP();
}
Result_t Data(VESParser*, const byte_t*, i32_t s)
{
m_FrameSize += s;
return RESULT_OK;
}
};
//------------------------------------------------------------------------------------------
// The following code assumes the following things:
// - each frame will begin with a picture header or a sequence header
// - any frame that begins with a sequence header is an I frame and is
// assumed to contain a GOP header, a picture header and complete picture data
// - any frame that begins with a picture header is either an I, B or P frame
// and is assumed to contain a complete picture header and picture data
class Parser::h__Parser
{
StreamParams m_ParamsDelegate;
FrameParser m_ParserDelegate;
VESParser m_Parser;
Kumu::FileReader m_FileReader;
ui32_t m_FrameNumber;
bool m_EOF;
ASDCP::MPEG2::FrameBuffer m_TmpBuffer;
ASDCP_NO_COPY_CONSTRUCT(h__Parser);
public:
h__Parser() : m_TmpBuffer(VESReadSize*8) {}
~h__Parser() { Close(); }
Result_t OpenRead(const std::string& filename);
void Close();
Result_t Reset();
Result_t ReadFrame(FrameBuffer&);
Result_t FillVideoDescriptor(VideoDescriptor&);
};
} // namespace MPEG2
} // namespace asdcp
//
Result_t
ASDCP::MPEG2::Parser::h__Parser::Reset()
{
m_FrameNumber = 0;
m_EOF = false;
m_FileReader.Seek(0);
m_ParserDelegate.Reset();
return RESULT_OK;
}
//
void
ASDCP::MPEG2::Parser::h__Parser::Close()
{
m_FileReader.Close();
}
//
ASDCP::Result_t
ASDCP::MPEG2::Parser::h__Parser::OpenRead(const std::string& filename)
{
ui32_t read_count = 0;
Result_t result = m_FileReader.OpenRead(filename);
if ( ASDCP_SUCCESS(result) )
result = m_FileReader.Read(m_TmpBuffer.Data(), m_TmpBuffer.Capacity(), &read_count);
if ( ASDCP_SUCCESS(result) )
{
const byte_t* p = m_TmpBuffer.RoData();
// the mxflib parser demanded the file start with a sequence header.
// Since no one complained and that's the easiest thing to implement,
// I have left it that way. Let me know if you want to be able to
// locate the first GOP in the stream.
ui32_t i = 0;
while ( p[i] == 0 ) i++;
if ( i < 2 || p[i] != 1 || ! ( p[i+1] == SEQ_START || p[i+1] == PIC_START ) )
{
DefaultLogSink().Error("Frame buffer does not begin with a PIC or SEQ start code.\n");
return RESULT_RAW_FORMAT;
}
if ( ASDCP_SUCCESS(result) )
{
m_Parser.SetDelegate(&m_ParamsDelegate);
result = m_Parser.Parse(p, read_count);
}
}
if ( ASDCP_SUCCESS(result) )
{
ui64_t tmp = m_FileReader.Size() / 65536; // a gross approximation
m_ParamsDelegate.m_VDesc.ContainerDuration = (ui32_t) tmp;
m_Parser.SetDelegate(&m_ParserDelegate);
m_FileReader.Seek(0);
}
if ( ASDCP_FAILURE(result) )
{
DefaultLogSink().Error("Unable to identify a wrapping mode for the essence in file \"%s\"\n", filename.c_str());
m_FileReader.Close();
}
return result;}
//
//
ASDCP::Result_t
ASDCP::MPEG2::Parser::h__Parser::ReadFrame(FrameBuffer& FB)
{
Result_t result = RESULT_OK;
ui32_t write_offset = 0;
ui32_t read_count = 0;
FB.Size(0);
if ( m_EOF )
return RESULT_ENDOFFILE;
// Data is read in VESReadSize chunks. Each chunk is parsed, and the
// process is stopped when a Sequence or Picture header is found or when
// the input file is exhausted. The partial next frame is cached for the
// next call.
m_ParserDelegate.Reset();
m_Parser.Reset();
if ( m_TmpBuffer.Size() > 0 )
{
memcpy(FB.Data(), m_TmpBuffer.RoData(), m_TmpBuffer.Size());
result = m_Parser.Parse(FB.RoData(), m_TmpBuffer.Size());
write_offset = m_TmpBuffer.Size();
m_TmpBuffer.Size(0);
}
while ( ! m_ParserDelegate.m_CompletePicture && result == RESULT_OK )
{
if ( FB.Capacity() < ( write_offset + VESReadSize ) )
{
DefaultLogSink().Error("FrameBuf.Capacity: %u FrameLength: %u\n",
FB.Capacity(), ( write_offset + VESReadSize ));
return RESULT_SMALLBUF;
}
result = m_FileReader.Read(FB.Data() + write_offset, VESReadSize, &read_count);
if ( result == RESULT_ENDOFFILE || read_count == 0 )
{
m_EOF = true;
if ( write_offset > 0 )
result = RESULT_OK;
}
if ( ASDCP_SUCCESS(result) )
{
result = m_Parser.Parse(FB.RoData() + write_offset, read_count);
write_offset += read_count;
}
if ( m_EOF )
break;
}
assert(m_ParserDelegate.m_FrameSize <= write_offset);
if ( ASDCP_SUCCESS(result)
&& m_ParserDelegate.m_FrameSize < write_offset )
{
assert(m_TmpBuffer.Size() == 0);
ui32_t diff = write_offset - m_ParserDelegate.m_FrameSize;
assert(diff <= m_TmpBuffer.Capacity());
memcpy(m_TmpBuffer.Data(), FB.RoData() + m_ParserDelegate.m_FrameSize, diff);
m_TmpBuffer.Size(diff);
}
if ( ASDCP_SUCCESS(result) )
{
const byte_t* p = FB.RoData();
if ( p[0] != 0 || p[1] != 0 || p[2] != 1 || ! ( p[3] == SEQ_START || p[3] == PIC_START ) )
{
DefaultLogSink().Error("Frame buffer does not begin with a PIC or SEQ start code.\n");
return RESULT_RAW_FORMAT;
}
}
if ( ASDCP_SUCCESS(result) )
{
FB.Size(m_ParserDelegate.m_FrameSize);
FB.TemporalOffset(m_ParserDelegate.m_TemporalRef);
FB.FrameType(m_ParserDelegate.m_FrameType);
FB.PlaintextOffset(m_ParserDelegate.m_PlaintextOffset);
FB.FrameNumber(m_FrameNumber++);
FB.GOPStart(m_ParserDelegate.m_HasGOP);
FB.ClosedGOP(m_ParserDelegate.m_ClosedGOP);
}
return result;
}
// Fill a VideoDescriptor struct with the values from the file's header.
ASDCP::Result_t
ASDCP::MPEG2::Parser::h__Parser::FillVideoDescriptor(VideoDescriptor& VDesc)
{
VDesc = m_ParamsDelegate.m_VDesc;
return RESULT_OK;
}
//------------------------------------------------------------------------------------------
ASDCP::MPEG2::Parser::Parser()
{
}
ASDCP::MPEG2::Parser::~Parser()
{
}
// Opens the stream for reading, parses enough data to provide a complete
// set of stream metadata for the MXFWriter below.
ASDCP::Result_t
ASDCP::MPEG2::Parser::OpenRead(const std::string& filename) const
{
const_cast<ASDCP::MPEG2::Parser*>(this)->m_Parser = new h__Parser;
Result_t result = m_Parser->OpenRead(filename);
if ( ASDCP_FAILURE(result) )
const_cast<ASDCP::MPEG2::Parser*>(this)->m_Parser.release();
return result;
}
// Rewinds the stream to the beginning.
ASDCP::Result_t
ASDCP::MPEG2::Parser::Reset() const
{
if ( m_Parser.empty() )
return RESULT_INIT;
return m_Parser->Reset();
}
// Places a frame of data in the frame buffer. Fails if the buffer is too small
// or the stream is empty.
ASDCP::Result_t
ASDCP::MPEG2::Parser::ReadFrame(FrameBuffer& FB) const
{
if ( m_Parser.empty() )
return RESULT_INIT;
return m_Parser->ReadFrame(FB);
}
ASDCP::Result_t
ASDCP::MPEG2::Parser::FillVideoDescriptor(VideoDescriptor& VDesc) const
{
if ( m_Parser.empty() )
return RESULT_INIT;
return m_Parser->FillVideoDescriptor(VDesc);
}
//
// end MPEG2_Parser.cpp
//
|