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, ...)
140 va_start(argptr, format);
141 ret = vprintf(format, argptr);
147 int my_sprintf(char *str, const char *format, ...)
152 va_start(argptr, format);
153 ret = vsprintf(str,format, argptr);
159 int my_fprintf(const char *format, ...)
164 va_start(argptr, format);
165 ret = vfprintf(stderr,format, argptr);
170 void my_exit(int status)
176 #define GDCM_BUILD_MPEG2DEC
178 #ifdef GDCM_BUILD_MPEG2DEC
184 base.open_stream = my_open;
185 base.seek_stream = my_seek;
186 base.read_stream = my_read;
187 base.close_stream = my_close;
191 /* decode command line arguments */
192 Process_Options(argc,argv);
198 ld = &base; /* select base layer context */
200 /* open MPEG base layer bitstream file(s) */
201 /* NOTE: this is either a base layer stream or a spatial enhancement stream */
202 /* if ((base.Infile=open(Main_Bitstream_Filename,O_RDONLY|O_BINARY))<0) */
203 base.Infile = ld->open_stream(Main_Bitstream_Filename);
204 if( base.Infile < 0 )
206 fprintf(stderr,"Base layer input file %s not found\n", Main_Bitstream_Filename);
215 if(Show_Bits(8)==0x47)
217 sprintf(Error_Text,"Decoder currently does not parse transport streams\n");
222 code = Show_Bits(32);
226 case SEQUENCE_HEADER_CODE:
228 case PACK_START_CODE:
229 System_Stream_Flag = 1;
230 case VIDEO_ELEMENTARY_STREAM:
231 System_Stream_Flag = 1;
234 sprintf(Error_Text,"Unable to recognize stream type\n");
239 /*lseek(base.Infile, 0l, SEEK_SET);*/
240 ld->seek_stream(base.Infile,0l,SEEK_SET);
246 /*lseek(base.Infile, 0l, SEEK_SET);*/
247 ld->seek_stream(base.Infile,0l,SEEK_SET);
254 ld = &enhan; /* select enhancement layer context */
256 /*if ((enhan.Infile = open(Enhancement_Layer_Bitstream_Filename,O_RDONLY|O_BINARY))<0)*/
257 enhan.Infile = ld->open_stream(Enhancement_Layer_Bitstream_Filename);
260 sprintf(Error_Text,"enhancment layer bitstream file %s not found\n",
261 Enhancement_Layer_Bitstream_Filename);
270 Initialize_Decoder();
272 ret = Decode_Bitstream();
274 /*close(base.Infile);*/
275 ld->close_stream(base.Infile);
278 /*close(enhan.Infile);*/
279 ld->close_stream(enhan.Infile);
281 DeInitialize_Decoder();
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 static void DeInitialize_Decoder()
311 free(Clip-384); /* I love magic number */
314 /* mostly IMPLEMENTAION specific routines */
315 static void Initialize_Sequence()
318 static int Table_6_20[3] = {6,8,12};
320 /* check scalability mode of enhancement layer */
321 if (Two_Streams && (enhan.scalable_mode!=SC_SNR) && (base.scalable_mode!=SC_DP))
322 Error("unsupported scalability mode\n");
324 /* force MPEG-1 parameters for proper decoder behavior */
325 /* see ISO/IEC 13818-2 section D.9.14 */
326 if (!base.MPEG2_Flag)
328 progressive_sequence = 1;
329 progressive_frame = 1;
330 picture_structure = FRAME_PICTURE;
331 frame_pred_frame_dct = 1;
332 chroma_format = CHROMA420;
333 matrix_coefficients = 5;
336 /* round to nearest multiple of coded macroblocks */
337 /* ISO/IEC 13818-2 section 6.3.3 sequence_header() */
338 mb_width = (horizontal_size+15)/16;
339 mb_height = (base.MPEG2_Flag && !progressive_sequence) ? 2*((vertical_size+31)/32)
340 : (vertical_size+15)/16;
342 Coded_Picture_Width = 16*mb_width;
343 Coded_Picture_Height = 16*mb_height;
345 /* ISO/IEC 13818-2 sections 6.1.1.8, 6.1.1.9, and 6.1.1.10 */
346 Chroma_Width = (chroma_format==CHROMA444) ? Coded_Picture_Width
347 : Coded_Picture_Width>>1;
348 Chroma_Height = (chroma_format!=CHROMA420) ? Coded_Picture_Height
349 : Coded_Picture_Height>>1;
351 /* derived based on Table 6-20 in ISO/IEC 13818-2 section 6.3.17 */
352 block_count = Table_6_20[chroma_format-1];
354 for (cc=0; cc<3; cc++)
357 size = Coded_Picture_Width*Coded_Picture_Height;
359 size = Chroma_Width*Chroma_Height;
361 if (!(backward_reference_frame[cc] = (unsigned char *)malloc(size)))
362 Error("backward_reference_frame[] malloc failed\n");
364 if (!(forward_reference_frame[cc] = (unsigned char *)malloc(size)))
365 Error("forward_reference_frame[] malloc failed\n");
367 if (!(auxframe[cc] = (unsigned char *)malloc(size)))
368 Error("auxframe[] malloc failed\n");
371 if (!(substitute_frame[cc] = (unsigned char *)malloc(size)))
372 Error("substitute_frame[] malloc failed\n");
375 if (base.scalable_mode==SC_SPAT)
377 /* this assumes lower layer is 4:2:0 */
378 if (!(llframe0[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
379 Error("llframe0 malloc failed\n");
380 if (!(llframe1[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
381 Error("llframe1 malloc failed\n");
385 /* SCALABILITY: Spatial */
386 if (base.scalable_mode==SC_SPAT)
388 if (!(lltmp = (short *)malloc(lower_layer_prediction_horizontal_size*((lower_layer_prediction_vertical_size*vertical_subsampling_factor_n)/vertical_subsampling_factor_m)*sizeof(short))))
389 Error("lltmp malloc failed\n");
393 if (Output_Type==T_X11)
395 Initialize_Display_Process("");
396 Initialize_Dither_Matrix();
405 fprintf(stderr,text);
409 /* Trace_Flag output */
410 void Print_Bits(code,bits,len)
414 for (i=0; i<len; i++)
415 printf("%d",(code>>(bits-1-i))&1);
420 /* option processing */
421 static void Process_Options(argc,argv)
422 int argc; /* argument count */
423 char *argv[]; /* argument vector */
425 int i, LastArg, NextArg;
427 /* at least one argument should be present */
430 printf("\n%s, %s\n",Version,Author);
431 printf("Usage: mpeg2decode {options}\n"
432 "Options: -b file main bitstream (base or spatial enhancement layer)\n"
433 " -cn file conformance report (n: level)\n"
434 " -e file enhancement layer bitstream (SNR or Data Partitioning)\n"
435 " -f store/display interlaced video in frame format\n"
436 " -g concatenated file format for substitution method (-x)\n"
437 " -in file information & statistics report (n: level)\n"
438 " -l file file name pattern for lower layer sequence\n");
439 printf(" (for spatial scalability)\n"
440 " -on file output format (0:YUV 1:SIF 2:TGA 3:PPM 4:X11 5:X11HiQ)\n"
441 " -q disable warnings to stderr\n"
442 " -r use double precision reference IDCT\n"
443 " -t enable low level tracing to stdout\n"
444 " -u file print user_data to stdio or file\n"
445 " -vn verbose output (n: level)\n"
446 " -x file filename pattern of picture substitution sequence\n\n");
447 printf("File patterns: for sequential filenames, \"printf\" style, e.g. rec%%d\n"
448 " or rec%%d%%c for fieldwise storage\n"
449 "Levels: 0:none 1:sequence 2:picture 3:slice 4:macroblock 5:block\n\n"
450 "Example: mpeg2decode -b bitstream.mpg -f -r -o0 rec%%d\n"
459 /* command-line options are proceeded by '-' */
463 /* check if this is the last argument */
464 LastArg = ((argc-i)==1);
466 /* parse ahead to see if another flag immediately follows current
467 argument (this is used to tell if a filename is missing) */
469 NextArg = (argv[i+1][0]=='-');
473 /* second character, [1], after '-' is the switch */
476 switch(toupper(argv[i][1]))
478 /* third character. [2], is the value */
480 Main_Bitstream_Flag = 1;
482 if(NextArg || LastArg)
484 printf("ERROR: -b must be followed the main bitstream filename\n");
487 Main_Bitstream_Filename = argv[++i];
495 Verify_Flag = atoi(&argv[i][2]);
497 if((Verify_Flag < NO_LAYER) || (Verify_Flag > ALL_LAYERS))
499 printf("ERROR: -c level (%d) out of range [%d,%d]\n",
500 Verify_Flag, NO_LAYER, ALL_LAYERS);
504 printf("This program not compiled for Verify_Flag option\n");
509 Two_Streams = 1; /* either Data Partitioning (DP) or SNR Scalability enhancment */
511 if(NextArg || LastArg)
513 printf("ERROR: -e must be followed by filename\n");
517 Enhancement_Layer_Bitstream_Filename = argv[++i];
523 Frame_Store_Flag = 1;
527 Big_Picture_Flag = 1;
533 Stats_Flag = atoi(&argv[i][2]);
535 printf("WARNING: This program not compiled for -i option\n");
539 case 'L': /* spatial scalability flag */
542 if(NextArg || LastArg)
544 printf("ERROR: -l must be followed by filename\n");
548 Lower_Layer_Picture_Filename = argv[++i];
554 Output_Type = atoi(&argv[i][2]);
556 if((Output_Type==4) || (Output_Type==5))
557 Output_Picture_Filename = ""; /* no need of filename */
558 else if(NextArg || LastArg)
560 printf("ERROR: -o must be followed by filename\n");
564 /* filename is separated by space, so it becomes the next argument */
565 Output_Picture_Filename = argv[++i];
568 if (Output_Type==T_X11HIQ)
581 Reference_IDCT_Flag = 1;
588 printf("WARNING: This program not compiled for -t option\n");
597 Verbose_Flag = atoi(&argv[i][2]);
599 printf("This program not compiled for -v option\n");
607 if(NextArg || LastArg)
609 printf("ERROR: -x must be followed by filename\n");
613 Substitute_Picture_Filename = argv[++i];
620 fprintf(stderr,"undefined option -%c ignored. Exiting program\n",
626 } /* if argv[i][0] == '-' */
630 /* check for bitstream filename argument (there must always be one, at the very end
631 of the command line arguments */
636 /* options sense checking */
638 if(Main_Bitstream_Flag!=1)
640 printf("There must be a main bitstream specified (-b filename)\n");
643 /* force display process to show frame pictures */
644 if((Output_Type==4 || Output_Type==5) && Frame_Store_Flag)
645 Display_Progressive_Flag = 1;
647 Display_Progressive_Flag = 0;
650 /* parse the bitstream, do not actually decode it completely */
656 Decode_Layer = Verify_Flag;
657 printf("FYI: Decoding bitstream elements up to: %s\n",
658 Layer_Table[Decode_Layer]);
662 Decode_Layer = ALL_LAYERS;
666 /* no output type specified */
670 Output_Picture_Filename = "";
675 if (Output_Type==T_X11)
678 Display_Progressive_Flag = 1;
680 Display_Progressive_Flag = 0;
682 Frame_Store_Flag = 1; /* to avoid calling dither() twice */
692 this is an old routine used to convert command line arguments
695 static int Get_Val(argv)
700 if (sscanf(argv[1]+2,"%d",&val)!=1)
703 while (isdigit(argv[1][2]))
719 /* return when end of sequence (0) or picture
720 header has been parsed (1) */
728 if (Get_Hdr()!=ret && !Quiet_Flag)
729 fprintf(stderr,"streams out of sync\n");
738 static int Decode_Bitstream()
741 int Bitstream_Framenum;
743 Bitstream_Framenum = 0;
749 Clear_Verify_Headers();
756 ret = video_sequence(&Bitstream_Framenum);
765 static void Deinitialize_Sequence()
769 /* First cleanup the static buffer in store.c */
777 free(backward_reference_frame[i]);
778 free(forward_reference_frame[i]);
781 if (base.scalable_mode==SC_SPAT)
788 if (base.scalable_mode==SC_SPAT)
792 if (Output_Type==T_X11)
793 Terminate_Display_Process();
798 static int video_sequence(Bitstream_Framenumber)
799 int *Bitstream_Framenumber;
801 int Bitstream_Framenum;
802 int Sequence_Framenum;
805 Bitstream_Framenum = *Bitstream_Framenumber;
808 Initialize_Sequence();
810 /* decode picture whose header has already been parsed in
811 Decode_Bitstream() */
814 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
816 /* update picture numbers */
819 Bitstream_Framenum++;
823 /* loop through the rest of the pictures in the sequence */
824 while ((Return_Value=Headers()))
826 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
830 Bitstream_Framenum++;
836 if (Sequence_Framenum!=0)
838 Output_Last_Frame_of_Sequence(Bitstream_Framenum);
841 Deinitialize_Sequence();
844 Clear_Verify_Headers();
847 *Bitstream_Framenumber = Bitstream_Framenum;
848 return(Return_Value);
853 static void Clear_Options()
857 Output_Picture_Filename = " ";
860 Frame_Store_Flag = 0;
862 Lower_Layer_Picture_Filename = " ";
863 Reference_IDCT_Flag = 0;
867 Substitute_Picture_Filename = " ";
869 Enhancement_Layer_Bitstream_Filename = " ";
870 Big_Picture_Flag = 0;
871 Main_Bitstream_Flag = 0;
872 Main_Bitstream_Filename = " ";
880 static void Print_Options()
883 printf("Verbose_Flag = %d\n", Verbose_Flag);
884 printf("Output_Type = %d\n", Output_Type);
885 printf("Output_Picture_Filename = %s\n", Output_Picture_Filename);
886 printf("hiQdither = %d\n", hiQdither);
887 printf("Output_Type = %d\n", Output_Type);
888 printf("Frame_Store_Flag = %d\n", Frame_Store_Flag);
889 printf("Spatial_Flag = %d\n", Spatial_Flag);
890 printf("Lower_Layer_Picture_Filename = %s\n", Lower_Layer_Picture_Filename);
891 printf("Reference_IDCT_Flag = %d\n", Reference_IDCT_Flag);
892 printf("Trace_Flag = %d\n", Trace_Flag);
893 printf("Quiet_Flag = %d\n", Quiet_Flag);
894 printf("Ersatz_Flag = %d\n", Ersatz_Flag);
895 printf("Substitute_Picture_Filename = %s\n", Substitute_Picture_Filename);
896 printf("Two_Streams = %d\n", Two_Streams);
897 printf("Enhancement_Layer_Bitstream_Filename = %s\n", Enhancement_Layer_Bitstream_Filename);
898 printf("Big_Picture_Flag = %d\n", Big_Picture_Flag);
899 printf("Main_Bitstream_Flag = %d\n", Main_Bitstream_Flag);
900 printf("Main_Bitstream_Filename = %s\n", Main_Bitstream_Filename);
901 printf("Verify_Flag = %d\n", Verify_Flag);
902 printf("Stats_Flag = %d\n", Stats_Flag);
903 printf("User_Data_Flag = %d\n", User_Data_Flag);