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