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