2 /* mpeg2dec.c, main(), initialization, option processing */
4 /* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
7 * Disclaimer of Warranty
9 * These software programs are available to the user without any license fee or
10 * royalty on an "as is" basis. The MPEG Software Simulation Group disclaims
11 * any and all warranties, whether express, implied, or statuary, including any
12 * implied warranties or merchantability or of fitness for a particular
13 * purpose. In no event shall the copyright-holder be liable for any
14 * incidental, punitive, or consequential damages of any kind whatsoever
15 * arising from the use of these programs.
17 * This disclaimer of warranty extends to the user of these programs and user's
18 * customers, employees, agents, transferees, successors, and assigns.
20 * The MPEG Software Simulation Group does not represent or warrant that the
21 * programs furnished hereunder are free of infringement of any third-party
24 * Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
25 * are subject to royalty fees to patent holders. Many of these patents are
26 * general enough such that they are unavoidable regardless of implementation
39 /* private prototypes */
40 static int video_sequence _ANSI_ARGS_((int *framenum));
41 static int Decode_Bitstream _ANSI_ARGS_((void));
42 static int Headers _ANSI_ARGS_((void));
43 static void Initialize_Sequence _ANSI_ARGS_((void));
44 static void Initialize_Decoder _ANSI_ARGS_((void));
45 static void Deinitialize_Sequence _ANSI_ARGS_((void));
46 static void Process_Options _ANSI_ARGS_((int argc, char *argv[]));
50 static int Get_Val _ANSI_ARGS_((char *argv[]));
55 static void Clear_Options();
57 static void Print_Options();
61 int my_open(char *filename)
63 return open(filename,O_RDONLY|O_BINARY);
65 off_t my_seek(int infile, off_t offset,int whence)
67 return lseek(infile, offset, whence);
69 ssize_t my_read(int infile,void *buf,size_t count)
71 return read(infile,buf,count);
73 int my_close(int infile)
78 ostream *my_fopen(const char *path, const char *mode)
80 FILE *fd = fopen(path, mode);
81 ostream *os = (ostream*)malloc(sizeof(ostream));
86 int my_fseek(ostream *stream, long offset, int whence)
88 return fseek(stream->Fd, offset, whence);
91 size_t my_fread(void *ptr, size_t size, size_t nmemb, ostream *stream)
93 return fread(ptr, size, nmemb, stream->Fd);
96 size_t my_fwrite(const void *ptr, size_t size, size_t nmemb, ostream *stream)
98 return fwrite(ptr, size, nmemb, stream->Fd);
101 int my_fclose(ostream *fp)
109 int my_printf(const char *format, ...)
111 //return printf(format, ...);
115 va_start(argptr, format);
116 ret = vprintf(format, argptr);
122 int my_sprintf(char *str, const char *format, ...)
124 //return sprintf(str, format, ...);
128 va_start(argptr, format);
129 ret = vsprintf(str,format, argptr);
135 int my_fprintf(const char *format, ...)
137 //return fprintf(stderr, format, ...);
141 va_start(argptr, format);
142 ret = vfprintf(stderr,format, argptr);
147 void my_exit(int status)
153 #define GDCM_BUILD_MPEG2DEC
155 #ifdef GDCM_BUILD_MPEG2DEC
161 base.open_stream = my_open;
162 base.seek_stream = my_seek;
163 base.read_stream = my_read;
164 base.close_stream = my_close;
168 /* decode command line arguments */
169 Process_Options(argc,argv);
175 ld = &base; /* select base layer context */
177 /* open MPEG base layer bitstream file(s) */
178 /* NOTE: this is either a base layer stream or a spatial enhancement stream */
179 /* if ((base.Infile=open(Main_Bitstream_Filename,O_RDONLY|O_BINARY))<0) */
180 base.Infile = ld->open_stream(Main_Bitstream_Filename);
181 if( base.Infile < 0 )
183 fprintf(stderr,"Base layer input file %s not found\n", Main_Bitstream_Filename);
192 if(Show_Bits(8)==0x47)
194 sprintf(Error_Text,"Decoder currently does not parse transport streams\n");
199 code = Show_Bits(32);
203 case SEQUENCE_HEADER_CODE:
205 case PACK_START_CODE:
206 System_Stream_Flag = 1;
207 case VIDEO_ELEMENTARY_STREAM:
208 System_Stream_Flag = 1;
211 sprintf(Error_Text,"Unable to recognize stream type\n");
216 /*lseek(base.Infile, 0l, SEEK_SET);*/
217 ld->seek_stream(base.Infile,0l,SEEK_SET);
223 /*lseek(base.Infile, 0l, SEEK_SET);*/
224 ld->seek_stream(base.Infile,0l,SEEK_SET);
231 ld = &enhan; /* select enhancement layer context */
233 /*if ((enhan.Infile = open(Enhancement_Layer_Bitstream_Filename,O_RDONLY|O_BINARY))<0)*/
234 enhan.Infile = ld->open_stream(Enhancement_Layer_Bitstream_Filename);
237 sprintf(Error_Text,"enhancment layer bitstream file %s not found\n",
238 Enhancement_Layer_Bitstream_Filename);
247 Initialize_Decoder();
249 ret = Decode_Bitstream();
251 /*close(base.Infile);*/
252 ld->close_stream(base.Infile);
255 /*close(enhan.Infile);*/
256 ld->close_stream(enhan.Infile);
260 #endif /*GDCM_BUILD_MPEG2DEC*/
262 /* IMPLEMENTATION specific routines */
263 static void Initialize_Decoder()
268 if (!(Clip=(unsigned char *)malloc(1024)))
269 Error("Clip[] malloc failed\n");
273 for (i=-384; i<640; i++)
274 Clip[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
277 if (Reference_IDCT_Flag)
278 Initialize_Reference_IDCT();
280 Initialize_Fast_IDCT();
284 /* mostly IMPLEMENTAION specific rouintes */
285 static void Initialize_Sequence()
288 static int Table_6_20[3] = {6,8,12};
290 /* check scalability mode of enhancement layer */
291 if (Two_Streams && (enhan.scalable_mode!=SC_SNR) && (base.scalable_mode!=SC_DP))
292 Error("unsupported scalability mode\n");
294 /* force MPEG-1 parameters for proper decoder behavior */
295 /* see ISO/IEC 13818-2 section D.9.14 */
296 if (!base.MPEG2_Flag)
298 progressive_sequence = 1;
299 progressive_frame = 1;
300 picture_structure = FRAME_PICTURE;
301 frame_pred_frame_dct = 1;
302 chroma_format = CHROMA420;
303 matrix_coefficients = 5;
306 /* round to nearest multiple of coded macroblocks */
307 /* ISO/IEC 13818-2 section 6.3.3 sequence_header() */
308 mb_width = (horizontal_size+15)/16;
309 mb_height = (base.MPEG2_Flag && !progressive_sequence) ? 2*((vertical_size+31)/32)
310 : (vertical_size+15)/16;
312 Coded_Picture_Width = 16*mb_width;
313 Coded_Picture_Height = 16*mb_height;
315 /* ISO/IEC 13818-2 sections 6.1.1.8, 6.1.1.9, and 6.1.1.10 */
316 Chroma_Width = (chroma_format==CHROMA444) ? Coded_Picture_Width
317 : Coded_Picture_Width>>1;
318 Chroma_Height = (chroma_format!=CHROMA420) ? Coded_Picture_Height
319 : Coded_Picture_Height>>1;
321 /* derived based on Table 6-20 in ISO/IEC 13818-2 section 6.3.17 */
322 block_count = Table_6_20[chroma_format-1];
324 for (cc=0; cc<3; cc++)
327 size = Coded_Picture_Width*Coded_Picture_Height;
329 size = Chroma_Width*Chroma_Height;
331 if (!(backward_reference_frame[cc] = (unsigned char *)malloc(size)))
332 Error("backward_reference_frame[] malloc failed\n");
334 if (!(forward_reference_frame[cc] = (unsigned char *)malloc(size)))
335 Error("forward_reference_frame[] malloc failed\n");
337 if (!(auxframe[cc] = (unsigned char *)malloc(size)))
338 Error("auxframe[] malloc failed\n");
341 if (!(substitute_frame[cc] = (unsigned char *)malloc(size)))
342 Error("substitute_frame[] malloc failed\n");
345 if (base.scalable_mode==SC_SPAT)
347 /* this assumes lower layer is 4:2:0 */
348 if (!(llframe0[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
349 Error("llframe0 malloc failed\n");
350 if (!(llframe1[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
351 Error("llframe1 malloc failed\n");
355 /* SCALABILITY: Spatial */
356 if (base.scalable_mode==SC_SPAT)
358 if (!(lltmp = (short *)malloc(lower_layer_prediction_horizontal_size*((lower_layer_prediction_vertical_size*vertical_subsampling_factor_n)/vertical_subsampling_factor_m)*sizeof(short))))
359 Error("lltmp malloc failed\n");
363 if (Output_Type==T_X11)
365 Initialize_Display_Process("");
366 Initialize_Dither_Matrix();
375 fprintf(stderr,text);
379 /* Trace_Flag output */
380 void Print_Bits(code,bits,len)
384 for (i=0; i<len; i++)
385 printf("%d",(code>>(bits-1-i))&1);
390 /* option processing */
391 static void Process_Options(argc,argv)
392 int argc; /* argument count */
393 char *argv[]; /* argument vector */
395 int i, LastArg, NextArg;
397 /* at least one argument should be present */
400 printf("\n%s, %s\n",Version,Author);
401 printf("Usage: mpeg2decode {options}\n"
402 "Options: -b file main bitstream (base or spatial enhancement layer)\n"
403 " -cn file conformance report (n: level)\n"
404 " -e file enhancement layer bitstream (SNR or Data Partitioning)\n"
405 " -f store/display interlaced video in frame format\n"
406 " -g concatenated file format for substitution method (-x)\n"
407 " -in file information & statistics report (n: level)\n"
408 " -l file file name pattern for lower layer sequence\n"
409 " (for spatial scalability)\n"
410 " -on file output format (0:YUV 1:SIF 2:TGA 3:PPM 4:X11 5:X11HiQ)\n"
411 " -q disable warnings to stderr\n"
412 " -r use double precision reference IDCT\n"
413 " -t enable low level tracing to stdout\n"
414 " -u file print user_data to stdio or file\n"
415 " -vn verbose output (n: level)\n"
416 " -x file filename pattern of picture substitution sequence\n\n"
417 "File patterns: for sequential filenames, \"printf\" style, e.g. rec%%d\n"
418 " or rec%%d%%c for fieldwise storage\n"
419 "Levels: 0:none 1:sequence 2:picture 3:slice 4:macroblock 5:block\n\n"
420 "Example: mpeg2decode -b bitstream.mpg -f -r -o0 rec%%d\n"
429 /* command-line options are proceeded by '-' */
433 /* check if this is the last argument */
434 LastArg = ((argc-i)==1);
436 /* parse ahead to see if another flag immediately follows current
437 argument (this is used to tell if a filename is missing) */
439 NextArg = (argv[i+1][0]=='-');
443 /* second character, [1], after '-' is the switch */
446 switch(toupper(argv[i][1]))
448 /* third character. [2], is the value */
450 Main_Bitstream_Flag = 1;
452 if(NextArg || LastArg)
454 printf("ERROR: -b must be followed the main bitstream filename\n");
457 Main_Bitstream_Filename = argv[++i];
465 Verify_Flag = atoi(&argv[i][2]);
467 if((Verify_Flag < NO_LAYER) || (Verify_Flag > ALL_LAYERS))
469 printf("ERROR: -c level (%d) out of range [%d,%d]\n",
470 Verify_Flag, NO_LAYER, ALL_LAYERS);
474 printf("This program not compiled for Verify_Flag option\n");
479 Two_Streams = 1; /* either Data Partitioning (DP) or SNR Scalability enhancment */
481 if(NextArg || LastArg)
483 printf("ERROR: -e must be followed by filename\n");
487 Enhancement_Layer_Bitstream_Filename = argv[++i];
493 Frame_Store_Flag = 1;
497 Big_Picture_Flag = 1;
503 Stats_Flag = atoi(&argv[i][2]);
505 printf("WARNING: This program not compiled for -i option\n");
509 case 'L': /* spatial scalability flag */
512 if(NextArg || LastArg)
514 printf("ERROR: -l must be followed by filename\n");
518 Lower_Layer_Picture_Filename = argv[++i];
524 Output_Type = atoi(&argv[i][2]);
526 if((Output_Type==4) || (Output_Type==5))
527 Output_Picture_Filename = ""; /* no need of filename */
528 else if(NextArg || LastArg)
530 printf("ERROR: -o must be followed by filename\n");
534 /* filename is separated by space, so it becomes the next argument */
535 Output_Picture_Filename = argv[++i];
538 if (Output_Type==T_X11HIQ)
551 Reference_IDCT_Flag = 1;
558 printf("WARNING: This program not compiled for -t option\n");
567 Verbose_Flag = atoi(&argv[i][2]);
569 printf("This program not compiled for -v option\n");
577 if(NextArg || LastArg)
579 printf("ERROR: -x must be followed by filename\n");
583 Substitute_Picture_Filename = argv[++i];
590 fprintf(stderr,"undefined option -%c ignored. Exiting program\n",
596 } /* if argv[i][0] == '-' */
600 /* check for bitstream filename argument (there must always be one, at the very end
601 of the command line arguments */
606 /* options sense checking */
608 if(Main_Bitstream_Flag!=1)
610 printf("There must be a main bitstream specified (-b filename)\n");
613 /* force display process to show frame pictures */
614 if((Output_Type==4 || Output_Type==5) && Frame_Store_Flag)
615 Display_Progressive_Flag = 1;
617 Display_Progressive_Flag = 0;
620 /* parse the bitstream, do not actually decode it completely */
626 Decode_Layer = Verify_Flag;
627 printf("FYI: Decoding bitstream elements up to: %s\n",
628 Layer_Table[Decode_Layer]);
632 Decode_Layer = ALL_LAYERS;
636 /* no output type specified */
640 Output_Picture_Filename = "";
645 if (Output_Type==T_X11)
648 Display_Progressive_Flag = 1;
650 Display_Progressive_Flag = 0;
652 Frame_Store_Flag = 1; /* to avoid calling dither() twice */
662 this is an old routine used to convert command line arguments
665 static int Get_Val(argv)
670 if (sscanf(argv[1]+2,"%d",&val)!=1)
673 while (isdigit(argv[1][2]))
689 /* return when end of sequence (0) or picture
690 header has been parsed (1) */
698 if (Get_Hdr()!=ret && !Quiet_Flag)
699 fprintf(stderr,"streams out of sync\n");
708 static int Decode_Bitstream()
711 int Bitstream_Framenum;
713 Bitstream_Framenum = 0;
719 Clear_Verify_Headers();
726 ret = video_sequence(&Bitstream_Framenum);
735 static void Deinitialize_Sequence()
744 free(backward_reference_frame[i]);
745 free(forward_reference_frame[i]);
748 if (base.scalable_mode==SC_SPAT)
755 if (base.scalable_mode==SC_SPAT)
759 if (Output_Type==T_X11)
760 Terminate_Display_Process();
765 static int video_sequence(Bitstream_Framenumber)
766 int *Bitstream_Framenumber;
768 int Bitstream_Framenum;
769 int Sequence_Framenum;
772 Bitstream_Framenum = *Bitstream_Framenumber;
775 Initialize_Sequence();
777 /* decode picture whose header has already been parsed in
778 Decode_Bitstream() */
781 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
783 /* update picture numbers */
786 Bitstream_Framenum++;
790 /* loop through the rest of the pictures in the sequence */
791 while ((Return_Value=Headers()))
793 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
797 Bitstream_Framenum++;
803 if (Sequence_Framenum!=0)
805 Output_Last_Frame_of_Sequence(Bitstream_Framenum);
808 Deinitialize_Sequence();
811 Clear_Verify_Headers();
814 *Bitstream_Framenumber = Bitstream_Framenum;
815 return(Return_Value);
820 static void Clear_Options()
824 Output_Picture_Filename = " ";
827 Frame_Store_Flag = 0;
829 Lower_Layer_Picture_Filename = " ";
830 Reference_IDCT_Flag = 0;
834 Substitute_Picture_Filename = " ";
836 Enhancement_Layer_Bitstream_Filename = " ";
837 Big_Picture_Flag = 0;
838 Main_Bitstream_Flag = 0;
839 Main_Bitstream_Filename = " ";
847 static void Print_Options()
850 printf("Verbose_Flag = %d\n", Verbose_Flag);
851 printf("Output_Type = %d\n", Output_Type);
852 printf("Output_Picture_Filename = %s\n", Output_Picture_Filename);
853 printf("hiQdither = %d\n", hiQdither);
854 printf("Output_Type = %d\n", Output_Type);
855 printf("Frame_Store_Flag = %d\n", Frame_Store_Flag);
856 printf("Spatial_Flag = %d\n", Spatial_Flag);
857 printf("Lower_Layer_Picture_Filename = %s\n", Lower_Layer_Picture_Filename);
858 printf("Reference_IDCT_Flag = %d\n", Reference_IDCT_Flag);
859 printf("Trace_Flag = %d\n", Trace_Flag);
860 printf("Quiet_Flag = %d\n", Quiet_Flag);
861 printf("Ersatz_Flag = %d\n", Ersatz_Flag);
862 printf("Substitute_Picture_Filename = %s\n", Substitute_Picture_Filename);
863 printf("Two_Streams = %d\n", Two_Streams);
864 printf("Enhancement_Layer_Bitstream_Filename = %s\n", Enhancement_Layer_Bitstream_Filename);
865 printf("Big_Picture_Flag = %d\n", Big_Picture_Flag);
866 printf("Main_Bitstream_Flag = %d\n", Main_Bitstream_Flag);
867 printf("Main_Bitstream_Filename = %s\n", Main_Bitstream_Filename);
868 printf("Verify_Flag = %d\n", Verify_Flag);
869 printf("Stats_Flag = %d\n", Stats_Flag);
870 printf("User_Data_Flag = %d\n", User_Data_Flag);