summaryrefslogtreecommitdiffstats
path: root/mpeglib/lib/mpegplay/videoDecoder.cpp
blob: b71442914a965f537d33282d450dfe3247156598 (plain)
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
/*
  mpeg I video decoder (derived from mpeg_play)
  Copyright (C) 2000  Martin Vogt

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU Library General Public License as published by
  the Free Software Foundation.

  For more information look at the file COPYRIGHT in this package

 */



#include "videoDecoder.h"

using namespace std;



VideoDecoder::VideoDecoder(MpegVideoStream* inputStream,
			   MpegVideoHeader* initSequence) {

  /* Check for legal buffer length. */

  init_tables();


  /* Initialize fields that used to be global */

  mpegVideoStream=inputStream;
  decoderClass=new DecoderClass(this,mpegVideoStream);
  recon=new Recon();
  motionVector=new MotionVector();
  slice=new Slice();
  group=new GOP();
  mpegVideoHeader=new MpegVideoHeader();
  picture=new Picture();
  macroBlock=new MacroBlock(this);

  // init this stream with the init sequence
  initSequence->copyTo(mpegVideoHeader);

  syncState=SYNC_TO_CLOSED_GOP;
  extension=new MpegExtension();
  frameCounter=0;
}


VideoDecoder::~VideoDecoder() {

  delete mpegVideoHeader;
  delete picture;
  delete decoderClass;
  delete recon;
  delete motionVector;
  delete slice;
  delete group;
  delete extension;
  delete macroBlock;
}





/*
 *--------------------------------------------------------------
 *
 * mpegVidRsrc --
 *
 *      Parses bit stream until MB_TQUANTUM number of
 *      macroblocks have been decoded or current slice or
 *      picture ends, whichever comes first. If the start
 *      of a frame is encountered, the frame is time stamped
 *      with the value passed in time_stamp. If the value
 *      passed in buffer is not null, the video stream buffer
 *      is set to buffer and the length of the buffer is
 *      expected in value passed in through length. The current
 *      video stream is set to vid_stream. If vid_stream
 *      is passed as NULL, a new VideoDecoder structure is created
 *      and initialized and used as the current video stream.
 *
 * Results:
 *      A pointer to the video stream structure used.
 *
 * Side effects:
 *      Bit stream is irreversibly parsed. If a picture is completed,
 *      a function is called to display the frame at the correct time.
 *
 *--------------------------------------------------------------
 */

