]> Creatis software - gdcm.git/blob - src/gdcmmpeg2/src/mpeg2dec/getpic.c
COMP: Fix compilation on Win32 system without unistd.h but instead io.h
[gdcm.git] / src / gdcmmpeg2 / src / mpeg2dec / getpic.c
1 /* getpic.c, picture decoding                                               */
2
3 /* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
4
5 /*
6  * Disclaimer of Warranty
7  *
8  * These software programs are available to the user without any license fee or
9  * royalty on an "as is" basis.  The MPEG Software Simulation Group disclaims
10  * any and all warranties, whether express, implied, or statuary, including any
11  * implied warranties or merchantability or of fitness for a particular
12  * purpose.  In no event shall the copyright-holder be liable for any
13  * incidental, punitive, or consequential damages of any kind whatsoever
14  * arising from the use of these programs.
15  *
16  * This disclaimer of warranty extends to the user of these programs and user's
17  * customers, employees, agents, transferees, successors, and assigns.
18  *
19  * The MPEG Software Simulation Group does not represent or warrant that the
20  * programs furnished hereunder are free of infringement of any third-party
21  * patents.
22  *
23  * Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
24  * are subject to royalty fees to patent holders.  Many of these patents are
25  * general enough such that they are unavoidable regardless of implementation
26  * design.
27  *
28  */
29
30 #include <stdio.h>
31
32 #include "config.h"
33 #include "global.h"
34
35 /* private prototypes*/
36 static void picture_data _ANSI_ARGS_((int framenum));
37 static void macroblock_modes _ANSI_ARGS_((int *pmacroblock_type, int *pstwtype,
38   int *pstwclass, int *pmotion_type, int *pmotion_vector_count, int *pmv_format, int *pdmv,
39   int *pmvscale, int *pdct_type));
40 static void Clear_Block _ANSI_ARGS_((int comp));
41 static void Sum_Block _ANSI_ARGS_((int comp));
42 static void Saturate _ANSI_ARGS_((short *bp));
43 static void Add_Block _ANSI_ARGS_((int comp, int bx, int by,
44   int dct_type, int addflag));
45 static void Update_Picture_Buffers _ANSI_ARGS_((void));
46 static void frame_reorder _ANSI_ARGS_((int bitstream_framenum, 
47   int sequence_framenum));
48 static void Decode_SNR_Macroblock _ANSI_ARGS_((int *SNRMBA, int *SNRMBAinc, 
49   int MBA, int MBAmax, int *dct_type));
50
51 static void motion_compensation _ANSI_ARGS_((int MBA, int macroblock_type, 
52  int motion_type, int PMV[2][2][2], int motion_vertical_field_select[2][2], 
53  int dmvector[2], int stwtype, int dct_type));
54
55 static void skipped_macroblock _ANSI_ARGS_((int dc_dct_pred[3], 
56   int PMV[2][2][2], int *motion_type, int motion_vertical_field_select[2][2],
57   int *stwtype, int *macroblock_type));
58
59 static int slice _ANSI_ARGS_((int framenum, int MBAmax));
60
61 static int start_of_slice _ANSI_ARGS_ ((int MBAmax, int *MBA,
62   int *MBAinc, int dc_dct_pred[3], int PMV[2][2][2]));
63
64 static int decode_macroblock _ANSI_ARGS_((int *macroblock_type, 
65   int *stwtype, int *stwclass, int *motion_type, int *dct_type,
66   int PMV[2][2][2], int dc_dct_pred[3], 
67   int motion_vertical_field_select[2][2], int dmvector[2]));
68
69
70 /* decode one frame or field picture */
71 void Decode_Picture(bitstream_framenum, sequence_framenum)
72 int bitstream_framenum, sequence_framenum;
73 {
74
75   if (picture_structure==FRAME_PICTURE && Second_Field)
76   {
77     /* recover from illegal number of field pictures */
78     printf("odd number of field pictures\n");
79     Second_Field = 0;
80   }
81
82   /* IMPLEMENTATION: update picture buffer pointers */
83   Update_Picture_Buffers();
84
85 #ifdef VERIFY 
86   Check_Headers(bitstream_framenum, sequence_framenum);
87 #endif /* VERIFY */
88
89   /* ISO/IEC 13818-4 section 2.4.5.4 "frame buffer intercept method" */
90   /* (section number based on November 1995 (Dallas) draft of the 
91       conformance document) */
92   if(Ersatz_Flag)
93     Substitute_Frame_Buffer(bitstream_framenum, sequence_framenum);
94
95   /* form spatial scalable picture */
96  
97   /* form spatial scalable picture */
98   /* ISO/IEC 13818-2 section 7.7: Spatial scalability */
99   if (base.pict_scal && !Second_Field) 
100   {
101     Spatial_Prediction();
102   }
103
104   /* decode picture data ISO/IEC 13818-2 section 6.2.3.7 */
105   picture_data(bitstream_framenum);
106
107   /* write or display current or previously decoded reference frame */
108   /* ISO/IEC 13818-2 section 6.1.1.11: Frame reordering */
109   frame_reorder(bitstream_framenum, sequence_framenum);
110
111   if (picture_structure!=FRAME_PICTURE)
112     Second_Field = !Second_Field;
113 }
114
115
116 /* decode all macroblocks of the current picture */
117 /* stages described in ISO/IEC 13818-2 section 7 */
118 static void picture_data(framenum)
119 int framenum;
120 {
121   int MBAmax;
122   int ret;
123
124   /* number of macroblocks per picture */
125   MBAmax = mb_width*mb_height;
126
127   if (picture_structure!=FRAME_PICTURE)
128     MBAmax>>=1; /* field picture has half as mnay macroblocks as frame */
129
130   for(;;)
131   {
132     if((ret=slice(framenum, MBAmax))<0)
133       return;
134   }
135
136 }
137
138
139
140 /* decode all macroblocks of the current picture */
141 /* ISO/IEC 13818-2 section 6.3.16 */
142 static int slice(framenum, MBAmax)
143 int framenum, MBAmax;
144 {
145   int MBA; 
146   int MBAinc, macroblock_type, motion_type, dct_type;
147   int dc_dct_pred[3];
148   int PMV[2][2][2], motion_vertical_field_select[2][2];
149   int dmvector[2];
150   int stwtype, stwclass;
151   int SNRMBA, SNRMBAinc;
152   int ret;
153   (void)framenum;
154
155   MBA = 0; /* macroblock address */
156   MBAinc = 0;
157
158   if((ret=start_of_slice(MBAmax, &MBA, &MBAinc, dc_dct_pred, PMV))!=1)
159     return(ret);
160
161   if (Two_Streams && enhan.scalable_mode==SC_SNR)
162   {
163     SNRMBA=0;
164     SNRMBAinc=0;
165   }
166
167   Fault_Flag=0;
168
169   for (;;)
170   {
171
172     /* this is how we properly exit out of picture */
173     if (MBA>=MBAmax)
174       return(-1); /* all macroblocks decoded */
175
176 #ifdef TRACE
177     if (Trace_Flag)
178       printf("frame %d, MB %d\n",framenum,MBA);
179 #endif /* TRACE */
180
181 #ifdef DISPLAY
182     if (!progressive_frame && picture_structure==FRAME_PICTURE 
183       && MBA==(MBAmax>>1) && framenum!=0 && Output_Type==T_X11 
184        && !Display_Progressive_Flag)
185     {
186       Display_Second_Field();
187     }
188 #endif
189
190     ld = &base;
191
192     if (MBAinc==0)
193     {
194       if (base.scalable_mode==SC_DP && base.priority_breakpoint==1)
195           ld = &enhan;
196
197       if (!Show_Bits(23) || Fault_Flag) /* next_start_code or fault */
198       {
199 resync: /* if Fault_Flag: resynchronize to next next_start_code */
200         Fault_Flag = 0;
201         return(0);     /* trigger: go to next slice */
202       }
203       else /* neither next_start_code nor Fault_Flag */
204       {
205         if (base.scalable_mode==SC_DP && base.priority_breakpoint==1)
206           ld = &enhan;
207
208         /* decode macroblock address increment */
209         MBAinc = Get_macroblock_address_increment();
210
211         if (Fault_Flag) goto resync;
212       }
213     }
214
215     if (MBA>=MBAmax)
216     {
217       /* MBAinc points beyond picture dimensions */
218       if (!Quiet_Flag)
219         printf("Too many macroblocks in picture\n");
220       return(-1);
221     }
222
223     if (MBAinc==1) /* not skipped */
224     {
225       ret = decode_macroblock(&macroblock_type, &stwtype, &stwclass,
226               &motion_type, &dct_type, PMV, dc_dct_pred, 
227               motion_vertical_field_select, dmvector);
228
229       if(ret==-1)
230         return(-1);
231    
232       if(ret==0)
233         goto resync;
234
235     }
236     else /* MBAinc!=1: skipped macroblock */
237     {      
238       /* ISO/IEC 13818-2 section 7.6.6 */
239       skipped_macroblock(dc_dct_pred, PMV, &motion_type, 
240         motion_vertical_field_select, &stwtype, &macroblock_type);
241     }
242
243     /* SCALABILITY: SNR */
244     /* ISO/IEC 13818-2 section 7.8 */
245     /* NOTE: we currently ignore faults encountered in this routine */
246     if (Two_Streams && enhan.scalable_mode==SC_SNR)
247       Decode_SNR_Macroblock(&SNRMBA, &SNRMBAinc, MBA, MBAmax, &dct_type);
248
249     /* ISO/IEC 13818-2 section 7.6 */
250     motion_compensation(MBA, macroblock_type, motion_type, PMV, 
251       motion_vertical_field_select, dmvector, stwtype, dct_type);
252
253
254     /* advance to next macroblock */
255     MBA++;
256     MBAinc--;
257  
258     /* SCALABILITY: SNR */
259     if (Two_Streams && enhan.scalable_mode==SC_SNR)
260     {
261       SNRMBA++;
262       SNRMBAinc--;
263     }
264
265     if (MBA>=MBAmax)
266       return(-1); /* all macroblocks decoded */
267   }
268 }
269
270  
271 /* ISO/IEC 13818-2 section 6.3.17.1: Macroblock modes */
272 static void macroblock_modes(pmacroblock_type,pstwtype,pstwclass,
273   pmotion_type,pmotion_vector_count,pmv_format,pdmv,pmvscale,pdct_type)
274   int *pmacroblock_type, *pstwtype, *pstwclass;
275   int *pmotion_type, *pmotion_vector_count, *pmv_format, *pdmv, *pmvscale;
276   int *pdct_type;
277 {
278   int macroblock_type;
279   int stwtype, stwcode, stwclass;
280   int motion_type = 0;
281   int motion_vector_count, mv_format, dmv, mvscale;
282   int dct_type;
283   static unsigned char stwc_table[3][4]
284     = { {6,3,7,4}, {2,1,5,4}, {2,5,7,4} };
285   static unsigned char stwclass_table[9]
286     = {0, 1, 2, 1, 1, 2, 3, 3, 4};
287
288   /* get macroblock_type */
289   macroblock_type = Get_macroblock_type();
290
291   if (Fault_Flag) return;
292
293   /* get spatial_temporal_weight_code */
294   if (macroblock_type & MB_WEIGHT)
295   {
296     if (spatial_temporal_weight_code_table_index==0)
297       stwtype = 4;
298     else
299     {
300       stwcode = Get_Bits(2);
301 #ifdef TRACE
302       if (Trace_Flag)
303       {
304         printf("spatial_temporal_weight_code (");
305         Print_Bits(stwcode,2,2);
306         printf("): %d\n",stwcode);
307       }
308 #endif /* TRACE */
309       stwtype = stwc_table[spatial_temporal_weight_code_table_index-1][stwcode];
310     }
311   }
312   else
313     stwtype = (macroblock_type & MB_CLASS4) ? 8 : 0;
314
315   /* SCALABILITY: derive spatial_temporal_weight_class (Table 7-18) */
316   stwclass = stwclass_table[stwtype];
317
318   /* get frame/field motion type */
319   if (macroblock_type & (MACROBLOCK_MOTION_FORWARD|MACROBLOCK_MOTION_BACKWARD))
320   {
321     if (picture_structure==FRAME_PICTURE) /* frame_motion_type */
322     {
323       motion_type = frame_pred_frame_dct ? MC_FRAME : Get_Bits(2);
324 #ifdef TRACE
325       if (!frame_pred_frame_dct && Trace_Flag)
326       {
327         printf("frame_motion_type (");
328         Print_Bits(motion_type,2,2);
329         printf("): %s\n",motion_type==MC_FIELD?"Field":
330                          motion_type==MC_FRAME?"Frame":
331                          motion_type==MC_DMV?"Dual_Prime":"Invalid");
332       }
333 #endif /* TRACE */
334     }
335     else /* field_motion_type */
336     {
337       motion_type = Get_Bits(2);
338 #ifdef TRACE
339       if (Trace_Flag)
340       {
341         printf("field_motion_type (");
342         Print_Bits(motion_type,2,2);
343         printf("): %s\n",motion_type==MC_FIELD?"Field":
344                          motion_type==MC_16X8?"16x8 MC":
345                          motion_type==MC_DMV?"Dual_Prime":"Invalid");
346       }
347 #endif /* TRACE */
348     }
349   }
350   else if ((macroblock_type & MACROBLOCK_INTRA) && concealment_motion_vectors)
351   {
352     /* concealment motion vectors */
353     motion_type = (picture_structure==FRAME_PICTURE) ? MC_FRAME : MC_FIELD;
354   }
355 #if 0
356   else
357   {
358     printf("maroblock_modes(): unknown macroblock type\n");
359     motion_type = -1;
360   }
361 #endif
362
363   /* derive motion_vector_count, mv_format and dmv, (table 6-17, 6-18) */
364   if (picture_structure==FRAME_PICTURE)
365   {
366     motion_vector_count = (motion_type==MC_FIELD && stwclass<2) ? 2 : 1;
367     mv_format = (motion_type==MC_FRAME) ? MV_FRAME : MV_FIELD;
368   }
369   else
370   {
371     motion_vector_count = (motion_type==MC_16X8) ? 2 : 1;
372     mv_format = MV_FIELD;
373   }
374
375   dmv = (motion_type==MC_DMV); /* dual prime */
376
377   /* field mv predictions in frame pictures have to be scaled
378    * ISO/IEC 13818-2 section 7.6.3.1 Decoding the motion vectors
379    * IMPLEMENTATION: mvscale is derived for later use in motion_vectors()
380    * it displaces the stage:
381    *
382    *    if((mv_format=="field")&&(t==1)&&(picture_structure=="Frame picture"))
383    *      prediction = PMV[r][s][t] DIV 2;
384    */
385
386   mvscale = ((mv_format==MV_FIELD) && (picture_structure==FRAME_PICTURE));
387
388   /* get dct_type (frame DCT / field DCT) */
389   dct_type = (picture_structure==FRAME_PICTURE)
390              && (!frame_pred_frame_dct)
391              && (macroblock_type & (MACROBLOCK_PATTERN|MACROBLOCK_INTRA))
392              ? Get_Bits(1)
393              : 0;
394
395 #ifdef TRACE
396   if (Trace_Flag  && (picture_structure==FRAME_PICTURE)
397              && (!frame_pred_frame_dct)
398              && (macroblock_type & (MACROBLOCK_PATTERN|MACROBLOCK_INTRA)))
399     printf("dct_type (%d): %s\n",dct_type,dct_type?"Field":"Frame");
400 #endif /* TRACE */
401
402   /* return values */
403   *pmacroblock_type = macroblock_type;
404   *pstwtype = stwtype;
405   *pstwclass = stwclass;
406   *pmotion_type = motion_type;
407   *pmotion_vector_count = motion_vector_count;
408   *pmv_format = mv_format;
409   *pdmv = dmv;
410   *pmvscale = mvscale;
411   *pdct_type = dct_type;
412 }
413
414
415 /* move/add 8x8-Block from block[comp] to backward_reference_frame */
416 /* copy reconstructed 8x8 block from block[comp] to current_frame[]
417  * ISO/IEC 13818-2 section 7.6.8: Adding prediction and coefficient data
418  * This stage also embodies some of the operations implied by:
419  *   - ISO/IEC 13818-2 section 7.6.7: Combining predictions
420  *   - ISO/IEC 13818-2 section 6.1.3: Macroblock
421 */
422 static void Add_Block(comp,bx,by,dct_type,addflag)
423 int comp,bx,by,dct_type,addflag;
424 {
425   int cc,i, j, iincr;
426   unsigned char *rfp;
427   short *bp;
428
429   
430   /* derive color component index */
431   /* equivalent to ISO/IEC 13818-2 Table 7-1 */
432   cc = (comp<4) ? 0 : (comp&1)+1; /* color component index */
433
434   if (cc==0)
435   {
436     /* luminance */
437
438     if (picture_structure==FRAME_PICTURE)
439       if (dct_type)
440       {
441         /* field DCT coding */
442         rfp = current_frame[0]
443               + Coded_Picture_Width*(by+((comp&2)>>1)) + bx + ((comp&1)<<3);
444         iincr = (Coded_Picture_Width<<1) - 8;
445       }
446       else
447       {
448         /* frame DCT coding */
449         rfp = current_frame[0]
450               + Coded_Picture_Width*(by+((comp&2)<<2)) + bx + ((comp&1)<<3);
451         iincr = Coded_Picture_Width - 8;
452       }
453     else
454     {
455       /* field picture */
456       rfp = current_frame[0]
457             + (Coded_Picture_Width<<1)*(by+((comp&2)<<2)) + bx + ((comp&1)<<3);
458       iincr = (Coded_Picture_Width<<1) - 8;
459     }
460   }
461   else
462   {
463     /* chrominance */
464
465     /* scale coordinates */
466     if (chroma_format!=CHROMA444)
467       bx >>= 1;
468     if (chroma_format==CHROMA420)
469       by >>= 1;
470     if (picture_structure==FRAME_PICTURE)
471     {
472       if (dct_type && (chroma_format!=CHROMA420))
473       {
474         /* field DCT coding */
475         rfp = current_frame[cc]
476               + Chroma_Width*(by+((comp&2)>>1)) + bx + (comp&8);
477         iincr = (Chroma_Width<<1) - 8;
478       }
479       else
480       {
481         /* frame DCT coding */
482         rfp = current_frame[cc]
483               + Chroma_Width*(by+((comp&2)<<2)) + bx + (comp&8);
484         iincr = Chroma_Width - 8;
485       }
486     }
487     else
488     {
489       /* field picture */
490       rfp = current_frame[cc]
491             + (Chroma_Width<<1)*(by+((comp&2)<<2)) + bx + (comp&8);
492       iincr = (Chroma_Width<<1) - 8;
493     }
494   }
495
496   bp = ld->block[comp];
497
498   if (addflag)
499   {
500     for (i=0; i<8; i++)
501     {
502       for (j=0; j<8; j++)
503       {
504         *rfp = Clip[*bp++ + *rfp];
505         rfp++;
506       }
507
508       rfp+= iincr;
509     }
510   }
511   else
512   {
513     for (i=0; i<8; i++)
514     {
515       for (j=0; j<8; j++)
516         *rfp++ = Clip[*bp++ + 128];
517
518       rfp+= iincr;
519     }
520   }
521 }
522
523
524 /* ISO/IEC 13818-2 section 7.8 */
525 static void Decode_SNR_Macroblock(SNRMBA, SNRMBAinc, MBA, MBAmax, dct_type)
526   int *SNRMBA, *SNRMBAinc;
527   int MBA, MBAmax;
528   int *dct_type;
529 {
530   int SNRmacroblock_type, SNRcoded_block_pattern, SNRdct_type, dummy; 
531   int slice_vert_pos_ext, quantizer_scale_code, comp, code;
532
533   ld = &enhan;
534
535   if (*SNRMBAinc==0)
536   {
537     if (!Show_Bits(23)) /* next_start_code */
538     {
539       next_start_code();
540       code = Show_Bits(32);
541
542       if (code<SLICE_START_CODE_MIN || code>SLICE_START_CODE_MAX)
543       {
544         /* only slice headers are allowed in picture_data */
545         if (!Quiet_Flag)
546           printf("SNR: Premature end of picture\n");
547         return;
548       }
549
550       Flush_Buffer32();
551
552       /* decode slice header (may change quantizer_scale) */
553       slice_vert_pos_ext = slice_header();
554
555       /* decode macroblock address increment */
556       *SNRMBAinc = Get_macroblock_address_increment();
557
558       /* set current location */
559       *SNRMBA =
560         ((slice_vert_pos_ext<<7) + (code&255) - 1)*mb_width + *SNRMBAinc - 1;
561
562       *SNRMBAinc = 1; /* first macroblock in slice: not skipped */
563     }
564     else /* not next_start_code */
565     {
566       if (*SNRMBA>=MBAmax)
567       {
568         if (!Quiet_Flag)
569           printf("Too many macroblocks in picture\n");
570         return;
571       }
572
573       /* decode macroblock address increment */
574       *SNRMBAinc = Get_macroblock_address_increment();
575     }
576   }
577
578   if (*SNRMBA!=MBA)
579   {
580     /* streams out of sync */
581     if (!Quiet_Flag)
582       printf("Cant't synchronize streams\n");
583     return;
584   }
585
586   if (*SNRMBAinc==1) /* not skipped */
587   {
588     macroblock_modes(&SNRmacroblock_type, &dummy, &dummy,
589       &dummy, &dummy, &dummy, &dummy, &dummy,
590       &SNRdct_type);
591
592     if (SNRmacroblock_type & MACROBLOCK_PATTERN)
593       *dct_type = SNRdct_type;
594
595     if (SNRmacroblock_type & MACROBLOCK_QUANT)
596     {
597       quantizer_scale_code = Get_Bits(5);
598       ld->quantizer_scale =
599         ld->q_scale_type ? Non_Linear_quantizer_scale[quantizer_scale_code] : quantizer_scale_code<<1;
600     }
601
602     /* macroblock_pattern */
603     if (SNRmacroblock_type & MACROBLOCK_PATTERN)
604     {
605       SNRcoded_block_pattern = Get_coded_block_pattern();
606
607       if (chroma_format==CHROMA422)
608         SNRcoded_block_pattern = (SNRcoded_block_pattern<<2) | Get_Bits(2); /* coded_block_pattern_1 */
609       else if (chroma_format==CHROMA444)
610         SNRcoded_block_pattern = (SNRcoded_block_pattern<<6) | Get_Bits(6); /* coded_block_pattern_2 */
611     }
612     else
613       SNRcoded_block_pattern = 0;
614
615     /* decode blocks */
616     for (comp=0; comp<block_count; comp++)
617     {
618       Clear_Block(comp);
619
620       if (SNRcoded_block_pattern & (1<<(block_count-1-comp)))
621         Decode_MPEG2_Non_Intra_Block(comp);
622     }
623   }
624   else /* SNRMBAinc!=1: skipped macroblock */
625   {
626     for (comp=0; comp<block_count; comp++)
627       Clear_Block(comp);
628   }
629
630   ld = &base;
631 }
632
633
634
635 /* IMPLEMENTATION: set scratch pad macroblock to zero */
636 static void Clear_Block(comp)
637 int comp;
638 {
639   short *Block_Ptr;
640   int i;
641
642   Block_Ptr = ld->block[comp];
643
644   for (i=0; i<64; i++)
645     *Block_Ptr++ = 0;
646 }
647
648
649 /* SCALABILITY: add SNR enhancement layer block data to base layer */
650 /* ISO/IEC 13818-2 section 7.8.3.4: Addition of coefficients from the two layes */
651 static void Sum_Block(comp)
652 int comp;
653 {
654   short *Block_Ptr1, *Block_Ptr2;
655   int i;
656
657   Block_Ptr1 = base.block[comp];
658   Block_Ptr2 = enhan.block[comp];
659
660   for (i=0; i<64; i++)
661     *Block_Ptr1++ += *Block_Ptr2++;
662 }
663
664
665 /* limit coefficients to -2048..2047 */
666 /* ISO/IEC 13818-2 section 7.4.3 and 7.4.4: Saturation and Mismatch control */
667 static void Saturate(Block_Ptr)
668 short *Block_Ptr;
669 {
670   int i, sum, val;
671
672   sum = 0;
673
674   /* ISO/IEC 13818-2 section 7.4.3: Saturation */
675   for (i=0; i<64; i++)
676   {
677     val = Block_Ptr[i];
678
679     if (val>2047)
680       val = 2047;
681     else if (val<-2048)
682       val = -2048;
683
684     Block_Ptr[i] = val;
685     sum+= val;
686   }
687
688   /* ISO/IEC 13818-2 section 7.4.4: Mismatch control */
689   if ((sum&1)==0)
690     Block_Ptr[63]^= 1;
691
692 }
693
694
695 /* reuse old picture buffers as soon as they are no longer needed 
696    based on life-time axioms of MPEG */
697 static void Update_Picture_Buffers()
698 {                           
699   int cc;              /* color component index */
700   unsigned char *tmp;  /* temporary swap pointer */
701
702   for (cc=0; cc<3; cc++)
703   {
704     /* B pictures do not need to be save for future reference */
705     if (picture_coding_type==B_TYPE)
706     {
707       current_frame[cc] = auxframe[cc];
708     }
709     else
710     {
711       /* only update at the beginning of the coded frame */
712       if (!Second_Field)
713       {
714         tmp = forward_reference_frame[cc];
715
716         /* the previously decoded reference frame is stored
717            coincident with the location where the backward 
718            reference frame is stored (backwards prediction is not
719            needed in P pictures) */
720         forward_reference_frame[cc] = backward_reference_frame[cc];
721         
722         /* update pointer for potential future B pictures */
723         backward_reference_frame[cc] = tmp;
724       }
725
726       /* can erase over old backward reference frame since it is not used
727          in a P picture, and since any subsequent B pictures will use the 
728          previously decoded I or P frame as the backward_reference_frame */
729       current_frame[cc] = backward_reference_frame[cc];
730     }
731
732     /* IMPLEMENTATION:
733        one-time folding of a line offset into the pointer which stores the
734        memory address of the current frame saves offsets and conditional 
735        branches throughout the remainder of the picture processing loop */
736     if (picture_structure==BOTTOM_FIELD)
737       current_frame[cc]+= (cc==0) ? Coded_Picture_Width : Chroma_Width;
738   }
739 }
740
741
742 /* store last frame */
743
744 void Output_Last_Frame_of_Sequence(Framenum)
745 int Framenum;
746 {
747   if (Second_Field)
748     printf("last frame incomplete, not stored\n");
749   else
750     Write_Frame(backward_reference_frame,Framenum-1);
751 }
752
753
754
755 static void frame_reorder(Bitstream_Framenum, Sequence_Framenum)
756 int Bitstream_Framenum, Sequence_Framenum;
757 {
758   /* tracking variables to insure proper output in spatial scalability */
759   static int Oldref_progressive_frame, Newref_progressive_frame;
760
761   if (Sequence_Framenum!=0)
762   {
763     if (picture_structure==FRAME_PICTURE || Second_Field)
764     {
765       if (picture_coding_type==B_TYPE)
766         Write_Frame(auxframe,Bitstream_Framenum-1);
767       else
768       {
769         Newref_progressive_frame = progressive_frame;
770         progressive_frame = Oldref_progressive_frame;
771
772         Write_Frame(forward_reference_frame,Bitstream_Framenum-1);
773
774         Oldref_progressive_frame = progressive_frame = Newref_progressive_frame;
775       }
776     }
777 #ifdef DISPLAY
778     else if (Output_Type==T_X11)
779     {
780       if(!Display_Progressive_Flag)
781         Display_Second_Field();
782     }
783 #endif
784   }
785   else
786     Oldref_progressive_frame = progressive_frame;
787
788 }
789
790
791 /* ISO/IEC 13818-2 section 7.6 */
792 static void motion_compensation(MBA, macroblock_type, motion_type, PMV, 
793   motion_vertical_field_select, dmvector, stwtype, dct_type)
794 int MBA;
795 int macroblock_type;
796 int motion_type;
797 int PMV[2][2][2];
798 int motion_vertical_field_select[2][2];
799 int dmvector[2];
800 int stwtype;
801 int dct_type;
802 {
803   int bx, by;
804   int comp;
805
806   /* derive current macroblock position within picture */
807   /* ISO/IEC 13818-2 section 6.3.1.6 and 6.3.1.7 */
808   bx = 16*(MBA%mb_width);
809   by = 16*(MBA/mb_width);
810
811   /* motion compensation */
812   if (!(macroblock_type & MACROBLOCK_INTRA))
813     form_predictions(bx,by,macroblock_type,motion_type,PMV,
814       motion_vertical_field_select,dmvector,stwtype);
815   
816   /* SCALABILITY: Data Partitioning */
817   if (base.scalable_mode==SC_DP)
818     ld = &base;
819
820   /* copy or add block data into picture */
821   for (comp=0; comp<block_count; comp++)
822   {
823     /* SCALABILITY: SNR */
824     /* ISO/IEC 13818-2 section 7.8.3.4: Addition of coefficients from 
825        the two a layers */
826     if (Two_Streams && enhan.scalable_mode==SC_SNR)
827       Sum_Block(comp); /* add SNR enhancement layer data to base layer */
828
829     /* MPEG-2 saturation and mismatch control */
830     /* base layer could be MPEG-1 stream, enhancement MPEG-2 SNR */
831     /* ISO/IEC 13818-2 section 7.4.3 and 7.4.4: Saturation and Mismatch control */
832     if ((Two_Streams && enhan.scalable_mode==SC_SNR) || ld->MPEG2_Flag)
833       Saturate(ld->block[comp]);
834
835     /* ISO/IEC 13818-2 section Annex A: inverse DCT */
836     if (Reference_IDCT_Flag)
837       Reference_IDCT(ld->block[comp]);
838     else
839       Fast_IDCT(ld->block[comp]);
840     
841     /* ISO/IEC 13818-2 section 7.6.8: Adding prediction and coefficient data */
842     Add_Block(comp,bx,by,dct_type,(macroblock_type & MACROBLOCK_INTRA)==0);
843   }
844
845 }
846
847
848
849 /* ISO/IEC 13818-2 section 7.6.6 */
850 static void skipped_macroblock(dc_dct_pred, PMV, motion_type, 
851   motion_vertical_field_select, stwtype, macroblock_type)
852 int dc_dct_pred[3];
853 int PMV[2][2][2];
854 int *motion_type;
855 int motion_vertical_field_select[2][2];
856 int *stwtype;
857 int *macroblock_type;
858 {
859   int comp;
860   
861   /* SCALABILITY: Data Paritioning */
862   if (base.scalable_mode==SC_DP)
863     ld = &base;
864
865   for (comp=0; comp<block_count; comp++)
866     Clear_Block(comp);
867
868   /* reset intra_dc predictors */
869   /* ISO/IEC 13818-2 section 7.2.1: DC coefficients in intra blocks */
870   dc_dct_pred[0]=dc_dct_pred[1]=dc_dct_pred[2]=0;
871
872   /* reset motion vector predictors */
873   /* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
874   if (picture_coding_type==P_TYPE)
875     PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
876
877   /* derive motion_type */
878   if (picture_structure==FRAME_PICTURE)
879     *motion_type = MC_FRAME;
880   else
881   {
882     *motion_type = MC_FIELD;
883
884     /* predict from field of same parity */
885     /* ISO/IEC 13818-2 section 7.6.6.1 and 7.6.6.3: P field picture and B field
886        picture */
887     motion_vertical_field_select[0][0]=motion_vertical_field_select[0][1] = 
888       (picture_structure==BOTTOM_FIELD);
889   }
890
891   /* skipped I are spatial-only predicted, */
892   /* skipped P and B are temporal-only predicted */
893   /* ISO/IEC 13818-2 section 7.7.6: Skipped macroblocks */
894   *stwtype = (picture_coding_type==I_TYPE) ? 8 : 0;
895
896  /* IMPLEMENTATION: clear MACROBLOCK_INTRA */
897   *macroblock_type&= ~MACROBLOCK_INTRA;
898
899 }
900
901
902 /* return==-1 means go to next picture */
903 /* the expression "start of slice" is used throughout the normative
904    body of the MPEG specification */
905 static int start_of_slice(MBAmax, MBA, MBAinc, 
906   dc_dct_pred, PMV)
907 int MBAmax;
908 int *MBA;
909 int *MBAinc;
910 int dc_dct_pred[3];
911 int PMV[2][2][2];
912 {
913   unsigned int code;
914   int slice_vert_pos_ext;
915   (void)MBAmax;
916
917   ld = &base;
918
919   Fault_Flag = 0;
920
921   next_start_code();
922   code = Show_Bits(32);
923
924   if (code<SLICE_START_CODE_MIN || code>SLICE_START_CODE_MAX)
925   {
926     /* only slice headers are allowed in picture_data */
927     if (!Quiet_Flag)
928       printf("start_of_slice(): Premature end of picture\n");
929
930     return(-1);  /* trigger: go to next picture */
931   }
932
933   Flush_Buffer32(); 
934
935   /* decode slice header (may change quantizer_scale) */
936   slice_vert_pos_ext = slice_header();
937
938  
939   /* SCALABILITY: Data Partitioning */
940   if (base.scalable_mode==SC_DP)
941   {
942     ld = &enhan;
943     next_start_code();
944     code = Show_Bits(32);
945
946     if (code<SLICE_START_CODE_MIN || code>SLICE_START_CODE_MAX)
947     {
948       /* only slice headers are allowed in picture_data */
949       if (!Quiet_Flag)
950         printf("DP: Premature end of picture\n");
951       return(-1);    /* trigger: go to next picture */
952     }
953
954     Flush_Buffer32();
955
956     /* decode slice header (may change quantizer_scale) */
957     slice_vert_pos_ext = slice_header();
958
959     if (base.priority_breakpoint!=1)
960       ld = &base;
961   }
962
963   /* decode macroblock address increment */
964   *MBAinc = Get_macroblock_address_increment();
965
966   if (Fault_Flag) 
967   {
968     printf("start_of_slice(): MBAinc unsuccessful\n");
969     return(0);   /* trigger: go to next slice */
970   }
971
972   /* set current location */
973   /* NOTE: the arithmetic used to derive macroblock_address below is
974    *       equivalent to ISO/IEC 13818-2 section 6.3.17: Macroblock
975    */
976   *MBA = ((slice_vert_pos_ext<<7) + (code&255) - 1)*mb_width + *MBAinc - 1;
977   *MBAinc = 1; /* first macroblock in slice: not skipped */
978
979   /* reset all DC coefficient and motion vector predictors */
980   /* reset all DC coefficient and motion vector predictors */
981   /* ISO/IEC 13818-2 section 7.2.1: DC coefficients in intra blocks */
982   dc_dct_pred[0]=dc_dct_pred[1]=dc_dct_pred[2]=0;
983   
984   /* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
985   PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
986   PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
987
988   /* successfull: trigger decode macroblocks in slice */
989   return(1);
990 }
991
992
993 /* ISO/IEC 13818-2 sections 7.2 through 7.5 */
994 static int decode_macroblock(macroblock_type, stwtype, stwclass,
995   motion_type, dct_type, PMV, dc_dct_pred, 
996   motion_vertical_field_select, dmvector)
997 int *macroblock_type; 
998 int *stwtype;
999 int *stwclass;
1000 int *motion_type; 
1001 int *dct_type;
1002 int PMV[2][2][2]; 
1003 int dc_dct_pred[3]; 
1004 int motion_vertical_field_select[2][2];
1005 int dmvector[2];
1006 {
1007   /* locals */
1008   int quantizer_scale_code; 
1009   int comp;
1010
1011   int motion_vector_count; 
1012   int mv_format; 
1013   int dmv; 
1014   int mvscale;
1015   int coded_block_pattern;
1016
1017   /* SCALABILITY: Data Patitioning */
1018   if (base.scalable_mode==SC_DP)
1019   {
1020     if (base.priority_breakpoint<=2)
1021       ld = &enhan;
1022     else
1023       ld = &base;
1024   }
1025
1026   /* ISO/IEC 13818-2 section 6.3.17.1: Macroblock modes */
1027   macroblock_modes(macroblock_type, stwtype, stwclass,
1028     motion_type, &motion_vector_count, &mv_format, &dmv, &mvscale,
1029     dct_type);
1030
1031   if (Fault_Flag) return(0);  /* trigger: go to next slice */
1032
1033   if (*macroblock_type & MACROBLOCK_QUANT)
1034   {
1035     quantizer_scale_code = Get_Bits(5);
1036
1037 #ifdef TRACE
1038     if (Trace_Flag)
1039     {
1040       printf("quantiser_scale_code (");
1041       Print_Bits(quantizer_scale_code,5,5);
1042       printf("): %d\n",quantizer_scale_code);
1043     }
1044 #endif /* TRACE */
1045
1046     /* ISO/IEC 13818-2 section 7.4.2.2: Quantizer scale factor */
1047     if (ld->MPEG2_Flag)
1048       ld->quantizer_scale =
1049       ld->q_scale_type ? Non_Linear_quantizer_scale[quantizer_scale_code] 
1050        : (quantizer_scale_code << 1);
1051     else
1052       ld->quantizer_scale = quantizer_scale_code;
1053
1054     /* SCALABILITY: Data Partitioning */
1055     if (base.scalable_mode==SC_DP)
1056       /* make sure base.quantizer_scale is valid */
1057       base.quantizer_scale = ld->quantizer_scale;
1058   }
1059
1060   /* motion vectors */
1061
1062
1063   /* ISO/IEC 13818-2 section 6.3.17.2: Motion vectors */
1064
1065   /* decode forward motion vectors */
1066   if ((*macroblock_type & MACROBLOCK_MOTION_FORWARD) 
1067     || ((*macroblock_type & MACROBLOCK_INTRA) 
1068     && concealment_motion_vectors))
1069   {
1070     if (ld->MPEG2_Flag)
1071       motion_vectors(PMV,dmvector,motion_vertical_field_select,
1072         0,motion_vector_count,mv_format,f_code[0][0]-1,f_code[0][1]-1,
1073         dmv,mvscale);
1074     else
1075       motion_vector(PMV[0][0],dmvector,
1076       forward_f_code-1,forward_f_code-1,0,0,full_pel_forward_vector);
1077   }
1078
1079   if (Fault_Flag) return(0);  /* trigger: go to next slice */
1080
1081   /* decode backward motion vectors */
1082   if (*macroblock_type & MACROBLOCK_MOTION_BACKWARD)
1083   {
1084     if (ld->MPEG2_Flag)
1085       motion_vectors(PMV,dmvector,motion_vertical_field_select,
1086         1,motion_vector_count,mv_format,f_code[1][0]-1,f_code[1][1]-1,0,
1087         mvscale);
1088     else
1089       motion_vector(PMV[0][1],dmvector,
1090         backward_f_code-1,backward_f_code-1,0,0,full_pel_backward_vector);
1091   }
1092
1093   if (Fault_Flag) return(0);  /* trigger: go to next slice */
1094
1095   if ((*macroblock_type & MACROBLOCK_INTRA) && concealment_motion_vectors)
1096     Flush_Buffer(1); /* remove marker_bit */
1097
1098   if (base.scalable_mode==SC_DP && base.priority_breakpoint==3)
1099     ld = &enhan;
1100
1101   /* macroblock_pattern */
1102   /* ISO/IEC 13818-2 section 6.3.17.4: Coded block pattern */
1103   if (*macroblock_type & MACROBLOCK_PATTERN)
1104   {
1105     coded_block_pattern = Get_coded_block_pattern();
1106
1107     if (chroma_format==CHROMA422)
1108     {
1109       /* coded_block_pattern_1 */
1110       coded_block_pattern = (coded_block_pattern<<2) | Get_Bits(2); 
1111
1112 #ifdef TRACE
1113        if (Trace_Flag)
1114        {
1115          printf("coded_block_pattern_1: ");
1116          Print_Bits(coded_block_pattern,2,2);
1117          printf(" (%d)\n",coded_block_pattern&3);
1118        }
1119 #endif /* TRACE */
1120      }
1121      else if (chroma_format==CHROMA444)
1122      {
1123       /* coded_block_pattern_2 */
1124       coded_block_pattern = (coded_block_pattern<<6) | Get_Bits(6); 
1125
1126 #ifdef TRACE
1127       if (Trace_Flag)
1128       {
1129         printf("coded_block_pattern_2: ");
1130         Print_Bits(coded_block_pattern,6,6);
1131         printf(" (%d)\n",coded_block_pattern&63);
1132       }
1133 #endif /* TRACE */
1134     }
1135   }
1136   else
1137     coded_block_pattern = (*macroblock_type & MACROBLOCK_INTRA) ? 
1138       (1<<block_count)-1 : 0;
1139
1140   if (Fault_Flag) return(0);  /* trigger: go to next slice */
1141
1142   /* decode blocks */
1143   for (comp=0; comp<block_count; comp++)
1144   {
1145     /* SCALABILITY: Data Partitioning */
1146     if (base.scalable_mode==SC_DP)
1147     ld = &base;
1148
1149     Clear_Block(comp);
1150
1151     if (coded_block_pattern & (1<<(block_count-1-comp)))
1152     {
1153       if (*macroblock_type & MACROBLOCK_INTRA)
1154       {
1155         if (ld->MPEG2_Flag)
1156           Decode_MPEG2_Intra_Block(comp,dc_dct_pred);
1157         else
1158           Decode_MPEG1_Intra_Block(comp,dc_dct_pred);
1159       }
1160       else
1161       {
1162         if (ld->MPEG2_Flag)
1163           Decode_MPEG2_Non_Intra_Block(comp);
1164         else
1165           Decode_MPEG1_Non_Intra_Block(comp);
1166       }
1167
1168       if (Fault_Flag) return(0);  /* trigger: go to next slice */
1169     }
1170   }
1171
1172   if(picture_coding_type==D_TYPE)
1173   {
1174     /* remove end_of_macroblock (always 1, prevents startcode emulation) */
1175     /* ISO/IEC 11172-2 section 2.4.2.7 and 2.4.3.6 */
1176     marker_bit("D picture end_of_macroblock bit");
1177   }
1178
1179   /* reset intra_dc predictors */
1180   /* ISO/IEC 13818-2 section 7.2.1: DC coefficients in intra blocks */
1181   if (!(*macroblock_type & MACROBLOCK_INTRA))
1182     dc_dct_pred[0]=dc_dct_pred[1]=dc_dct_pred[2]=0;
1183
1184   /* reset motion vector predictors */
1185   if ((*macroblock_type & MACROBLOCK_INTRA) && !concealment_motion_vectors)
1186   {
1187     /* intra mb without concealment motion vectors */
1188     /* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
1189     PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
1190     PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
1191   }
1192
1193   /* special "No_MC" macroblock_type case */
1194   /* ISO/IEC 13818-2 section 7.6.3.5: Prediction in P pictures */
1195   if ((picture_coding_type==P_TYPE) 
1196     && !(*macroblock_type & (MACROBLOCK_MOTION_FORWARD|MACROBLOCK_INTRA)))
1197   {
1198     /* non-intra mb without forward mv in a P picture */
1199     /* ISO/IEC 13818-2 section 7.6.3.4: Resetting motion vector predictors */
1200     PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
1201
1202     /* derive motion_type */
1203     /* ISO/IEC 13818-2 section 6.3.17.1: Macroblock modes, frame_motion_type */
1204     if (picture_structure==FRAME_PICTURE)
1205       *motion_type = MC_FRAME;
1206     else
1207     {
1208       *motion_type = MC_FIELD;
1209       /* predict from field of same parity */
1210       motion_vertical_field_select[0][0] = (picture_structure==BOTTOM_FIELD);
1211     }
1212   }
1213
1214   if (*stwclass==4)
1215   {
1216     /* purely spatially predicted macroblock */
1217     /* ISO/IEC 13818-2 section 7.7.5.1: Resetting motion vector predictions */
1218     PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
1219     PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
1220   }
1221
1222   /* successfully decoded macroblock */
1223   return(1);
1224
1225 } /* decode_macroblock */
1226
1227