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