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