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