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_Decoder _ANSI_ARGS_((void));
46 static void Deinitialize_Sequence _ANSI_ARGS_((void));
47 static void Process_Options _ANSI_ARGS_((int argc, char *argv[]));
51 static int Get_Val _ANSI_ARGS_((char *argv[]));
56 static void Clear_Options();
58 static void Print_Options();
62 int my_open(char *filename)
64 return open(filename,O_RDONLY|O_BINARY);
67 off_t my_seek(int infile, off_t offset,int whence)
69 return lseek(infile, offset, whence);
71 ssize_t my_read(int infile,void *buf,size_t count)
73 return read(infile,buf,count);
75 int my_close(int infile)
80 int my_fopenr(const char *path, const char *mode, istream *os)
82 FILE *fd = fopen(path, mode);
93 int my_fopen(const char *path, const char *mode, ostream *os)
95 FILE *fd = fopen(path, mode);
106 int my_fseek(ostream *stream, long offset, int whence)
108 return fseek(stream->OutFd, offset, whence);
110 int my_fseekr(istream *stream, long offset, int whence)
112 return fseek(stream->InFd, offset, whence);
115 size_t my_fread(void *ptr, size_t size, size_t nmemb, istream *stream)
117 return fread(ptr, size, nmemb, stream->InFd);
120 size_t my_fwrite(const void *ptr, size_t size, size_t nmemb, ostream *stream)
122 return fwrite(ptr, size, nmemb, stream->OutFd);
125 int my_fcloser(istream *fp)
127 return fclose(fp->InFd);
129 int my_fclose(ostream *fp)
131 return fclose(fp->OutFd);
135 int my_printf(const char *format, ...)
137 //return printf(format, ...);
141 va_start(argptr, format);
142 ret = vprintf(format, argptr);
148 int my_sprintf(char *str, const char *format, ...)
150 //return sprintf(str, format, ...);
154 va_start(argptr, format);
155 ret = vsprintf(str,format, argptr);
161 int my_fprintf(const char *format, ...)
163 //return fprintf(stderr, format, ...);
167 va_start(argptr, format);
168 ret = vfprintf(stderr,format, argptr);
173 void my_exit(int status)
179 #define GDCM_BUILD_MPEG2DEC
181 #ifdef GDCM_BUILD_MPEG2DEC
187 base.open_stream = my_open;
188 base.seek_stream = my_seek;
189 base.read_stream = my_read;
190 base.close_stream = my_close;
194 /* decode command line arguments */
195 Process_Options(argc,argv);
201 ld = &base; /* select base layer context */
203 /* open MPEG base layer bitstream file(s) */
204 /* NOTE: this is either a base layer stream or a spatial enhancement stream */
205 /* if ((base.Infile=open(Main_Bitstream_Filename,O_RDONLY|O_BINARY))<0) */
206 base.Infile = ld->open_stream(Main_Bitstream_Filename);
207 if( base.Infile < 0 )
209 fprintf(stderr,"Base layer input file %s not found\n", Main_Bitstream_Filename);
218 if(Show_Bits(8)==0x47)
220 sprintf(Error_Text,"Decoder currently does not parse transport streams\n");
225 code = Show_Bits(32);
229 case SEQUENCE_HEADER_CODE:
231 case PACK_START_CODE:
232 System_Stream_Flag = 1;
233 case VIDEO_ELEMENTARY_STREAM:
234 System_Stream_Flag = 1;
237 sprintf(Error_Text,"Unable to recognize stream type\n");
242 /*lseek(base.Infile, 0l, SEEK_SET);*/
243 ld->seek_stream(base.Infile,0l,SEEK_SET);
249 /*lseek(base.Infile, 0l, SEEK_SET);*/
250 ld->seek_stream(base.Infile,0l,SEEK_SET);
257 ld = &enhan; /* select enhancement layer context */
259 /*if ((enhan.Infile = open(Enhancement_Layer_Bitstream_Filename,O_RDONLY|O_BINARY))<0)*/
260 enhan.Infile = ld->open_stream(Enhancement_Layer_Bitstream_Filename);
263 sprintf(Error_Text,"enhancment layer bitstream file %s not found\n",
264 Enhancement_Layer_Bitstream_Filename);
273 Initialize_Decoder();
275 ret = Decode_Bitstream();
277 /*close(base.Infile);*/
278 ld->close_stream(base.Infile);
281 /*close(enhan.Infile);*/
282 ld->close_stream(enhan.Infile);
284 DeInitialize_Decoder();
288 #endif /*GDCM_BUILD_MPEG2DEC*/
290 /* IMPLEMENTATION specific routines */
291 static void Initialize_Decoder()
296 if (!(Clip=(unsigned char *)malloc(1024)))
297 Error("Clip[] malloc failed\n");
301 for (i=-384; i<640; i++)
302 Clip[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
305 if (Reference_IDCT_Flag)
306 Initialize_Reference_IDCT();
308 Initialize_Fast_IDCT();
312 static void DeInitialize_Decoder()
314 free(Clip-384); // WTF !!!
317 /* mostly IMPLEMENTAION specific rouintes */
318 static void Initialize_Sequence()
321 static int Table_6_20[3] = {6,8,12};
323 /* check scalability mode of enhancement layer */
324 if (Two_Streams && (enhan.scalable_mode!=SC_SNR) && (base.scalable_mode!=SC_DP))
325 Error("unsupported scalability mode\n");
327 /* force MPEG-1 parameters for proper decoder behavior */
328 /* see ISO/IEC 13818-2 section D.9.14 */
329 if (!base.MPEG2_Flag)
331 progressive_sequence = 1;
332 progressive_frame = 1;
333 picture_structure = FRAME_PICTURE;
334 frame_pred_frame_dct = 1;
335 chroma_format = CHROMA420;
336 matrix_coefficients = 5;
339 /* round to nearest multiple of coded macroblocks */
340 /* ISO/IEC 13818-2 section 6.3.3 sequence_header() */
341 mb_width = (horizontal_size+15)/16;
342 mb_height = (base.MPEG2_Flag && !progressive_sequence) ? 2*((vertical_size+31)/32)
343 : (vertical_size+15)/16;
345 Coded_Picture_Width = 16*mb_width;
346 Coded_Picture_Height = 16*mb_height;
348 /* ISO/IEC 13818-2 sections 6.1.1.8, 6.1.1.9, and 6.1.1.10 */
349 Chroma_Width = (chroma_format==CHROMA444) ? Coded_Picture_Width
350 : Coded_Picture_Width>>1;
351 Chroma_Height = (chroma_format!=CHROMA420) ? Coded_Picture_Height
352 : Coded_Picture_Height>>1;
354 /* derived based on Table 6-20 in ISO/IEC 13818-2 section 6.3.17 */
355 block_count = Table_6_20[chroma_format-1];
357 for (cc=0; cc<3; cc++)
360 size = Coded_Picture_Width*Coded_Picture_Height;
362 size = Chroma_Width*Chroma_Height;
364 if (!(backward_reference_frame[cc] = (unsigned char *)malloc(size)))
365 Error("backward_reference_frame[] malloc failed\n");
367 if (!(forward_reference_frame[cc] = (unsigned char *)malloc(size)))
368 Error("forward_reference_frame[] malloc failed\n");
370 if (!(auxframe[cc] = (unsigned char *)malloc(size)))
371 Error("auxframe[] malloc failed\n");
374 if (!(substitute_frame[cc] = (unsigned char *)malloc(size)))
375 Error("substitute_frame[] malloc failed\n");
378 if (base.scalable_mode==SC_SPAT)
380 /* this assumes lower layer is 4:2:0 */
381 if (!(llframe0[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
382 Error("llframe0 malloc failed\n");
383 if (!(llframe1[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
384 Error("llframe1 malloc failed\n");
388 /* SCALABILITY: Spatial */
389 if (base.scalable_mode==SC_SPAT)
391 if (!(lltmp = (short *)malloc(lower_layer_prediction_horizontal_size*((lower_layer_prediction_vertical_size*vertical_subsampling_factor_n)/vertical_subsampling_factor_m)*sizeof(short))))
392 Error("lltmp malloc failed\n");
396 if (Output_Type==T_X11)
398 Initialize_Display_Process("");
399 Initialize_Dither_Matrix();
408 fprintf(stderr,text);
412 /* Trace_Flag output */
413 void Print_Bits(code,bits,len)
417 for (i=0; i<len; i++)
418 printf("%d",(code>>(bits-1-i))&1);
423 /* option processing */
424 static void Process_Options(argc,argv)
425 int argc; /* argument count */
426 char *argv[]; /* argument vector */
428 int i, LastArg, NextArg;
430 /* at least one argument should be present */
433 printf("\n%s, %s\n",Version,Author);
434 printf("Usage: mpeg2decode {options}\n"
435 "Options: -b file main bitstream (base or spatial enhancement layer)\n"
436 " -cn file conformance report (n: level)\n"
437 " -e file enhancement layer bitstream (SNR or Data Partitioning)\n"
438 " -f store/display interlaced video in frame format\n"
439 " -g concatenated file format for substitution method (-x)\n"
440 " -in file information & statistics report (n: level)\n"
441 " -l file file name pattern for lower layer sequence\n"
442 " (for spatial scalability)\n"
443 " -on file output format (0:YUV 1:SIF 2:TGA 3:PPM 4:X11 5:X11HiQ)\n"
444 " -q disable warnings to stderr\n"
445 " -r use double precision reference IDCT\n"
446 " -t enable low level tracing to stdout\n"
447 " -u file print user_data to stdio or file\n"
448 " -vn verbose output (n: level)\n"
449 " -x file filename pattern of picture substitution sequence\n\n"
450 "File patterns: for sequential filenames, \"printf\" style, e.g. rec%%d\n"
451 " or rec%%d%%c for fieldwise storage\n"
452 "Levels: 0:none 1:sequence 2:picture 3:slice 4:macroblock 5:block\n\n"
453 "Example: mpeg2decode -b bitstream.mpg -f -r -o0 rec%%d\n"
462 /* command-line options are proceeded by '-' */
466 /* check if this is the last argument */
467 LastArg = ((argc-i)==1);
469 /* parse ahead to see if another flag immediately follows current
470 argument (this is used to tell if a filename is missing) */
472 NextArg = (argv[i+1][0]=='-');
476 /* second character, [1], after '-' is the switch */
479 switch(toupper(argv[i][1]))
481 /* third character. [2], is the value */
483 Main_Bitstream_Flag = 1;
485 if(NextArg || LastArg)
487 printf("ERROR: -b must be followed the main bitstream filename\n");
490 Main_Bitstream_Filename = argv[++i];
498 Verify_Flag = atoi(&argv[i][2]);
500 if((Verify_Flag < NO_LAYER) || (Verify_Flag > ALL_LAYERS))
502 printf("ERROR: -c level (%d) out of range [%d,%d]\n",
503 Verify_Flag, NO_LAYER, ALL_LAYERS);
507 printf("This program not compiled for Verify_Flag option\n");
512 Two_Streams = 1; /* either Data Partitioning (DP) or SNR Scalability enhancment */
514 if(NextArg || LastArg)
516 printf("ERROR: -e must be followed by filename\n");
520 Enhancement_Layer_Bitstream_Filename = argv[++i];
526 Frame_Store_Flag = 1;
530 Big_Picture_Flag = 1;
536 Stats_Flag = atoi(&argv[i][2]);
538 printf("WARNING: This program not compiled for -i option\n");
542 case 'L': /* spatial scalability flag */
545 if(NextArg || LastArg)
547 printf("ERROR: -l must be followed by filename\n");
551 Lower_Layer_Picture_Filename = argv[++i];
557 Output_Type = atoi(&argv[i][2]);
559 if((Output_Type==4) || (Output_Type==5))
560 Output_Picture_Filename = ""; /* no need of filename */
561 else if(NextArg || LastArg)
563 printf("ERROR: -o must be followed by filename\n");
567 /* filename is separated by space, so it becomes the next argument */
568 Output_Picture_Filename = argv[++i];
571 if (Output_Type==T_X11HIQ)
584 Reference_IDCT_Flag = 1;
591 printf("WARNING: This program not compiled for -t option\n");
600 Verbose_Flag = atoi(&argv[i][2]);
602 printf("This program not compiled for -v option\n");
610 if(NextArg || LastArg)
612 printf("ERROR: -x must be followed by filename\n");
616 Substitute_Picture_Filename = argv[++i];
623 fprintf(stderr,"undefined option -%c ignored. Exiting program\n",
629 } /* if argv[i][0] == '-' */
633 /* check for bitstream filename argument (there must always be one, at the very end
634 of the command line arguments */
639 /* options sense checking */
641 if(Main_Bitstream_Flag!=1)
643 printf("There must be a main bitstream specified (-b filename)\n");
646 /* force display process to show frame pictures */
647 if((Output_Type==4 || Output_Type==5) && Frame_Store_Flag)
648 Display_Progressive_Flag = 1;
650 Display_Progressive_Flag = 0;
653 /* parse the bitstream, do not actually decode it completely */
659 Decode_Layer = Verify_Flag;
660 printf("FYI: Decoding bitstream elements up to: %s\n",
661 Layer_Table[Decode_Layer]);
665 Decode_Layer = ALL_LAYERS;
669 /* no output type specified */
673 Output_Picture_Filename = "";
678 if (Output_Type==T_X11)
681 Display_Progressive_Flag = 1;
683 Display_Progressive_Flag = 0;
685 Frame_Store_Flag = 1; /* to avoid calling dither() twice */
695 this is an old routine used to convert command line arguments
698 static int Get_Val(argv)
703 if (sscanf(argv[1]+2,"%d",&val)!=1)
706 while (isdigit(argv[1][2]))
722 /* return when end of sequence (0) or picture
723 header has been parsed (1) */
731 if (Get_Hdr()!=ret && !Quiet_Flag)
732 fprintf(stderr,"streams out of sync\n");
741 static int Decode_Bitstream()
744 int Bitstream_Framenum;
746 Bitstream_Framenum = 0;
752 Clear_Verify_Headers();
759 ret = video_sequence(&Bitstream_Framenum);
768 static void Deinitialize_Sequence()
772 /* First clenup the static buffer in store.c */
780 free(backward_reference_frame[i]);
781 free(forward_reference_frame[i]);
784 if (base.scalable_mode==SC_SPAT)
791 if (base.scalable_mode==SC_SPAT)
795 if (Output_Type==T_X11)
796 Terminate_Display_Process();
801 static int video_sequence(Bitstream_Framenumber)
802 int *Bitstream_Framenumber;
804 int Bitstream_Framenum;
805 int Sequence_Framenum;
808 Bitstream_Framenum = *Bitstream_Framenumber;
811 Initialize_Sequence();
813 /* decode picture whose header has already been parsed in
814 Decode_Bitstream() */
817 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
819 /* update picture numbers */
822 Bitstream_Framenum++;
826 /* loop through the rest of the pictures in the sequence */
827 while ((Return_Value=Headers()))
829 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
833 Bitstream_Framenum++;
839 if (Sequence_Framenum!=0)
841 Output_Last_Frame_of_Sequence(Bitstream_Framenum);
844 Deinitialize_Sequence();
847 Clear_Verify_Headers();
850 *Bitstream_Framenumber = Bitstream_Framenum;
851 return(Return_Value);
856 static void Clear_Options()
860 Output_Picture_Filename = " ";
863 Frame_Store_Flag = 0;
865 Lower_Layer_Picture_Filename = " ";
866 Reference_IDCT_Flag = 0;
870 Substitute_Picture_Filename = " ";
872 Enhancement_Layer_Bitstream_Filename = " ";
873 Big_Picture_Flag = 0;
874 Main_Bitstream_Flag = 0;
875 Main_Bitstream_Filename = " ";
883 static void Print_Options()
886 printf("Verbose_Flag = %d\n", Verbose_Flag);
887 printf("Output_Type = %d\n", Output_Type);
888 printf("Output_Picture_Filename = %s\n", Output_Picture_Filename);
889 printf("hiQdither = %d\n", hiQdither);
890 printf("Output_Type = %d\n", Output_Type);
891 printf("Frame_Store_Flag = %d\n", Frame_Store_Flag);
892 printf("Spatial_Flag = %d\n", Spatial_Flag);
893 printf("Lower_Layer_Picture_Filename = %s\n", Lower_Layer_Picture_Filename);
894 printf("Reference_IDCT_Flag = %d\n", Reference_IDCT_Flag);
895 printf("Trace_Flag = %d\n", Trace_Flag);
896 printf("Quiet_Flag = %d\n", Quiet_Flag);
897 printf("Ersatz_Flag = %d\n", Ersatz_Flag);
898 printf("Substitute_Picture_Filename = %s\n", Substitute_Picture_Filename);
899 printf("Two_Streams = %d\n", Two_Streams);
900 printf("Enhancement_Layer_Bitstream_Filename = %s\n", Enhancement_Layer_Bitstream_Filename);
901 printf("Big_Picture_Flag = %d\n", Big_Picture_Flag);
902 printf("Main_Bitstream_Flag = %d\n", Main_Bitstream_Flag);
903 printf("Main_Bitstream_Filename = %s\n", Main_Bitstream_Filename);
904 printf("Verify_Flag = %d\n", Verify_Flag);
905 printf("Stats_Flag = %d\n", Stats_Flag);
906 printf("User_Data_Flag = %d\n", User_Data_Flag);