int VideoDecoder::mpegVidRsrc(PictureArray* pictureArray) {
  int back=_SYNC_TO_NONE;

  unsigned int data;
  int i;


  /*
   * If called for the first time, find start code, make sure it is a
   * sequence start code.
   */


  /* Get next 32 bits (size of start codes). */

  data=mpegVideoStream->showBits(32);


  /*
   * Process according to start code (or parse macroblock if not a start code
   * at all).
   */
  switch (data) {
    /*
  case PACK_START_CODE:
  case SYSTEM_HEADER_START_CODE:  
    cout << "Packet in Loop **************"<<endl;
    mpegVideoStream->flushBits(32);
    packet->read_sys(data,vid_stream->bufferReader);
    */
  case SETQ_END_CODE:
  case ISO_11172_END_CODE:   /*  handle ISO_11172_END_CODE too */

    /* Display last frame. */

    // removed!

    /* Sequence done. Do the right thing. For right now, exit. */


    cout << "******** flushin end code"<<endl;
    mpegVideoStream->flushBits(32);
    goto done;
    break;
  case EXT_START_CODE:
    cout << "found EXT_START_CODE skipping"<<endl;
    mpegVideoStream->flushBits(32);
    /* Goto next start code. */
    mpegVideoStream->next_start_code();
 
    break;
  case USER_START_CODE:
    mpegVideoStream->flushBits(32);
    /* Goto next start code. */
    mpegVideoStream->next_start_code();

    break;
  case SETQ_START_CODE:
    
    /* Sequence start code. Parse sequence header. */
    if (ParseSeqHead() == false) {
      printf("SETQ_START_CODE 1-error\n");
      goto error;
    }
    goto done;

  case GOP_START_CODE:
    /* Group of Pictures start code. Parse gop header. */
    if (ParseGOP() == false) {
      printf("GOP_START_CODE 1-error\n");
      goto error;
    }
    goto done;

  case PICTURE_START_CODE:

    /* Picture start code. Parse picture header and first slice header. */

    
    back=ParsePicture();
    if (back != _SYNC_TO_NONE) {
      //cout << "skip B Frame we are late"<<endl;
      return back;
    }

    // parse ok
    if (ParseSlice() == false) {
      printf("PICTURE_START_CODE 2-error\n");
      goto error;
    }
    break;

  case SEQUENCE_ERROR_CODE:
    mpegVideoStream->flushBits(32);
    mpegVideoStream->next_start_code();

    goto done;

    
  default:

    /* Check for slice start code. */
    if ((data >= SLICE_MIN_START_CODE) && (data <= SLICE_MAX_START_CODE)) {

      /* Slice start code. Parse slice header. */
      if (ParseSlice() == false) {
	printf("default 1-error\n");
        goto error;
      }
    }
    break;
  }

  /* Parse next MB_TQUANTUM macroblocks. */
  for (i = 0; i < MB_TQUANTUM; i++) {

    /* Check to see if actually a startcode and not a macroblock. */
    data=mpegVideoStream->showBits(23);
    if (data != 0x0) {
      /* Not start code. Parse Macroblock. fill yuv pictures*/
      if (macroBlock->processMacroBlock(pictureArray) == false) {
        goto error;
      }
    } else {
      /* Not macroblock, actually start code. Get start code. */
      mpegVideoStream->next_start_code();

      /*
       * If start code is outside range of slice start codes, frame is
       * complete, display frame.
       */
      data=mpegVideoStream->showBits(32);

      if (((data < SLICE_MIN_START_CODE) || (data > SLICE_MAX_START_CODE)) &&
	  (data != SEQUENCE_ERROR_CODE)) {
	doPictureDisplay(pictureArray);
      }
      goto done;
    }
  }
  data=mpegVideoStream->showBits(23);
  /* Check if we just finished a picture on the MB_TQUANTUM macroblock */
  if (data == 0x0) {
    mpegVideoStream->next_start_code();

    data=mpegVideoStream->showBits(32);
    if ((data < SLICE_MIN_START_CODE) || (data > SLICE_MAX_START_CODE)) {
      doPictureDisplay(pictureArray);
    }
  }

  /* Return pointer to video stream structure. */

  goto done;

error:
  init_tables();
  back=_SYNC_TO_GOP;
  mpegVideoHeader->init_quanttables();

  goto done;

done:
  return back;

}






int VideoDecoder::ParseSeqHead() {
  int back;

  /* Flush off sequence start code. */

  mpegVideoStream->flushBits(32);

  back=mpegVideoHeader->parseSeq(mpegVideoStream);

  return back;

}




int VideoDecoder::ParseGOP() {
  if (syncState==SYNC_TO_CLOSED_GOP) {
    syncState=SYNC_HAS_CLOSED_GOP;
  }

  return group->processGOP(mpegVideoStream);
}




int VideoDecoder::ParsePicture() {
  int back;
  back=picture->processPicture(mpegVideoStream);

  macroBlock->resetPastMacroBlock();
  if (back == false) {
    return _SYNC_TO_GOP;
  }


  return _SYNC_TO_NONE;
}



int VideoDecoder::ParseSlice() {

  
  slice->parseSlice(mpegVideoStream);
  macroBlock->resetMacroBlock();
  decoderClass->resetDCT();
  return true;
}




/**
   After a seek we can only start with an I frame
*/

void VideoDecoder::resyncToI_Frame() {

  syncState=SYNC_TO_CLOSED_GOP;
}


