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);
66 off_t my_seek(int infile, off_t offset,int whence)
68 return lseek(infile, offset, whence);
70 ssize_t my_read(int infile,void *buf,size_t count)
72 return read(infile,buf,count);
74 int my_close(int infile)
79 int my_fopenr(const char *path, const char *mode, istream *os)
81 FILE *fd = fopen(path, mode);
92 int my_fopen(const char *path, const char *mode, ostream *os)
94 FILE *fd = fopen(path, mode);
105 int my_fseek(ostream *stream, long offset, int whence)
107 return fseek(stream->OutFd, offset, whence);
109 int my_fseekr(istream *stream, long offset, int whence)
111 return fseek(stream->InFd, offset, whence);
114 size_t my_fread(void *ptr, size_t size, size_t nmemb, istream *stream)
116 return fread(ptr, size, nmemb, stream->InFd);
119 size_t my_fwrite(const void *ptr, size_t size, size_t nmemb, ostream *stream)
121 return fwrite(ptr, size, nmemb, stream->OutFd);
124 int my_fcloser(istream *fp)
126 return fclose(fp->InFd);
128 int my_fclose(ostream *fp)
130 return fclose(fp->OutFd);
134 int my_printf(const char *format, ...)
136 //return printf(format, ...);
140 va_start(argptr, format);
141 ret = vprintf(format, argptr);
147 int my_sprintf(char *str, const char *format, ...)
149 //return sprintf(str, format, ...);
153 va_start(argptr, format);
154 ret = vsprintf(str,format, argptr);
160 int my_fprintf(const char *format, ...)
162 //return fprintf(stderr, format, ...);
166 va_start(argptr, format);
167 ret = vfprintf(stderr,format, argptr);
172 void my_exit(int status)
178 #define GDCM_BUILD_MPEG2DEC
180 #ifdef GDCM_BUILD_MPEG2DEC
186 base.open_stream = my_open;
187 base.seek_stream = my_seek;
188 base.read_stream = my_read;
189 base.close_stream = my_close;
193 /* decode command line arguments */
194 Process_Options(argc,argv);
200 ld = &base; /* select base layer context */
202 /* open MPEG base layer bitstream file(s) */
203 /* NOTE: this is either a base layer stream or a spatial enhancement stream */
204 /* if ((base.Infile=open(Main_Bitstream_Filename,O_RDONLY|O_BINARY))<0) */
205 base.Infile = ld->open_stream(Main_Bitstream_Filename);
206 if( base.Infile < 0 )
208 fprintf(stderr,"Base layer input file %s not found\n", Main_Bitstream_Filename);
217 if(Show_Bits(8)==0x47)
219 sprintf(Error_Text,"Decoder currently does not parse transport streams\n");
224 code = Show_Bits(32);
228 case SEQUENCE_HEADER_CODE:
230 case PACK_START_CODE:
231 System_Stream_Flag = 1;
232 case VIDEO_ELEMENTARY_STREAM:
233 System_Stream_Flag = 1;
236 sprintf(Error_Text,"Unable to recognize stream type\n");
241 /*lseek(base.Infile, 0l, SEEK_SET);*/
242 ld->seek_stream(base.Infile,0l,SEEK_SET);
248 /*lseek(base.Infile, 0l, SEEK_SET);*/
249 ld->seek_stream(base.Infile,0l,SEEK_SET);
256 ld = &enhan; /* select enhancement layer context */
258 /*if ((enhan.Infile = open(Enhancement_Layer_Bitstream_Filename,O_RDONLY|O_BINARY))<0)*/
259 enhan.Infile = ld->open_stream(Enhancement_Layer_Bitstream_Filename);
262 sprintf(Error_Text,"enhancment layer bitstream file %s not found\n",
263 Enhancement_Layer_Bitstream_Filename);
272 Initialize_Decoder();
274 ret = Decode_Bitstream();
276 /*close(base.Infile);*/
277 ld->close_stream(base.Infile);
280 /*close(enhan.Infile);*/
281 ld->close_stream(enhan.Infile);
285 #endif /*GDCM_BUILD_MPEG2DEC*/
287 /* IMPLEMENTATION specific routines */
288 static void Initialize_Decoder()
293 if (!(Clip=(unsigned char *)malloc(1024)))
294 Error("Clip[] malloc failed\n");
298 for (i=-384; i<640; i++)
299 Clip[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
302 if (Reference_IDCT_Flag)
303 Initialize_Reference_IDCT();
305 Initialize_Fast_IDCT();
309 /* mostly IMPLEMENTAION specific rouintes */
310 static void Initialize_Sequence()
313 static int Table_6_20[3] = {6,8,12};
315 /* check scalability mode of enhancement layer */
316 if (Two_Streams && (enhan.scalable_mode!=SC_SNR) && (base.scalable_mode!=SC_DP))
317 Error("unsupported scalability mode\n");
319 /* force MPEG-1 parameters for proper decoder behavior */
320 /* see ISO/IEC 13818-2 section D.9.14 */
321 if (!base.MPEG2_Flag)
323 progressive_sequence = 1;
324 progressive_frame = 1;
325 picture_structure = FRAME_PICTURE;
326 frame_pred_frame_dct = 1;
327 chroma_format = CHROMA420;
328 matrix_coefficients = 5;
331 /* round to nearest multiple of coded macroblocks */
332 /* ISO/IEC 13818-2 section 6.3.3 sequence_header() */
333 mb_width = (horizontal_size+15)/16;
334 mb_height = (base.MPEG2_Flag && !progressive_sequence) ? 2*((vertical_size+31)/32)
335 : (vertical_size+15)/16;
337 Coded_Picture_Width = 16*mb_width;
338 Coded_Picture_Height = 16*mb_height;
340 /* ISO/IEC 13818-2 sections 6.1.1.8, 6.1.1.9, and 6.1.1.10 */
341 Chroma_Width = (chroma_format==CHROMA444) ? Coded_Picture_Width
342 : Coded_Picture_Width>>1;
343 Chroma_Height = (chroma_format!=CHROMA420) ? Coded_Picture_Height
344 : Coded_Picture_Height>>1;
346 /* derived based on Table 6-20 in ISO/IEC 13818-2 section 6.3.17 */
347 block_count = Table_6_20[chroma_format-1];
349 for (cc=0; cc<3; cc++)
352 size = Coded_Picture_Width*Coded_Picture_Height;
354 size = Chroma_Width*Chroma_Height;
356 if (!(backward_reference_frame[cc] = (unsigned char *)malloc(size)))
357 Error("backward_reference_frame[] malloc failed\n");
359 if (!(forward_reference_frame[cc] = (unsigned char *)malloc(size)))
360 Error("forward_reference_frame[] malloc failed\n");
362 if (!(auxframe[cc] = (unsigned char *)malloc(size)))
363 Error("auxframe[] malloc failed\n");
366 if (!(substitute_frame[cc] = (unsigned char *)malloc(size)))
367 Error("substitute_frame[] malloc failed\n");
370 if (base.scalable_mode==SC_SPAT)
372 /* this assumes lower layer is 4:2:0 */
373 if (!(llframe0[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
374 Error("llframe0 malloc failed\n");
375 if (!(llframe1[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
376 Error("llframe1 malloc failed\n");
380 /* SCALABILITY: Spatial */
381 if (base.scalable_mode==SC_SPAT)
383 if (!(lltmp = (short *)malloc(lower_layer_prediction_horizontal_size*((lower_layer_prediction_vertical_size*vertical_subsampling_factor_n)/vertical_subsampling_factor_m)*sizeof(short))))
384 Error("lltmp malloc failed\n");
388 if (Output_Type==T_X11)
390 Initialize_Display_Process("");
391 Initialize_Dither_Matrix();
400 fprintf(stderr,text);
404 /* Trace_Flag output */
405 void Print_Bits(code,bits,len)
409 for (i=0; i<len; i++)
410 printf("%d",(code>>(bits-1-i))&1);
415 /* option processing */
416 static void Process_Options(argc,argv)
417 int argc; /* argument count */
418 char *argv[]; /* argument vector */
420 int i, LastArg, NextArg;
422 /* at least one argument should be present */
425 printf("\n%s, %s\n",Version,Author);
426 printf("Usage: mpeg2decode {options}\n"
427 "Options: -b file main bitstream (base or spatial enhancement layer)\n"
428 " -cn file conformance report (n: level)\n"
429 " -e file enhancement layer bitstream (SNR or Data Partitioning)\n"
430 " -f store/display interlaced video in frame format\n"
431 " -g concatenated file format for substitution method (-x)\n"
432 " -in file information & statistics report (n: level)\n"
433 " -l file file name pattern for lower layer sequence\n"
434 " (for spatial scalability)\n"
435 " -on file output format (0:YUV 1:SIF 2:TGA 3:PPM 4:X11 5:X11HiQ)\n"
436 " -q disable warnings to stderr\n"
437 " -r use double precision reference IDCT\n"
438 " -t enable low level tracing to stdout\n"
439 " -u file print user_data to stdio or file\n"
440 " -vn verbose output (n: level)\n"
441 " -x file filename pattern of picture substitution sequence\n\n"
442 "File patterns: for sequential filenames, \"printf\" style, e.g. rec%%d\n"
443 " or rec%%d%%c for fieldwise storage\n"
444 "Levels: 0:none 1:sequence 2:picture 3:slice 4:macroblock 5:block\n\n"
445 "Example: mpeg2decode -b bitstream.mpg -f -r -o0 rec%%d\n"
454 /* command-line options are proceeded by '-' */
458 /* check if this is the last argument */
459 LastArg = ((argc-i)==1);
461 /* parse ahead to see if another flag immediately follows current
462 argument (this is used to tell if a filename is missing) */
464 NextArg = (argv[i+1][0]=='-');
468 /* second character, [1], after '-' is the switch */
471 switch(toupper(argv[i][1]))
473 /* third character. [2], is the value */
475 Main_Bitstream_Flag = 1;
477 if(NextArg || LastArg)
479 printf("ERROR: -b must be followed the main bitstream filename\n");
482 Main_Bitstream_Filename = argv[++i];
490 Verify_Flag = atoi(&argv[i][2]);
492 if((Verify_Flag < NO_LAYER) || (Verify_Flag > ALL_LAYERS))
494 printf("ERROR: -c level (%d) out of range [%d,%d]\n",
495 Verify_Flag, NO_LAYER, ALL_LAYERS);
499 printf("This program not compiled for Verify_Flag option\n");
504 Two_Streams = 1; /* either Data Partitioning (DP) or SNR Scalability enhancment */
506 if(NextArg || LastArg)
508 printf("ERROR: -e must be followed by filename\n");
512 Enhancement_Layer_Bitstream_Filename = argv[++i];
518 Frame_Store_Flag = 1;
522 Big_Picture_Flag = 1;
528 Stats_Flag = atoi(&argv[i][2]);
530 printf("WARNING: This program not compiled for -i option\n");
534 case 'L': /* spatial scalability flag */
537 if(NextArg || LastArg)
539 printf("ERROR: -l must be followed by filename\n");
543 Lower_Layer_Picture_Filename = argv[++i];
549 Output_Type = atoi(&argv[i][2]);
551 if((Output_Type==4) || (Output_Type==5))
552 Output_Picture_Filename = ""; /* no need of filename */
553 else if(NextArg || LastArg)
555 printf("ERROR: -o must be followed by filename\n");
559 /* filename is separated by space, so it becomes the next argument */
560 Output_Picture_Filename = argv[++i];
563 if (Output_Type==T_X11HIQ)
576 Reference_IDCT_Flag = 1;
583 printf("WARNING: This program not compiled for -t option\n");
592 Verbose_Flag = atoi(&argv[i][2]);
594 printf("This program not compiled for -v option\n");
602 if(NextArg || LastArg)
604 printf("ERROR: -x must be followed by filename\n");
608 Substitute_Picture_Filename = argv[++i];
615 fprintf(stderr,"undefined option -%c ignored. Exiting program\n",
621 } /* if argv[i][0] == '-' */
625 /* check for bitstream filename argument (there must always be one, at the very end
626 of the command line arguments */
631 /* options sense checking */
633 if(Main_Bitstream_Flag!=1)
635 printf("There must be a main bitstream specified (-b filename)\n");
638 /* force display process to show frame pictures */
639 if((Output_Type==4 || Output_Type==5) && Frame_Store_Flag)
640 Display_Progressive_Flag = 1;
642 Display_Progressive_Flag = 0;
645 /* parse the bitstream, do not actually decode it completely */
651 Decode_Layer = Verify_Flag;
652 printf("FYI: Decoding bitstream elements up to: %s\n",
653 Layer_Table[Decode_Layer]);
657 Decode_Layer = ALL_LAYERS;
661 /* no output type specified */
665 Output_Picture_Filename = "";
670 if (Output_Type==T_X11)
673 Display_Progressive_Flag = 1;
675 Display_Progressive_Flag = 0;
677 Frame_Store_Flag = 1; /* to avoid calling dither() twice */
687 this is an old routine used to convert command line arguments
690 static int Get_Val(argv)
695 if (sscanf(argv[1]+2,"%d",&val)!=1)
698 while (isdigit(argv[1][2]))
714 /* return when end of sequence (0) or picture
715 header has been parsed (1) */
723 if (Get_Hdr()!=ret && !Quiet_Flag)
724 fprintf(stderr,"streams out of sync\n");
733 static int Decode_Bitstream()
736 int Bitstream_Framenum;
738 Bitstream_Framenum = 0;
744 Clear_Verify_Headers();
751 ret = video_sequence(&Bitstream_Framenum);
760 static void Deinitialize_Sequence()
769 free(backward_reference_frame[i]);
770 free(forward_reference_frame[i]);
773 if (base.scalable_mode==SC_SPAT)
780 if (base.scalable_mode==SC_SPAT)
784 if (Output_Type==T_X11)
785 Terminate_Display_Process();
790 static int video_sequence(Bitstream_Framenumber)
791 int *Bitstream_Framenumber;
793 int Bitstream_Framenum;
794 int Sequence_Framenum;
797 Bitstream_Framenum = *Bitstream_Framenumber;
800 Initialize_Sequence();
802 /* decode picture whose header has already been parsed in
803 Decode_Bitstream() */
806 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
808 /* update picture numbers */
811 Bitstream_Framenum++;
815 /* loop through the rest of the pictures in the sequence */
816 while ((Return_Value=Headers()))
818 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
822 Bitstream_Framenum++;
828 if (Sequence_Framenum!=0)
830 Output_Last_Frame_of_Sequence(Bitstream_Framenum);
833 Deinitialize_Sequence();
836 Clear_Verify_Headers();
839 *Bitstream_Framenumber = Bitstream_Framenum;
840 return(Return_Value);
845 static void Clear_Options()
849 Output_Picture_Filename = " ";
852 Frame_Store_Flag = 0;
854 Lower_Layer_Picture_Filename = " ";
855 Reference_IDCT_Flag = 0;
859 Substitute_Picture_Filename = " ";
861 Enhancement_Layer_Bitstream_Filename = " ";
862 Big_Picture_Flag = 0;
863 Main_Bitstream_Flag = 0;
864 Main_Bitstream_Filename = " ";
872 static void Print_Options()
875 printf("Verbose_Flag = %d\n", Verbose_Flag);
876 printf("Output_Type = %d\n", Output_Type);
877 printf("Output_Picture_Filename = %s\n", Output_Picture_Filename);
878 printf("hiQdither = %d\n", hiQdither);
879 printf("Output_Type = %d\n", Output_Type);
880 printf("Frame_Store_Flag = %d\n", Frame_Store_Flag);
881 printf("Spatial_Flag = %d\n", Spatial_Flag);
882 printf("Lower_Layer_Picture_Filename = %s\n", Lower_Layer_Picture_Filename);
883 printf("Reference_IDCT_Flag = %d\n", Reference_IDCT_Flag);
884 printf("Trace_Flag = %d\n", Trace_Flag);
885 printf("Quiet_Flag = %d\n", Quiet_Flag);
886 printf("Ersatz_Flag = %d\n", Ersatz_Flag);
887 printf("Substitute_Picture_Filename = %s\n", Substitute_Picture_Filename);
888 printf("Two_Streams = %d\n", Two_Streams);
889 printf("Enhancement_Layer_Bitstream_Filename = %s\n", Enhancement_Layer_Bitstream_Filename);
890 printf("Big_Picture_Flag = %d\n", Big_Picture_Flag);
891 printf("Main_Bitstream_Flag = %d\n", Main_Bitstream_Flag);
892 printf("Main_Bitstream_Filename = %s\n", Main_Bitstream_Filename);
893 printf("Verify_Flag = %d\n", Verify_Flag);
894 printf("Stats_Flag = %d\n", Stats_Flag);
895 printf("User_Data_Flag = %d\n", User_Data_Flag);