fixed for v4l2 captures, add colormodel uyuv
[goodguy/history.git] / cinelerra-5.0 / mpeg2enc / mpeg2enc.c
1 /* mpeg2enc.c, main() and parameter file reading                            */
2
3 /* Copyright (C) 1996, MPEG Software Simulation Group. All Rights Reserved. */
4
5 /*
6  * Disclaimer of Warranty
7  *
8  * These software programs are available to the user without any license fee or
9  * royalty on an "as is" basis.  The MPEG Software Simulation Group disclaims
10  * any and all warranties, whether express, implied, or statuary, including any
11  * implied warranties or merchantability or of fitness for a particular
12  * purpose.  In no event shall the copyright-holder be liable for any
13  * incidental, punitive, or consequential damages of any kind whatsoever
14  * arising from the use of these programs.
15  *
16  * This disclaimer of warranty extends to the user of these programs and user's
17  * customers, employees, agents, transferees, successors, and assigns.
18  *
19  * The MPEG Software Simulation Group does not represent or warrant that the
20  * programs furnished hereunder are free of infringement of any third-party
21  * patents.
22  *
23  * Commercial implementations of MPEG-1 and MPEG-2 video, including shareware,
24  * are subject to royalty fees to patent holders.  Many of these patents are
25  * general enough such that they are unavoidable regardless of implementation
26  * design.
27  *
28  */
29
30 #define MAX(a,b) ( (a)>(b) ? (a) : (b) )
31 #include <math.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35
36 #define GLOBAL_ /* used by global.h */
37 #include "config.h"
38 #include "global.h"
39
40 /* private prototypes */
41 static void init _ANSI_ARGS_((void));
42 static void readcmdline _ANSI_ARGS_((int argc, char *argv[]));
43 static void readquantmat _ANSI_ARGS_((void));
44
45
46 // Hack for libdv to remove glib dependancy
47
48 void
49 g_log (const char    *log_domain,
50        int  log_level,
51        const char    *format,
52        ...)
53 {
54 }
55
56 void
57 g_logv (const char    *log_domain,
58        int  log_level,
59        const char    *format,
60        ...)
61 {
62 }
63
64
65 void mpeg2enc_set_w(int width)
66 {
67         horizontal_size = width;
68 }
69
70 void mpeg2enc_set_h(int height)
71 {
72         vertical_size = height;
73 }
74
75 void mpeg2enc_set_rate(double rate)
76 {
77         input_frame_rate = rate;
78 }
79
80 void mpeg2enc_set_input_buffers(int eof, char *y, char *u, char *v)
81 {
82         pthread_mutex_lock(&output_lock);
83         input_buffer_end = eof;
84         input_buffer_y = y;
85         input_buffer_u = u;
86         input_buffer_v = v;
87         pthread_mutex_unlock(&input_lock);
88 // Wait for buffers to get copied before returning.
89         pthread_mutex_lock(&copy_lock);
90 }
91
92 void mpeg2enc_init_buffers()
93 {
94         pthread_mutex_init(&input_lock, 0);
95         pthread_mutex_init(&output_lock, 0);
96         pthread_mutex_init(&copy_lock, 0);
97         pthread_mutex_lock(&input_lock);
98         pthread_mutex_lock(&copy_lock);
99         input_buffer_end = 0;
100 }
101
102 int mpeg2enc(int argc, char *argv[])
103 {
104         stdin_fd = stdin;
105         
106         verbose = 1;
107
108
109 /* Read command line */
110         readcmdline(argc, argv);
111
112 /* read quantization matrices */
113         readquantmat();
114
115         if(!strlen(out_path))
116         {
117                 fprintf(stderr, "No output file given.\n");
118         }
119
120 /* open output file */
121         if(!(outfile = fopen(out_path, "wb")))
122         {
123       sprintf(errortext,"Couldn't create output file %s", out_path);
124       error(errortext);
125         }
126
127         init();
128
129         if(nframes < 0x7fffffff)
130                 printf("Frame    Completion    Current bitrate     Predicted file size\n");
131         putseq();
132
133         stop_slice_engines();
134         stop_motion_engines();
135         stop_transform_engines();
136         stop_itransform_engines();
137
138         fclose(outfile);
139         fclose(statfile);
140
141         if(qt_file) quicktime_close(qt_file);
142         if(qt_output) quicktime_close(qt_output);
143         if(mpeg_file) mpeg3_close(mpeg_file);
144
145         if(do_stdin)
146         {
147                 fclose(stdin_fd);
148         }
149         pthread_mutex_destroy(&input_lock);
150         pthread_mutex_destroy(&output_lock);
151         return 0;
152 }
153
154 int HorzMotionCode(int i)
155 {
156         if (i < 8)
157       return 1;
158         if (i < 16)
159       return 2;
160         if (i < 32)
161       return 3;
162         if ((i < 64) || (constrparms))
163       return 4;
164         if (i < 128)
165       return 5;
166         if (i < 256)
167       return 6;
168         if ((i < 512) || (level == 10))
169       return 7;
170         if ((i < 1024) || (level == 8))
171       return 8;
172         if (i < 2048)
173       return 9;
174         return 1;
175 }
176
177 int VertMotionCode(int i)
178 {
179         if (i < 8)
180       return 1;
181         if (i < 16)
182       return 2;
183         if (i < 32)
184       return 3;
185         if ((i < 64) || (level == 10) || (constrparms))
186       return 4;
187         return 5;
188 }
189
190 /*
191         Wrapper for malloc that allocates pbuffers aligned to the 
192         specified byte boundary and checks for failure.
193         N.b.  don't try to free the resulting pointers, eh...
194         BUG:    Of course this won't work if a char * won't fit in an int....
195 */
196 static uint8_t *bufalloc( size_t size )
197 {
198         char *buf = malloc( size + BUFFER_ALIGN );
199         int adjust;
200
201         if( buf == NULL )
202         {
203                 error("malloc failed\n");
204         }
205         adjust = ((unsigned long)buf) & (BUFFER_ALIGN-1);
206         if( adjust ) adjust = BUFFER_ALIGN - adjust;
207         memset(buf += adjust, 0, size);
208         return (uint8_t*)buf;
209 }
210
211 static void init()
212 {
213         int i, n, size;
214         static int block_count_tab[3] = {6,8,12};
215         int lum_buffer_size, chrom_buffer_size;
216         pthread_mutexattr_t mutex_attr;
217         pthread_mutexattr_init(&mutex_attr);
218         pthread_mutex_init(&test_lock, &mutex_attr);
219
220         bzero(&cur_picture, sizeof(pict_data_s));
221         mpeg2_initbits();
222         init_fdct();
223         init_idct();
224         init_motion();
225         init_predict_hv();
226         init_quantizer_hv();
227         init_transform_hv();
228
229 /* round picture dimensions to nZearest multiple of 16 or 32 */
230         mb_width = (horizontal_size+15)/16;
231         mb_height = prog_seq ? 
232                 (vertical_size + 15) / 16 : 
233                 2 * ((vertical_size + 31) / 32);
234         mb_height2 = fieldpic ? 
235                 mb_height >> 1 : 
236                 mb_height; /* for field pictures */
237         width = 16 * mb_width;
238         height = 16 * mb_height;
239
240         chrom_width = (chroma_format==CHROMA444) ? width : width>>1;
241         chrom_height = (chroma_format!=CHROMA420) ? height : height>>1;
242
243         height2 = fieldpic ? height>>1 : height;
244         width2 = fieldpic ? width<<1 : width;
245         chrom_width2 = fieldpic ? chrom_width<<1 : chrom_width;
246
247         block_count = block_count_tab[chroma_format-1];
248         lum_buffer_size = (width*height) + 
249                                          sizeof(uint8_t) *(width/2)*(height/2) +
250                                          sizeof(uint8_t) *(width/4)*(height/4+1);
251         chrom_buffer_size = chrom_width*chrom_height;
252
253         fsubsample_offset = (width)*(height) * sizeof(uint8_t);
254         qsubsample_offset =  fsubsample_offset + (width/2)*(height/2)*sizeof(uint8_t);
255
256         rowsums_offset = 0;
257         colsums_offset = 0;
258
259         mb_per_pict = mb_width*mb_height2;
260
261 /* clip table */
262         if (!(clp = (unsigned char *)malloc(1024)))
263       error("malloc failed\n");
264         clp+= 384;
265         for (i=-384; i<640; i++)
266       clp[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
267
268
269         
270         /* Allocate the frame buffer */
271
272
273         frame_buffers = (uint8_t ***) 
274                 bufalloc(2*READ_LOOK_AHEAD*sizeof(uint8_t**));
275         
276         for(n=0;n<2*READ_LOOK_AHEAD;n++)
277         {
278          frame_buffers[n] = (uint8_t **) bufalloc(3*sizeof(uint8_t*));
279                  for (i=0; i<3; i++)
280                  {
281                          frame_buffers[n][i] = 
282                                  bufalloc( (i==0) ? lum_buffer_size : chrom_buffer_size );
283                  }
284         }
285
286
287
288         /* TODO: The ref and aux frame buffers are no redundant! */
289         for( i = 0 ; i<3; i++)
290         {
291                 int size =  (i==0) ? lum_buffer_size : chrom_buffer_size;
292                 newrefframe[i] = bufalloc(size);
293                 oldrefframe[i] = bufalloc(size);
294                 auxframe[i]    = bufalloc(size);
295                 predframe[i]   = bufalloc(size);
296         }
297
298         cur_picture.qblocks =
299                 (int16_t (*)[64])bufalloc(mb_per_pict*block_count*sizeof(int16_t [64]));
300
301         /* Initialise current transformed picture data tables
302            These will soon become a buffer for transformed picture data to allow
303            look-ahead for bit allocation etc.
304          */
305         cur_picture.mbinfo = (
306                 struct mbinfo *)bufalloc(mb_per_pict*sizeof(struct mbinfo));
307
308         cur_picture.blocks =
309                 (int16_t (*)[64])bufalloc(mb_per_pict * block_count * sizeof(int16_t [64]));
310   
311   
312 /* open statistics output file */
313         if(statname[0]=='-') statfile = stdout;
314         else 
315         if(!(statfile = fopen(statname,"w")))
316         {
317       sprintf(errortext,"Couldn't create statistics output file %s",statname);
318       error(errortext);
319         }
320
321         ratectl = malloc(processors * sizeof(ratectl_t*));
322         for(i = 0; i < processors; i++)
323                 ratectl[i] = calloc(1, sizeof(ratectl_t));
324         
325
326
327 /* Start parallel threads */
328
329 //printf("init 1\n");
330         start_motion_engines();
331 //printf("init 2\n");
332         start_transform_engines();
333 //printf("init 3\n");
334         start_itransform_engines();
335 //printf("init 4\n");
336         start_slice_engines();
337 //printf("init 5\n");
338 }
339
340 void error(text)
341 char *text;
342 {
343   fprintf(stderr,text);
344   putc('\n',stderr);
345   exit(1);
346 }
347
348 #define STRINGLEN 254
349
350 int calculate_smp()
351 {
352 /* Get processor count */
353         int result = 1;
354         FILE *proc;
355         if(proc = fopen("/proc/cpuinfo", "r"))
356         {
357                 char string[1024];
358                 while(!feof(proc))
359                 {
360                         fgets(string, 1024, proc);
361                         if(!strncasecmp(string, "processor", 9))
362                         {
363                                 char *ptr = strchr(string, ':');
364                                 if(ptr)
365                                 {
366                                         ptr++;
367                                         result = atol(ptr) + 1;
368                                 }
369                         }
370                         else
371                         if(!strncasecmp(string, "cpus detected", 13))
372                         {
373                                 char *ptr = strchr(string, ':');
374                                 if(ptr)
375                                 {
376                                         ptr++;
377                                         result = atol(ptr);
378                                 }
379                         }
380                 }
381                 fclose(proc);
382         }
383         return result;
384 }
385
386 static void readcmdline(int argc, char *argv[])
387 {
388         int i, j;
389         int h,m,s,f;
390         FILE *fd;
391         char line[256];
392 // Master frame rate table must match decoder
393         static double ratetab[]=
394         {24000.0/1001.0,  // Official rates
395                 24.0,
396                 25.0,
397                 30000.0/1001.0,
398                 30.0,
399                 50.0,
400                 60000.0/1001.0,
401                 60.0,
402
403                 1,           // Unofficial economy rates
404                 5,
405                 10,
406                 12, 
407                 15,
408                 0,
409                 0};
410 // VBV buffer size limits
411         int vbvlim[4] = { 597, 448, 112, 29 };
412         long total_frame_rates = (sizeof(ratetab) / sizeof(double));
413         FILE *proc;
414 // Default 16
415         int param_searchrad = 16;
416         int isnum = 1;
417
418 //printf("readcmdline 1\n");
419         frame0 =                   0;  /* number of first frame */
420         start_frame = end_frame = -1;
421         use_hires_quant = 0;
422         use_denoise_quant = 0;
423         quiet = 1;
424         bit_rate = 5000000;                       /* default bit_rate (bits/s) */
425         prog_seq = 0;                        /* progressive_sequence is faster */
426         mpeg1 = 0;                                   /* ISO/IEC 11172-2 stream */
427     fixed_mquant = 0;                             /* vary the quantization */
428         quant_floor = 0;
429         act_boost = 3.0;
430         N = 15;                                      /* N (# of frames in GOP) */
431         M = 1;  /* M (I/P frame distance) */
432         processors = calculate_smp();
433         frame_rate = -1;
434         chroma_format =            1;  /* chroma_format: 1=4:2:0, 2=4:2:2, 3=4:4:4   LibMPEG3 only does 1 */
435         mpeg_file = 0;
436         qt_file = 0;
437         do_stdin = 0;
438         do_buffers = 1;
439         seq_header_every_gop = 0;
440 /* aspect_ratio_information 1=square pel, 2=4:3, 3=16:9, 4=2.11:1 */
441         aspectratio = 1;  
442
443
444
445
446
447 //printf("readcmdline 2\n");
448
449
450         sprintf(tplorg, "");
451         sprintf(out_path, "");
452
453 #define INTTOYES(x) ((x) ? "Yes" : "No")
454 // This isn't used anymore as this is a library entry point.
455   if(argc < 2)
456   {
457     printf("mpeg2encode V1.3, 2000/01/10\n"
458 "(C) 1996, MPEG Software Simulation Group\n"
459 "(C) 2001 Heroine Virtual\n"
460 "Usage: %s [options] <input file> <output file>\n\n"
461 " -1                 generate an MPEG-1 stream instead of MPEG-2 (%s)\n"
462 " -422                                 generate YUV 4:2:2 output\n"
463 " -b bitrate              fix the bitrate, vary the quantization (%d)\n"
464 " -d                                                     Denoise (%s)\n"
465 " -f rate                                      Convert framerate\n"
466 " -h                          High resolution quantization table (%s)\n"
467 " -m frames                set number of frames between P frames (%d)\n"
468 " -n frames                set number of frames between I frames (%d)\n"
469 " -p                                   encode progressive frames (%s)\n"
470 " -q quantization         fix the quantization, vary the bitrate\n"
471 " [number]               Start encoding from frame number to end\n"
472 " [number1] [number2]    Encode frame number 1 to frame number 2\n"
473 " -u                                        Use only 1 processor\n\n"
474 "Default settings:\n"
475 "   fixed 5000000 bits/sec\n"
476 "   interlaced\n"
477 "   MPEG-2\n"
478 "   15 frames between I frames   0 frames between P frames\n\n"
479 "For the recommended encoding parameters see docs/index.html.\n",
480 argv[0], 
481 mpeg1 ? "MPEG-1" : "MPEG-2",
482 (int)bit_rate,
483 INTTOYES(use_denoise_quant),
484 INTTOYES(use_hires_quant),
485 M - 1,
486 N,
487 INTTOYES(prog_seq));
488     exit(1);
489   }
490 //printf("readcmdline 3\n");
491
492         for(i = 1; i < argc; i++)
493         {
494                 isnum = 1;
495
496                 for(j = 0; j < strlen(argv[i]) && isnum; j++)
497                 {
498                         if(isalpha(argv[i][j])) isnum = 0;
499                 }
500
501
502 //printf("readcmdline %s\n", argv[i]);
503                 if(!strcmp(argv[i], "-1"))
504                 {
505                         mpeg1 = 1;
506                 }
507                 else
508                 if(!strcmp(argv[i], "-a"))
509                 {
510                         i++;
511                         if(i < argc)
512                         {
513                                 aspectratio = atoi(argv[i]);
514                         }
515                         else
516                         {
517                                 fprintf(stderr, "-i needs an aspect ratio enumeration.\n");
518                                 exit(1);
519                         }
520                 }
521                 else
522                 if(!strcmp(argv[i], "-b"))
523                 {
524                         i++;
525                         if(i < argc)
526                         {
527                                 bit_rate = atol(argv[i]);
528                         }
529                         else
530                         {
531                                 fprintf(stderr, "-b requires a bitrate\n");
532                                 exit(1);
533                         }
534                 }
535                 else
536                 if(!strcmp(argv[i], "-d"))
537                 {
538                         use_denoise_quant = 1;
539                 }
540                 else
541                 if(!strcmp(argv[i], "-f"))
542                 {
543                         i++;
544                         if(i < argc)
545                         {
546                                 frame_rate = atof(argv[i]);
547                         }
548                         else
549                         {
550                                 fprintf(stderr, "-f requires a frame rate\n");
551                                 exit(1);
552                         }
553                 }
554                 else
555                 if(!strcmp(argv[i], "-h"))
556                 {
557                         use_hires_quant = 1;
558                 }
559                 else
560                 if(!strcmp(argv[i], "-m"))
561                 {
562                         i++;
563                         if(i < argc)
564                         {
565                                 M = atol(argv[i]) + 1;
566                         }
567                         else
568                         {
569                                 fprintf(stderr, "-m requires a frame count\n");
570                                 exit(1);
571                         }
572                 }
573                 else
574                 if(!strcmp(argv[i], "-n"))
575                 {
576                         i++;
577                         if(i < argc)
578                         {
579                                 N = atol(argv[i]);
580                         }
581                         else
582                         {
583                                 fprintf(stderr, "-n requires a frame count\n");
584                                 exit(1);
585                         }
586                 }
587                 else
588                 if(!strcmp(argv[i], "-p"))
589                 {
590                         prog_seq = 1;
591                 }
592                 else
593                 if(!strcmp(argv[i], "-q"))
594                 {
595                         i++;
596                         if(i < argc)
597                         {
598                                 fixed_mquant = atol(argv[i]);
599                         }
600                         else
601                         {
602                                 fprintf(stderr, "-q requires a quantization value\n");
603                                 exit(1);
604                         }
605                 }
606                 else
607                 if(!strcmp(argv[i], "-u"))
608                 {
609                         processors = 1;
610                 }
611                 else
612                 if(!strcmp(argv[i], "-422"))
613                 {
614                         chroma_format = 2;
615                 }
616                 else
617                 if(!strcmp(argv[i], "-g"))
618                 {
619                         seq_header_every_gop = 1;
620                 }
621                 else
622                 if(!strcmp(argv[i], "-"))
623                 {
624                         do_stdin = 1;
625                 }
626                 else
627 /* Start or end frame if number */
628                 if(isnum)
629                 {
630                         if(start_frame < 0)
631                                 start_frame = atol(argv[i]);
632                         else
633                         if(end_frame < 0)
634                                 end_frame = atol(argv[i]);
635                 }
636                 else
637                 if(!strlen(tplorg) && !do_stdin && !do_buffers)
638                 {
639 /* Input path */
640                         strncpy(tplorg, argv[i], STRINGLEN);
641                 }
642                 else
643                 if(!strlen(out_path))
644                 {
645 /* Output path */
646                         strncpy(out_path, argv[i], STRINGLEN);
647                 }
648         }
649 //printf("readcmdline 4\n");
650
651         if(!strlen(out_path))
652         {
653 // Default output path
654                 strncpy(out_path, tplorg, STRINGLEN);
655                 for(i = strlen(out_path) - 1; i >= 0 && out_path[i] != '.'; i--)
656                         ;
657
658                 if(i < 0) i = strlen(out_path);
659                 
660                 if(mpeg1)
661                         sprintf(&out_path[i], ".m1v");
662                 else
663                         sprintf(&out_path[i], ".m2v");
664         }
665 //printf("readcmdline 5\n");
666
667 /* Get info from input file */
668         if(do_stdin)
669         {
670                 inputtype = T_STDIN;
671         }
672         else
673         if(do_buffers)
674         {
675                 inputtype = T_BUFFERS;
676         }
677         else
678         if(mpeg3_check_sig(tplorg))
679         {
680                 int error_return;
681                 mpeg_file = mpeg3_open(tplorg, &error_return);
682                 inputtype = T_MPEG;
683         }
684         else
685         if(quicktime_check_sig(tplorg))
686         {
687                 qt_file = quicktime_open(tplorg, 1, 0);
688                 inputtype = T_QUICKTIME;
689         }
690 //printf("readcmdline 6\n");
691
692         if(!qt_file && !mpeg_file && !do_stdin && !do_buffers)
693         {
694                 fprintf(stderr, "File format not recognized.\n");
695                 exit(1);
696         }
697
698 //printf("readcmdline 7\n");
699         if(qt_file)
700         {
701                 if(!quicktime_video_tracks(qt_file))
702                 {
703                         fprintf(stderr, "No video tracks in file.\n");
704                         exit(1);
705                 }
706
707                 if(!quicktime_supported_video(qt_file, 0))
708                 {
709                         fprintf(stderr, "Unsupported video codec.\n");
710                         exit(1);
711                 }
712         }
713 //printf("readcmdline 8\n");
714
715 /************************************************************************
716  *                            BEGIN PARAMETER FILE
717  ************************************************************************/
718
719 /* To eliminate the user hassle we replaced the parameter file with hard coded constants. */
720         strcpy(tplref,             "-");  /* name of intra quant matrix file     ("-": default matrix) */
721         strcpy(iqname,             "-");  /* name of intra quant matrix file     ("-": default matrix) */
722         strcpy(niqname,            "-");  /* name of non intra quant matrix file ("-": default matrix) */
723         strcpy(statname,           "/dev/null");  /* name of statistics file ("-": stdout ) */
724
725         if(qt_file)
726         {
727                 nframes =                  quicktime_video_length(qt_file, 0);  /* number of frames */
728                 horizontal_size =          quicktime_video_width(qt_file, 0);
729                 vertical_size =            quicktime_video_height(qt_file, 0);
730         }
731         else
732         if(mpeg_file)
733         {
734                 nframes =                  0x7fffffff;  /* Use percentage instead */
735                 horizontal_size =          mpeg3_video_width(mpeg_file, 0);
736                 vertical_size =            mpeg3_video_height(mpeg_file, 0);
737         }
738         else
739         if(do_stdin)
740         {
741                 unsigned char data[1024];
742                 nframes =                  0x7fffffff;
743                 
744                 fgets(data, 1024, stdin_fd);
745                 horizontal_size =          atol(data);
746                 fgets(data, 1024, stdin_fd);
747                 vertical_size =            atol(data);
748         }
749         else
750         if(do_buffers)
751         {
752                 nframes = 0x7fffffff;
753         }
754         
755         
756         h = m = s = f =            0;  /* timecode of first frame */
757         fieldpic =                 0;  /* 0: progressive, 1: bottom first, 2: top first, 3 = progressive seq, field MC and DCT in picture */
758         low_delay =                0;  /* low_delay  */
759         constrparms =              0;  /* constrained_parameters_flag */
760         profile =                  4;  /* Profile ID: Simple = 5, Main = 4, SNR = 3, Spatial = 2, High = 1 */
761         level =                    4;  /* Level ID:   Low = 10, Main = 8, High 1440 = 6, High = 4                  */
762         video_format =             2;  /* video_format: 0=comp., 1=PAL, 2=NTSC, 3=SECAM, 4=MAC, 5=unspec. */
763         color_primaries =          5;  /* color_primaries */
764         dctsatlim               = mpeg1 ? 255 : 2047;
765         dctsatlim = 255;
766         transfer_characteristics = 5;  /* transfer_characteristics */
767         matrix_coefficients =      4;  /* matrix_coefficients (not used) */
768         display_horizontal_size =  horizontal_size;
769         display_vertical_size =    vertical_size;
770         cur_picture.dc_prec =      0;  /* intra_dc_precision (0: 8 bit, 1: 9 bit, 2: 10 bit, 3: 11 bit */
771         cur_picture.topfirst =     1;  /* top_field_first */
772
773         frame_pred_dct_tab[0] =    mpeg1 ? 1 : 0;  /* frame_pred_frame_dct (I P B) */
774         frame_pred_dct_tab[1] =    mpeg1 ? 1 : 0;  /* frame_pred_frame_dct (I P B) */
775         frame_pred_dct_tab[2] =    mpeg1 ? 1 : 0;  /* frame_pred_frame_dct (I P B) */
776
777         conceal_tab[0]                   = 0;  /* concealment_motion_vectors (I P B) */
778         conceal_tab[1]                   = 0;  /* concealment_motion_vectors (I P B) */
779         conceal_tab[2]                   = 0;  /* concealment_motion_vectors (I P B) */
780         qscale_tab[0]                    = mpeg1 ? 0 : 1;  /* q_scale_type  (I P B) */
781         qscale_tab[1]                    = mpeg1 ? 0 : 1;  /* q_scale_type  (I P B) */
782         qscale_tab[2]                    = mpeg1 ? 0 : 1;  /* q_scale_type  (I P B) */
783
784         intravlc_tab[0]                  = 0;  /* intra_vlc_format (I P B)*/
785         intravlc_tab[1]                  = 0;  /* intra_vlc_format (I P B)*/
786         intravlc_tab[2]                  = 0;  /* intra_vlc_format (I P B)*/
787         altscan_tab[0]                   = 0;  /* alternate_scan_hv (I P B) */
788         altscan_tab[1]                   = 0;  /* alternate_scan_hv (I P B) */
789         altscan_tab[2]                   = 0;  /* alternate_scan_hv (I P B) */
790         opt_dc_prec         = 0;  /* 8 bits */
791         opt_topfirst        = (fieldpic == 2);
792         opt_repeatfirst     = 0;
793         opt_prog_frame      = prog_seq;
794         cur_picture.repeatfirst =              0;  /* repeat_first_field */
795         cur_picture.prog_frame =               prog_seq;  /* progressive_frame */
796 /* P:  forw_hor_f_code forw_vert_f_code search_width/height */
797     motion_data = (struct motion_data *)malloc(3 * sizeof(struct motion_data));
798         video_buffer_size =        46 * 1024 * 8;
799
800 /************************************************************************
801  *                                END PARAMETER FILE
802  ************************************************************************/
803 //printf("readcmdline 10\n");
804
805         if(mpeg1)
806         {
807                 opt_prog_frame = 1;
808                 cur_picture.prog_frame = 1;
809                 prog_seq = 1;
810         }
811
812         if(qt_file)
813         {
814                 input_frame_rate = quicktime_frame_rate(qt_file, 0);
815         }
816         else
817         if(mpeg_file)
818         {
819                 input_frame_rate = mpeg3_frame_rate(mpeg_file, 0);
820         }
821         else
822         if(do_stdin)
823         {
824                 char data[1024];
825                 
826                 fgets(data, 1024, stdin_fd);
827                 
828                 input_frame_rate = atof(data);
829         }
830         
831         
832         if(frame_rate < 0)
833         {
834                 frame_rate = input_frame_rate;
835         }
836 //printf("readcmdline 11\n");
837
838 //processors = 1;
839 //nframes = 16;
840         if(start_frame >= 0 && end_frame >= 0)
841         {
842                 nframes = end_frame - start_frame;
843                 frame0 = start_frame;
844         }
845         else
846         if(start_frame >= 0)
847         {
848                 end_frame = nframes;
849                 nframes -= start_frame;
850                 frame0 = start_frame;
851         }
852         else
853         {
854                 start_frame = 0;
855                 end_frame = nframes;
856         }
857 //printf("readcmdline 12\n");
858
859 // Show status
860         if(verbose)
861         {
862                 printf("Encoding: %s frames %ld\n", out_path, nframes);
863
864         if(fixed_mquant == 0) 
865                 printf("   bitrate %.0f\n", bit_rate);
866         else
867                 printf("   quantization %d\n", fixed_mquant);
868         printf("   %d frames between I frames   %d frames between P frames\n", N, M - 1);
869         printf("   %s\n", (prog_seq ? "progressive" : "interlaced"));
870                 printf("   %s\n", (mpeg1 ? "MPEG-1" : "MPEG-2"));
871                 printf("   %s\n", (chroma_format == 1) ? "YUV-420" : "YUV-422");
872                 printf("   %d processors\n", processors);
873                 printf("   %.02f frames per second\n", frame_rate);
874                 printf("   Denoise %s\n", INTTOYES(use_denoise_quant));
875                 printf("   Aspect ratio index %d\n", aspectratio);
876                 printf("   Hires quantization %s\n", INTTOYES(use_hires_quant));
877
878
879                 if(mpeg_file)
880                 {
881                         fprintf(stderr, "(MPEG to MPEG transcoding for official use only.)\n");
882                 }
883         }
884
885
886
887         { 
888                 int radius_x = ((param_searchrad + 4) / 8) * 8;
889                 int radius_y = ((param_searchrad * vertical_size / horizontal_size + 4) / 8) * 8;
890                 int c;
891         
892                 /* TODO: These f-codes should really be adjusted for each
893                    picture type... */
894                 c=5;
895                 if( radius_x*M < 64) c = 4;
896                 if( radius_x*M < 32) c = 3;
897                 if( radius_x*M < 16) c = 2;
898                 if( radius_x*M < 8) c = 1;
899
900                 if (!motion_data)
901                         error("malloc failed\n");
902
903                 for (i=0; i<M; i++)
904                 {
905                         if(i==0)
906                         {
907                                 motion_data[i].forw_hor_f_code  = c;
908                                 motion_data[i].forw_vert_f_code = c;
909                                 motion_data[i].sxf = MAX(1,radius_x*M);
910                                 motion_data[i].syf = MAX(1,radius_y*M);
911                         }
912                         else
913                         {
914                                 motion_data[i].forw_hor_f_code  = c;
915                                 motion_data[i].forw_vert_f_code = c;
916                                 motion_data[i].sxf = MAX(1,radius_x*i);
917                                 motion_data[i].syf = MAX(1,radius_y*i);
918                                 motion_data[i].back_hor_f_code  = c;
919                                 motion_data[i].back_vert_f_code = c;
920                                 motion_data[i].sxb = MAX(1,radius_x*(M-i));
921                                 motion_data[i].syb = MAX(1,radius_y*(M-i));
922                         }
923                 }
924                 
925         }
926
927 //    vbv_buffer_size = floor(((double)bit_rate * 0.20343) / 16384.0);
928     if(mpeg1)
929                 vbv_buffer_size = 20 * 16384;
930         else
931                 vbv_buffer_size = 112 * 16384;
932
933         fast_mc_frac    = 10;
934         mc_44_red               = 2;
935         mc_22_red               = 3;
936
937     if(vbv_buffer_size > vbvlim[(level - 4) >> 1])
938         vbv_buffer_size = vbvlim[(level - 4) >> 1];
939
940 /* Set up frame buffers */
941         frame_buffer = malloc(horizontal_size * vertical_size * 3 + 4);
942         row_pointers = malloc(sizeof(unsigned char*) * vertical_size);
943         for(i = 0; i < vertical_size; i++) row_pointers[i] = &frame_buffer[horizontal_size * 3 * i];
944
945 // Get frame rate code from input frame rate
946         for(i = 0; i < total_frame_rates; i++)
947         {
948                 if(fabs(frame_rate - ratetab[i]) < 0.001) frame_rate_code = i + 1;
949         }
950
951 /* make flags boolean (x!=0 -> x=1) */
952   mpeg1 = !!mpeg1;
953   fieldpic = !!fieldpic;
954   low_delay = !!low_delay;
955   constrparms = !!constrparms;
956   prog_seq = !!prog_seq;
957   cur_picture.topfirst = !!cur_picture.topfirst;
958
959   for (i = 0; i < 3; i++)
960   {
961     frame_pred_dct_tab[i] = !!frame_pred_dct_tab[i];
962     conceal_tab[i] = !!conceal_tab[i];
963     qscale_tab[i] = !!qscale_tab[i];
964     intravlc_tab[i] = !!intravlc_tab[i];
965     altscan_tab[i] = !!altscan_tab[i];
966   }
967   cur_picture.repeatfirst = !!cur_picture.repeatfirst;
968   cur_picture.prog_frame = !!cur_picture.prog_frame;
969
970   /* make sure MPEG specific parameters are valid */
971   range_checks();
972
973   /* timecode -> frame number */
974   tc0 = h;
975   tc0 = 60*tc0 + m;
976   tc0 = 60*tc0 + s;
977   tc0 = (int)(frame_rate+0.5)*tc0 + f;
978
979   qt_output = 0;
980
981
982
983
984
985
986
987
988
989
990   if (!mpeg1)
991   {
992     profile_and_level_checks();
993   }
994   else
995   {
996     /* MPEG-1 */
997     if (constrparms)
998     {
999       if (horizontal_size>768
1000           || vertical_size>576
1001           || ((horizontal_size+15)/16)*((vertical_size+15) / 16) > 396
1002           || ((horizontal_size+15)/16)*((vertical_size+15) / 16)*frame_rate>396*25.0
1003           || frame_rate>30.0)
1004       {
1005         if (!quiet)
1006           fprintf(stderr,"*** Warning: setting constrained_parameters_flag = 0\n");
1007         constrparms = 0;
1008       }
1009     }
1010   }
1011
1012   /* relational checks */
1013
1014   if (mpeg1)
1015   {
1016     if (!prog_seq)
1017     {
1018       prog_seq = 1;
1019     }
1020
1021     if (chroma_format!=CHROMA420)
1022     {
1023       chroma_format = CHROMA420;
1024     }
1025
1026     if (cur_picture.dc_prec!=0)
1027     {
1028       cur_picture.dc_prec = 0;
1029     }
1030
1031     for (i=0; i<3; i++)
1032       if (qscale_tab[i])
1033       {
1034         qscale_tab[i] = 0;
1035       }
1036
1037     for (i=0; i<3; i++)
1038       if (intravlc_tab[i])
1039       {
1040         intravlc_tab[i] = 0;
1041       }
1042
1043     for (i=0; i<3; i++)
1044       if (altscan_tab[i])
1045       {
1046         altscan_tab[i] = 0;
1047       }
1048   }
1049
1050   if (!mpeg1 && constrparms)
1051   {
1052     constrparms = 0;
1053   }
1054
1055   if (prog_seq && !cur_picture.prog_frame)
1056   {
1057     cur_picture.prog_frame = 1;
1058   }
1059
1060   if (cur_picture.prog_frame && fieldpic)
1061   {
1062     fieldpic = 0;
1063   }
1064
1065   if (!cur_picture.prog_frame && cur_picture.repeatfirst)
1066   {
1067     cur_picture.repeatfirst = 0;
1068   }
1069
1070   if (cur_picture.prog_frame)
1071   {
1072     for (i=0; i<3; i++)
1073       if (!frame_pred_dct_tab[i])
1074       {
1075         frame_pred_dct_tab[i] = 1;
1076       }
1077   }
1078
1079   if (prog_seq && !cur_picture.repeatfirst && cur_picture.topfirst)
1080   {
1081      if (!quiet)
1082        fprintf(stderr,"Warning: setting top_field_first = 0\n");
1083     cur_picture.topfirst = 0;
1084   }
1085
1086   /* search windows */
1087   for (i=0; i<M; i++)
1088   {
1089     if (motion_data[i].sxf > (4<<motion_data[i].forw_hor_f_code)-1)
1090     {
1091       if (!quiet)
1092         fprintf(stderr,
1093           "Warning: reducing forward horizontal search width to %d\n",
1094           (4<<motion_data[i].forw_hor_f_code)-1);
1095       motion_data[i].sxf = (4<<motion_data[i].forw_hor_f_code)-1;
1096     }
1097
1098     if (motion_data[i].syf > (4<<motion_data[i].forw_vert_f_code)-1)
1099     {
1100       if (!quiet)
1101         fprintf(stderr,
1102           "Warning: reducing forward vertical search width to %d\n",
1103           (4<<motion_data[i].forw_vert_f_code)-1);
1104       motion_data[i].syf = (4<<motion_data[i].forw_vert_f_code)-1;
1105     }
1106
1107     if (i!=0)
1108     {
1109       if (motion_data[i].sxb > (4<<motion_data[i].back_hor_f_code)-1)
1110       {
1111         if (!quiet)
1112           fprintf(stderr,
1113             "Warning: reducing backward horizontal search width to %d\n",
1114             (4<<motion_data[i].back_hor_f_code)-1);
1115         motion_data[i].sxb = (4<<motion_data[i].back_hor_f_code)-1;
1116       }
1117
1118       if (motion_data[i].syb > (4<<motion_data[i].back_vert_f_code)-1)
1119       {
1120         if (!quiet)
1121           fprintf(stderr,
1122             "Warning: reducing backward vertical search width to %d\n",
1123             (4<<motion_data[i].back_vert_f_code)-1);
1124         motion_data[i].syb = (4<<motion_data[i].back_vert_f_code)-1;
1125       }
1126     }
1127   }
1128
1129 }
1130
1131 /*
1132   If the user has selected suppression of hf noise via
1133   quantisation then we boost quantisation of hf components
1134   EXPERIMENTAL: currently a linear ramp from 0 at 4pel to 
1135   50% increased quantisation...
1136 */
1137
1138 static int quant_hfnoise_filt(int orgquant, int qmat_pos )
1139 {
1140         int x = qmat_pos % 8;
1141         int y = qmat_pos / 8;
1142         int qboost = 1024;
1143
1144         if(!use_denoise_quant)
1145         {
1146                 return orgquant;
1147         }
1148
1149         /* Maximum 50% quantisation boost for HF components... */
1150         if( x > 4 )
1151                 qboost += (256*(x-4)/3);
1152         if( y > 4 )
1153                 qboost += (256*(y-4)/3);
1154
1155         return (orgquant * qboost + 512)/ 1024;
1156 }
1157
1158 static void readquantmat()
1159 {
1160   int i,v,q;
1161         load_iquant = 0;
1162         load_niquant = 0;
1163
1164   if (iqname[0]=='-')
1165   {
1166         if(use_hires_quant)
1167         {
1168                 load_iquant |= 1;
1169                 for (i=0; i<64; i++)
1170                 {
1171                         intra_q[i] = hires_intra_quantizer_matrix_hv[i];
1172                 }       
1173         }
1174         else
1175         {
1176                 load_iquant = use_denoise_quant;
1177                 for (i=0; i<64; i++)
1178                 {
1179                         v = quant_hfnoise_filt(default_intra_quantizer_matrix_hv[i], i);
1180                         if (v<1 || v>255)
1181                                 error("value in intra quant matrix invalid (after noise filt adjust)");
1182                         intra_q[i] = v;
1183                 } 
1184         }
1185   }
1186
1187 /* TODO: Inv Quant matrix initialisation should check if the fraction fits in 16 bits! */
1188   if (niqname[0]=='-')
1189   {
1190                 if(use_hires_quant)
1191                 {
1192                         for (i=0; i<64; i++)
1193                         {
1194                                 inter_q[i] = hires_nonintra_quantizer_matrix_hv[i];
1195                         }       
1196                 }
1197                 else
1198                 {
1199 /* default non-intra matrix is all 16's. For *our* default we use something
1200    more suitable for domestic analog sources... which is non-standard...*/
1201                         load_niquant |= 1;
1202                         for (i=0; i<64; i++)
1203                         {
1204                                 v = quant_hfnoise_filt(default_nonintra_quantizer_matrix_hv[i],i);
1205                                 if (v<1 || v>255)
1206                                         error("value in non-intra quant matrix invalid (after noise filt adjust)");
1207                                 inter_q[i] = v;
1208                         }
1209                 }
1210   }
1211
1212         for (i=0; i<64; i++)
1213         {
1214                 i_intra_q[i] = (int)(((double)IQUANT_SCALE) / ((double)intra_q[i]));
1215                 i_inter_q[i] = (int)(((double)IQUANT_SCALE) / ((double)inter_q[i]));
1216         }
1217         
1218         for( q = 1; q <= 112; ++q )
1219         {
1220                 for (i=0; i<64; i++)
1221                 {
1222                         intra_q_tbl[q][i] = intra_q[i] * q;
1223                         inter_q_tbl[q][i] = inter_q[i] * q;
1224                         intra_q_tblf[q][i] = (float)intra_q_tbl[q][i];
1225                         inter_q_tblf[q][i] = (float)inter_q_tbl[q][i];
1226                         i_intra_q_tblf[q][i] = 1.0f/ ( intra_q_tblf[q][i] * 0.98);
1227                         i_intra_q_tbl[q][i] = (IQUANT_SCALE/intra_q_tbl[q][i]);
1228                         i_inter_q_tblf[q][i] =  1.0f/ (inter_q_tblf[q][i] * 0.98);
1229                         i_inter_q_tbl[q][i] = (IQUANT_SCALE/inter_q_tbl[q][i] );
1230                 }
1231         }
1232 }