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)
65 return open(filename,O_RDONLY|O_BINARY);
68 off_t my_seek(istream *infile, off_t offset, int whence)
71 return fseek(infile->InFd,offset, whence);
73 return lseek(infile->InFd,offset, whence);
76 ssize_t my_read(istream *infile, void *buf, size_t count)
79 return fread(buf,1,count, infile->InFd);
81 return read(infile->InFd,buf,count);
85 int my_close(istream *infile)
88 return fclose(infile->InFd);
90 return close(infile->InFd);
94 int my_fopenr(const char *path, const char *mode, istream *os)
96 FILE *fd = fopen(path, mode);
100 return 1; /*success*/
107 int my_fopen(const char *path, const char *mode, ostream *os)
109 FILE *fd = fopen(path, mode);
113 return 1; /*success*/
120 int my_fseek(ostream *stream, long offset, int whence)
122 return fseek(stream->OutFd, offset, whence);
124 int my_fseekr(istream *stream, long offset, int whence)
126 return fseek(stream->InFd, offset, whence);
129 size_t my_fread(void *ptr, size_t size, size_t nmemb, istream *stream)
131 return fread(ptr, size, nmemb, stream->InFd);
134 size_t my_fwrite(const void *ptr, size_t size, size_t nmemb, ostream *stream)
136 return fwrite(ptr, size, nmemb, stream->OutFd);
139 int my_fcloser(istream *fp)
141 return fclose(fp->InFd);
143 int my_fclose(ostream *fp)
145 return fclose(fp->OutFd);
149 int my_printf(const char *format, ...)
154 va_start(argptr, format);
155 ret = vprintf(format, argptr);
161 int my_sprintf(char *str, const char *format, ...)
166 va_start(argptr, format);
167 ret = vsprintf(str,format, argptr);
173 int my_fprintf(const char *format, ...)
178 va_start(argptr, format);
179 ret = vfprintf(stderr,format, argptr);
184 void my_exit(int status)
190 #define GDCM_BUILD_MPEG2DEC
192 #ifdef GDCM_BUILD_MPEG2DEC
199 /*base.open_stream = my_open;*/
200 base.seek_stream = my_seek;
201 base.read_stream = my_read;
202 base.close_stream = my_close;
206 /* decode command line arguments */
207 Process_Options(argc,argv);
213 ld = &base; /* select base layer context */
215 /* open MPEG base layer bitstream file(s) */
216 /* NOTE: this is either a base layer stream or a spatial enhancement stream */
217 /* if ((base.Infile=open(Main_Bitstream_Filename,O_RDONLY|O_BINARY))<0) */
218 /*base.Infile = ld->open_stream(Main_Bitstream_Filename);*/
221 base.Infile->InFd = fopen(Main_Bitstream_Filename, "rb");
223 base.Infile->InFd = open(Main_Bitstream_Filename,O_RDONLY|O_BINARY );
225 if( !base.Infile->InFd)
227 fprintf(stderr,"Base layer input file %s not found\n", Main_Bitstream_Filename);
236 if(Show_Bits(8)==0x47)
238 sprintf(Error_Text,"Decoder currently does not parse transport streams\n");
243 code = Show_Bits(32);
247 case SEQUENCE_HEADER_CODE:
249 case PACK_START_CODE:
250 System_Stream_Flag = 1;
251 case VIDEO_ELEMENTARY_STREAM:
252 System_Stream_Flag = 1;
255 sprintf(Error_Text,"Unable to recognize stream type\n");
260 /*lseek(base.Infile, 0l, SEEK_SET);*/
261 ld->seek_stream(base.Infile,0l,SEEK_SET);
267 /*lseek(base.Infile, 0l, SEEK_SET);*/
268 ld->seek_stream(base.Infile,0l,SEEK_SET);
275 ld = &enhan; /* select enhancement layer context */
277 /*if ((enhan.Infile = open(Enhancement_Layer_Bitstream_Filename,O_RDONLY|O_BINARY))<0)*/
278 /*enhan.Infile = ld->open_stream(Enhancement_Layer_Bitstream_Filename);*/
281 enhan.Infile->InFd = fopen(Main_Bitstream_Filename, "rb");
283 enhan.Infile->InFd = open(Enhancement_Layer_Bitstream_Filename,O_RDONLY|O_BINARY);
285 if (enhan.Infile->InFd)
287 sprintf(Error_Text,"enhancment layer bitstream file %s not found\n",
288 Enhancement_Layer_Bitstream_Filename);
297 Initialize_Decoder();
299 ret = Decode_Bitstream();
301 /*close(base.Infile);*/
302 ld->close_stream(base.Infile);
305 /*close(enhan.Infile);*/
306 ld->close_stream(enhan.Infile);
308 DeInitialize_Decoder();
312 #endif /*GDCM_BUILD_MPEG2DEC*/
314 /* IMPLEMENTATION specific routines */
315 static void Initialize_Decoder()
320 if (!(Clip=(unsigned char *)malloc(1024)))
321 Error("Clip[] malloc failed\n");
325 for (i=-384; i<640; i++)
326 Clip[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
329 if (Reference_IDCT_Flag)
330 Initialize_Reference_IDCT();
332 Initialize_Fast_IDCT();
336 static void DeInitialize_Decoder()
338 free(Clip-384); /* I love magic number */
341 /* mostly IMPLEMENTAION specific routines */
342 static void Initialize_Sequence()
345 static int Table_6_20[3] = {6,8,12};
347 /* check scalability mode of enhancement layer */
348 if (Two_Streams && (enhan.scalable_mode!=SC_SNR) && (base.scalable_mode!=SC_DP))
349 Error("unsupported scalability mode\n");
351 /* force MPEG-1 parameters for proper decoder behavior */
352 /* see ISO/IEC 13818-2 section D.9.14 */
353 if (!base.MPEG2_Flag)
355 progressive_sequence = 1;
356 progressive_frame = 1;
357 picture_structure = FRAME_PICTURE;
358 frame_pred_frame_dct = 1;
359 chroma_format = CHROMA420;
360 matrix_coefficients = 5;
363 /* round to nearest multiple of coded macroblocks */
364 /* ISO/IEC 13818-2 section 6.3.3 sequence_header() */
365 mb_width = (horizontal_size+15)/16;
366 mb_height = (base.MPEG2_Flag && !progressive_sequence) ? 2*((vertical_size+31)/32)
367 : (vertical_size+15)/16;
369 Coded_Picture_Width = 16*mb_width;
370 Coded_Picture_Height = 16*mb_height;
372 /* ISO/IEC 13818-2 sections 6.1.1.8, 6.1.1.9, and 6.1.1.10 */
373 Chroma_Width = (chroma_format==CHROMA444) ? Coded_Picture_Width
374 : Coded_Picture_Width>>1;
375 Chroma_Height = (chroma_format!=CHROMA420) ? Coded_Picture_Height
376 : Coded_Picture_Height>>1;
378 /* derived based on Table 6-20 in ISO/IEC 13818-2 section 6.3.17 */
379 block_count = Table_6_20[chroma_format-1];
381 for (cc=0; cc<3; cc++)
384 size = Coded_Picture_Width*Coded_Picture_Height;
386 size = Chroma_Width*Chroma_Height;
388 if (!(backward_reference_frame[cc] = (unsigned char *)malloc(size)))
389 Error("backward_reference_frame[] malloc failed\n");
391 if (!(forward_reference_frame[cc] = (unsigned char *)malloc(size)))
392 Error("forward_reference_frame[] malloc failed\n");
394 if (!(auxframe[cc] = (unsigned char *)malloc(size)))
395 Error("auxframe[] malloc failed\n");
398 if (!(substitute_frame[cc] = (unsigned char *)malloc(size)))
399 Error("substitute_frame[] malloc failed\n");
402 if (base.scalable_mode==SC_SPAT)
404 /* this assumes lower layer is 4:2:0 */
405 if (!(llframe0[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
406 Error("llframe0 malloc failed\n");
407 if (!(llframe1[cc] = (unsigned char *)malloc((lower_layer_prediction_horizontal_size*lower_layer_prediction_vertical_size)/(cc?4:1))))
408 Error("llframe1 malloc failed\n");
412 /* SCALABILITY: Spatial */
413 if (base.scalable_mode==SC_SPAT)
415 if (!(lltmp = (short *)malloc(lower_layer_prediction_horizontal_size*((lower_layer_prediction_vertical_size*vertical_subsampling_factor_n)/vertical_subsampling_factor_m)*sizeof(short))))
416 Error("lltmp malloc failed\n");
420 if (Output_Type==T_X11)
422 Initialize_Display_Process("");
423 Initialize_Dither_Matrix();
432 fprintf(stderr,text);
436 /* Trace_Flag output */
437 void Print_Bits(code,bits,len)
441 for (i=0; i<len; i++)
442 printf("%d",(code>>(bits-1-i))&1);
447 /* option processing */
448 static void Process_Options(argc,argv)
449 int argc; /* argument count */
450 char *argv[]; /* argument vector */
452 int i, LastArg, NextArg;
454 /* at least one argument should be present */
457 printf("\n%s, %s\n",Version,Author);
458 printf("Usage: mpeg2decode {options}\n"
459 "Options: -b file main bitstream (base or spatial enhancement layer)\n"
460 " -cn file conformance report (n: level)\n"
461 " -e file enhancement layer bitstream (SNR or Data Partitioning)\n"
462 " -f store/display interlaced video in frame format\n"
463 " -g concatenated file format for substitution method (-x)\n"
464 " -in file information & statistics report (n: level)\n"
465 " -l file file name pattern for lower layer sequence\n");
466 printf(" (for spatial scalability)\n"
467 " -on file output format (0:YUV 1:SIF 2:TGA 3:PPM 4:X11 5:X11HiQ)\n"
468 " -q disable warnings to stderr\n"
469 " -r use double precision reference IDCT\n"
470 " -t enable low level tracing to stdout\n"
471 " -u file print user_data to stdio or file\n"
472 " -vn verbose output (n: level)\n"
473 " -x file filename pattern of picture substitution sequence\n\n");
474 printf("File patterns: for sequential filenames, \"printf\" style, e.g. rec%%d\n"
475 " or rec%%d%%c for fieldwise storage\n"
476 "Levels: 0:none 1:sequence 2:picture 3:slice 4:macroblock 5:block\n\n"
477 "Example: mpeg2decode -b bitstream.mpg -f -r -o0 rec%%d\n"
486 /* command-line options are proceeded by '-' */
490 /* check if this is the last argument */
491 LastArg = ((argc-i)==1);
493 /* parse ahead to see if another flag immediately follows current
494 argument (this is used to tell if a filename is missing) */
496 NextArg = (argv[i+1][0]=='-');
500 /* second character, [1], after '-' is the switch */
503 switch(toupper(argv[i][1]))
505 /* third character. [2], is the value */
507 Main_Bitstream_Flag = 1;
509 if(NextArg || LastArg)
511 printf("ERROR: -b must be followed the main bitstream filename\n");
514 Main_Bitstream_Filename = argv[++i];
522 Verify_Flag = atoi(&argv[i][2]);
524 if((Verify_Flag < NO_LAYER) || (Verify_Flag > ALL_LAYERS))
526 printf("ERROR: -c level (%d) out of range [%d,%d]\n",
527 Verify_Flag, NO_LAYER, ALL_LAYERS);
531 printf("This program not compiled for Verify_Flag option\n");
536 Two_Streams = 1; /* either Data Partitioning (DP) or SNR Scalability enhancment */
538 if(NextArg || LastArg)
540 printf("ERROR: -e must be followed by filename\n");
544 Enhancement_Layer_Bitstream_Filename = argv[++i];
550 Frame_Store_Flag = 1;
554 Big_Picture_Flag = 1;
560 Stats_Flag = atoi(&argv[i][2]);
562 printf("WARNING: This program not compiled for -i option\n");
566 case 'L': /* spatial scalability flag */
569 if(NextArg || LastArg)
571 printf("ERROR: -l must be followed by filename\n");
575 Lower_Layer_Picture_Filename = argv[++i];
581 Output_Type = atoi(&argv[i][2]);
583 if((Output_Type==4) || (Output_Type==5))
584 Output_Picture_Filename = ""; /* no need of filename */
585 else if(NextArg || LastArg)
587 printf("ERROR: -o must be followed by filename\n");
591 /* filename is separated by space, so it becomes the next argument */
592 Output_Picture_Filename = argv[++i];
595 if (Output_Type==T_X11HIQ)
608 Reference_IDCT_Flag = 1;
615 printf("WARNING: This program not compiled for -t option\n");
624 Verbose_Flag = atoi(&argv[i][2]);
626 printf("This program not compiled for -v option\n");
634 if(NextArg || LastArg)
636 printf("ERROR: -x must be followed by filename\n");
640 Substitute_Picture_Filename = argv[++i];
647 fprintf(stderr,"undefined option -%c ignored. Exiting program\n",
653 } /* if argv[i][0] == '-' */
657 /* check for bitstream filename argument (there must always be one, at the very end
658 of the command line arguments */
663 /* options sense checking */
665 if(Main_Bitstream_Flag!=1)
667 printf("There must be a main bitstream specified (-b filename)\n");
670 /* force display process to show frame pictures */
671 if((Output_Type==4 || Output_Type==5) && Frame_Store_Flag)
672 Display_Progressive_Flag = 1;
674 Display_Progressive_Flag = 0;
677 /* parse the bitstream, do not actually decode it completely */
683 Decode_Layer = Verify_Flag;
684 printf("FYI: Decoding bitstream elements up to: %s\n",
685 Layer_Table[Decode_Layer]);
689 Decode_Layer = ALL_LAYERS;
693 /* no output type specified */
697 Output_Picture_Filename = "";
702 if (Output_Type==T_X11)
705 Display_Progressive_Flag = 1;
707 Display_Progressive_Flag = 0;
709 Frame_Store_Flag = 1; /* to avoid calling dither() twice */
719 this is an old routine used to convert command line arguments
722 static int Get_Val(argv)
727 if (sscanf(argv[1]+2,"%d",&val)!=1)
730 while (isdigit(argv[1][2]))
746 /* return when end of sequence (0) or picture
747 header has been parsed (1) */
755 if (Get_Hdr()!=ret && !Quiet_Flag)
756 fprintf(stderr,"streams out of sync\n");
765 static int Decode_Bitstream()
768 int Bitstream_Framenum;
770 Bitstream_Framenum = 0;
776 Clear_Verify_Headers();
783 ret = video_sequence(&Bitstream_Framenum);
792 static void Deinitialize_Sequence()
796 /* First cleanup the static buffer in store.c */
804 free(backward_reference_frame[i]);
805 free(forward_reference_frame[i]);
808 if (base.scalable_mode==SC_SPAT)
815 if (base.scalable_mode==SC_SPAT)
819 if (Output_Type==T_X11)
820 Terminate_Display_Process();
825 static int video_sequence(Bitstream_Framenumber)
826 int *Bitstream_Framenumber;
828 int Bitstream_Framenum;
829 int Sequence_Framenum;
832 Bitstream_Framenum = *Bitstream_Framenumber;
835 Initialize_Sequence();
837 /* decode picture whose header has already been parsed in
838 Decode_Bitstream() */
841 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
843 /* update picture numbers */
846 Bitstream_Framenum++;
850 /* loop through the rest of the pictures in the sequence */
851 while ((Return_Value=Headers()))
853 Decode_Picture(Bitstream_Framenum, Sequence_Framenum);
857 Bitstream_Framenum++;
863 if (Sequence_Framenum!=0)
865 Output_Last_Frame_of_Sequence(Bitstream_Framenum);
868 Deinitialize_Sequence();
871 Clear_Verify_Headers();
874 *Bitstream_Framenumber = Bitstream_Framenum;
875 return(Return_Value);
880 static void Clear_Options()
884 Output_Picture_Filename = " ";
887 Frame_Store_Flag = 0;
889 Lower_Layer_Picture_Filename = " ";
890 Reference_IDCT_Flag = 0;
894 Substitute_Picture_Filename = " ";
896 Enhancement_Layer_Bitstream_Filename = " ";
897 Big_Picture_Flag = 0;
898 Main_Bitstream_Flag = 0;
899 Main_Bitstream_Filename = " ";
907 static void Print_Options()
910 printf("Verbose_Flag = %d\n", Verbose_Flag);
911 printf("Output_Type = %d\n", Output_Type);
912 printf("Output_Picture_Filename = %s\n", Output_Picture_Filename);
913 printf("hiQdither = %d\n", hiQdither);
914 printf("Output_Type = %d\n", Output_Type);
915 printf("Frame_Store_Flag = %d\n", Frame_Store_Flag);
916 printf("Spatial_Flag = %d\n", Spatial_Flag);
917 printf("Lower_Layer_Picture_Filename = %s\n", Lower_Layer_Picture_Filename);
918 printf("Reference_IDCT_Flag = %d\n", Reference_IDCT_Flag);
919 printf("Trace_Flag = %d\n", Trace_Flag);
920 printf("Quiet_Flag = %d\n", Quiet_Flag);
921 printf("Ersatz_Flag = %d\n", Ersatz_Flag);
922 printf("Substitute_Picture_Filename = %s\n", Substitute_Picture_Filename);
923 printf("Two_Streams = %d\n", Two_Streams);
924 printf("Enhancement_Layer_Bitstream_Filename = %s\n", Enhancement_Layer_Bitstream_Filename);
925 printf("Big_Picture_Flag = %d\n", Big_Picture_Flag);
926 printf("Main_Bitstream_Flag = %d\n", Main_Bitstream_Flag);
927 printf("Main_Bitstream_Filename = %s\n", Main_Bitstream_Filename);
928 printf("Verify_Flag = %d\n", Verify_Flag);
929 printf("Stats_Flag = %d\n", Stats_Flag);
930 printf("User_Data_Flag = %d\n", User_Data_Flag);