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