void VideoDecoder::doPictureDisplay(PictureArray* pictureArray) {


  // insert end timestamp to current picture
  YUVPicture* pic=pictureArray->getCurrent();
  unsigned int code_type=picture->getCodeType();

  TimeStamp* startTimeStamp=picture->getStartOfPicStamp();

  pic->setStartTimeStamp(startTimeStamp);
  float rate=mpegVideoHeader->getPictureRate();

  pictureArray->setPicturePerSecond(rate);



  pic->setMpegPictureType(code_type);

  if (syncState < SYNC_HAS_CLOSED_GOP) {
    return;
  }
  if (syncState < SYNC_HAS_I_FRAME_SYNC) {
    if (code_type != I_TYPE) {
      return;
    }
  }
  if (code_type == I_TYPE) {
    YUVPicture* past=pictureArray->getPast();
    YUVPicture* future=pictureArray->getFuture();
    YUVPicture* current=pictureArray->getCurrent();

    YUVPicture* tmp=past;
    past = future;
    future = current;
    current = tmp;
    
    pic=past;

  
    pictureArray->setPast(past);
    pictureArray->setCurrent(current);
    pictureArray->setFuture(future);

    if (syncState < SYNC_HAS_I_FRAME_SYNC) {
      syncState=SYNC_HAS_I_FRAME_SYNC;
      return;
    }
    if (syncState == SYNC_HAS_P_FRAME_SYNC) {
      syncState=SYNC_HAS_FRAME_SYNC;
      return;
    }     
    if (syncState == SYNC_HAS_I_FRAME_SYNC) {
      syncState=SYNC_HAS_P_FRAME_SYNC;
      return;
    }    


  
  }
  
  if (code_type == P_TYPE) {
    YUVPicture* past=pictureArray->getPast();
    YUVPicture* future=pictureArray->getFuture();
    YUVPicture* current=pictureArray->getCurrent();

    YUVPicture* tmp=past;
    past = future;
    future = current;
    current = tmp;
       
    pic = past;


   
    pictureArray->setPast(past);
    pictureArray->setCurrent(current);
    pictureArray->setFuture(future);

    if (syncState < SYNC_HAS_P_FRAME_SYNC) {
      syncState=SYNC_HAS_P_FRAME_SYNC;
      return;
    }

  }  
  if (code_type == B_TYPE) {
    if (syncState == SYNC_HAS_P_FRAME_SYNC) {
      syncState=SYNC_HAS_FRAME_SYNC;
      YUVPicture* past=pictureArray->getPast();
      pic=past;
    }   
    /**
       Now check for PTS timeStamp error. It seems some encoders
       handles this different.
       If the P frame has a timeStamp earlier than our B stamp
       we swap them.
    */
    YUVPicture* pframe=pictureArray->getFuture();
    YUVPicture* bframe=pictureArray->getCurrent();

    TimeStamp* pTime=pframe->getStartTimeStamp();
    TimeStamp* bTime=bframe->getStartTimeStamp();

    double pPTS=pTime->getPTSTimeStamp();
    double bPTS=bTime->getPTSTimeStamp();
    if (pPTS < bPTS) {
      //cout << "********P/B Frame PTS error -> enable swap and pray"<<endl;
      bTime->copyTo(pTime);
    }
   


    // we display the current picture
    // (already set)
  }

  
  if (pic == NULL) {
    cout << "pic NULL"<<endl;
    exit(0);
    return;
  }
  if (syncState < SYNC_HAS_FRAME_SYNC) {
    return;
  }

  double val=pictureArray->getPicturePerSecond();
  pic->setPicturePerSecond(val);

  TimeStamp* currentStamp=pic->getStartTimeStamp();


  frameCounter++;

  if (currentStamp->getPTSFlag()==true) {
    frameCounter=0;
  }
  currentStamp->setVideoFrameCounter(frameCounter);


  // let plugin "rip" the picture
  pictureArray->setYUVPictureCallback(pic);
}