test: update MPEG-2 encoding case
[platform/upstream/libva.git] / test / encode / mpeg2enc.c
1 /*
2  * Copyright (c) 2012 Intel Corporation. All Rights Reserved.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sub license, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the
13  * next paragraph) shall be included in all copies or substantial portions
14  * of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
19  * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
20  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24 /*
25  * Simple MPEG-2 encoder based on libVA.
26  *
27  */  
28
29 #include "sysdeps.h"
30
31 #include <getopt.h>
32 #include <unistd.h>
33
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <pthread.h>
39
40 #include <va/va.h>
41 #include <va/va_enc_mpeg2.h>
42
43 #include "va_display.h"
44
45 #define START_CODE_PICUTRE      0x00000100
46 #define START_CODE_SLICE        0x00000101
47 #define START_CODE_USER         0x000001B2
48 #define START_CODE_SEQ          0x000001B3
49 #define START_CODE_EXT          0x000001B5
50 #define START_CODE_GOP          0x000001B8
51
52 #define CHROMA_FORMAT_RESERVED  0
53 #define CHROMA_FORMAT_420       1
54 #define CHROMA_FORMAT_422       2
55 #define CHROMA_FORMAT_444       3
56
57 #define MAX_SLICES              128
58
59 enum {
60     MPEG2_MODE_I = 0,
61     MPEG2_MODE_IP,
62     MPEG2_MODE_IPB,
63 };
64
65 enum {
66     MPEG2_LEVEL_LOW = 0,
67     MPEG2_LEVEL_MAIN,
68     MPEG2_LEVEL_HIGH,
69 };
70
71 #define CHECK_VASTATUS(va_status, func)                                 \
72     if (va_status != VA_STATUS_SUCCESS) {                               \
73         fprintf(stderr, "%s:%s (%d) failed, exit\n", __func__, func, __LINE__); \
74         exit(1);                                                        \
75     }
76
77 static VAProfile mpeg2_va_profiles[] = {
78     VAProfileMPEG2Simple,
79     VAProfileMPEG2Main
80 };
81
82 static struct _mpeg2_sampling_density
83 {
84     int samplers_per_line;
85     int line_per_frame;
86     int frame_per_sec;
87 } mpeg2_upper_samplings[2][3] = {
88     { { 0, 0, 0 },
89       { 720, 576, 30 },
90       { 0, 0, 0 },
91     },
92
93     { { 352, 288, 30 },
94       { 720, 576, 30 },
95       { 1920, 1152, 60 },
96     }
97 };
98
99 struct mpeg2enc_context {
100     /* args */
101     int rate_control_mode;
102     int fps;
103     int mode; /* 0:I, 1:I/P, 2:I/P/B */
104     VAProfile profile;
105     int level;
106     int width;
107     int height;
108     int frame_size;
109     int num_pictures;
110     int qp;
111     FILE *ifp;
112     FILE *ofp;
113     unsigned char *frame_data_buffer;
114     int intra_period;
115     int ip_period;
116     int bit_rate; /* in kbps */
117     VAEncPictureType next_type;
118     int next_display_order;
119     int next_bframes;
120     int new_sequence;
121     int new_gop_header;
122     int gop_header_in_display_order;
123
124     /* VA resource */
125     VADisplay va_dpy;
126     VAEncSequenceParameterBufferMPEG2 seq_param;
127     VAEncPictureParameterBufferMPEG2 pic_param;
128     VAEncSliceParameterBufferMPEG2 slice_param[MAX_SLICES];
129     VAContextID context_id;
130     VAConfigID config_id;
131     VABufferID seq_param_buf_id;                /* Sequence level parameter */
132     VABufferID pic_param_buf_id;                /* Picture level parameter */
133     VABufferID slice_param_buf_id[MAX_SLICES];  /* Slice level parameter, multil slices */
134     VABufferID codedbuf_buf_id;                 /* Output buffer, compressed data */
135     VABufferID packed_seq_header_param_buf_id;
136     VABufferID packed_seq_buf_id;
137     VABufferID packed_pic_header_param_buf_id;
138     VABufferID packed_pic_buf_id;
139     int num_slice_groups;
140     int codedbuf_i_size;
141     int codedbuf_pb_size;
142
143     /* thread */
144     pthread_t upload_thread_id;
145     int upload_thread_value;
146     int current_input_surface;
147     int current_upload_surface;
148 };
149
150 /*
151  * mpeg2enc helpers
152  */
153 #define BITSTREAM_ALLOCATE_STEPPING     4096
154
155 struct __bitstream {
156     unsigned int *buffer;
157     int bit_offset;
158     int max_size_in_dword;
159 };
160
161 typedef struct __bitstream bitstream;
162
163 static unsigned int 
164 swap32(unsigned int val)
165 {
166     unsigned char *pval = (unsigned char *)&val;
167
168     return ((pval[0] << 24)     |
169             (pval[1] << 16)     |
170             (pval[2] << 8)      |
171             (pval[3] << 0));
172 }
173
174 static void
175 bitstream_start(bitstream *bs)
176 {
177     bs->max_size_in_dword = BITSTREAM_ALLOCATE_STEPPING;
178     bs->buffer = calloc(bs->max_size_in_dword * sizeof(int), 1);
179     bs->bit_offset = 0;
180 }
181
182 static void
183 bitstream_end(bitstream *bs)
184 {
185     int pos = (bs->bit_offset >> 5);
186     int bit_offset = (bs->bit_offset & 0x1f);
187     int bit_left = 32 - bit_offset;
188
189     if (bit_offset) {
190         bs->buffer[pos] = swap32((bs->buffer[pos] << bit_left));
191     }
192 }
193  
194 static void
195 bitstream_put_ui(bitstream *bs, unsigned int val, int size_in_bits)
196 {
197     int pos = (bs->bit_offset >> 5);
198     int bit_offset = (bs->bit_offset & 0x1f);
199     int bit_left = 32 - bit_offset;
200
201     if (!size_in_bits)
202         return;
203
204     if (size_in_bits < 32)
205         val &= ((1 << size_in_bits) - 1);
206
207     bs->bit_offset += size_in_bits;
208
209     if (bit_left > size_in_bits) {
210         bs->buffer[pos] = (bs->buffer[pos] << size_in_bits | val);
211     } else {
212         size_in_bits -= bit_left;
213         bs->buffer[pos] = (bs->buffer[pos] << bit_left) | (val >> size_in_bits);
214         bs->buffer[pos] = swap32(bs->buffer[pos]);
215
216         if (pos + 1 == bs->max_size_in_dword) {
217             bs->max_size_in_dword += BITSTREAM_ALLOCATE_STEPPING;
218             bs->buffer = realloc(bs->buffer, bs->max_size_in_dword * sizeof(unsigned int));
219         }
220
221         bs->buffer[pos + 1] = val;
222     }
223 }
224
225 static void
226 bitstream_byte_aligning(bitstream *bs, int bit)
227 {
228     int bit_offset = (bs->bit_offset & 0x7);
229     int bit_left = 8 - bit_offset;
230     int new_val;
231
232     if (!bit_offset)
233         return;
234
235     assert(bit == 0 || bit == 1);
236
237     if (bit)
238         new_val = (1 << bit_left) - 1;
239     else
240         new_val = 0;
241
242     bitstream_put_ui(bs, new_val, bit_left);
243 }
244
245 static struct mpeg2_frame_rate {
246     int code;
247     float value;
248 } frame_rate_tab[] = {
249     {1, 23.976},
250     {2, 24.0},
251     {3, 25.0},
252     {4, 29.97},
253     {5, 30},
254     {6, 50},
255     {7, 59.94},
256     {8, 60}
257 };
258
259 static int
260 find_frame_rate_code(const VAEncSequenceParameterBufferMPEG2 *seq_param)
261 {
262     unsigned int delta = -1;
263     int code = 1, i;
264     float frame_rate_value = seq_param->frame_rate * 
265         (seq_param->sequence_extension.bits.frame_rate_extension_d + 1) / 
266         (seq_param->sequence_extension.bits.frame_rate_extension_n + 1);
267
268     for (i = 0; i < sizeof(frame_rate_tab) / sizeof(frame_rate_tab[0]); i++) {
269
270         if (abs(1000 * frame_rate_tab[i].value - 1000 * frame_rate_value) < delta) {
271             code = frame_rate_tab[i].code;
272             delta = abs(1000 * frame_rate_tab[i].value - 1000 * frame_rate_value);
273         }
274     }
275
276     return code;
277 }
278
279 static void 
280 sps_rbsp(struct mpeg2enc_context *ctx,
281          const VAEncSequenceParameterBufferMPEG2 *seq_param,
282          bitstream *bs)
283 {
284     int frame_rate_code = find_frame_rate_code(seq_param);
285
286     if (ctx->new_sequence) {
287         bitstream_put_ui(bs, START_CODE_SEQ, 32);
288         bitstream_put_ui(bs, seq_param->picture_width, 12);
289         bitstream_put_ui(bs, seq_param->picture_height, 12);
290         bitstream_put_ui(bs, seq_param->aspect_ratio_information, 4);
291         bitstream_put_ui(bs, frame_rate_code, 4); /* frame_rate_code */
292         bitstream_put_ui(bs, (seq_param->bits_per_second + 399) / 400, 18); /* the low 18 bits of bit_rate */
293         bitstream_put_ui(bs, 1, 1); /* marker_bit */
294         bitstream_put_ui(bs, seq_param->vbv_buffer_size, 10);
295         bitstream_put_ui(bs, 0, 1); /* constraint_parameter_flag, always 0 for MPEG-2 */
296         bitstream_put_ui(bs, 0, 1); /* load_intra_quantiser_matrix */
297         bitstream_put_ui(bs, 0, 1); /* load_non_intra_quantiser_matrix */
298
299         bitstream_byte_aligning(bs, 0);
300
301         bitstream_put_ui(bs, START_CODE_EXT, 32);
302         bitstream_put_ui(bs, 1, 4); /* sequence_extension id */
303         bitstream_put_ui(bs, seq_param->sequence_extension.bits.profile_and_level_indication, 8);
304         bitstream_put_ui(bs, seq_param->sequence_extension.bits.progressive_sequence, 1);
305         bitstream_put_ui(bs, seq_param->sequence_extension.bits.chroma_format, 2);
306         bitstream_put_ui(bs, seq_param->picture_width >> 12, 2);
307         bitstream_put_ui(bs, seq_param->picture_height >> 12, 2);
308         bitstream_put_ui(bs, ((seq_param->bits_per_second + 399) / 400) >> 18, 12); /* bit_rate_extension */
309         bitstream_put_ui(bs, 1, 1); /* marker_bit */
310         bitstream_put_ui(bs, seq_param->vbv_buffer_size >> 10, 8);
311         bitstream_put_ui(bs, seq_param->sequence_extension.bits.low_delay, 1);
312         bitstream_put_ui(bs, seq_param->sequence_extension.bits.frame_rate_extension_n, 2);
313         bitstream_put_ui(bs, seq_param->sequence_extension.bits.frame_rate_extension_d, 5);
314
315         bitstream_byte_aligning(bs, 0);
316     }
317
318     if (ctx->new_gop_header) {
319         bitstream_put_ui(bs, START_CODE_GOP, 32);
320         bitstream_put_ui(bs, seq_param->gop_header.bits.time_code, 25);
321         bitstream_put_ui(bs, seq_param->gop_header.bits.closed_gop, 1);
322         bitstream_put_ui(bs, seq_param->gop_header.bits.broken_link, 1);
323
324         bitstream_byte_aligning(bs, 0);
325     }
326 }
327
328 static void 
329 pps_rbsp(const VAEncSequenceParameterBufferMPEG2 *seq_param,
330          const VAEncPictureParameterBufferMPEG2 *pic_param,
331          bitstream *bs)
332 {
333     int i;
334     int chroma_420_type;
335
336     if (seq_param->sequence_extension.bits.chroma_format == CHROMA_FORMAT_420)
337         chroma_420_type = pic_param->picture_coding_extension.bits.progressive_frame;
338     else
339         chroma_420_type = 0;
340
341     bitstream_put_ui(bs, START_CODE_PICUTRE, 32);
342     bitstream_put_ui(bs, pic_param->temporal_reference, 10);
343     bitstream_put_ui(bs,
344                      pic_param->picture_type == VAEncPictureTypeIntra ? 1 :
345                      pic_param->picture_type == VAEncPictureTypePredictive ? 2 : 3,
346                      3);
347     bitstream_put_ui(bs, 0xFFFF, 16); /* vbv_delay, always 0xFFFF */
348     
349     if (pic_param->picture_type == VAEncPictureTypePredictive ||
350         pic_param->picture_type == VAEncPictureTypeBidirectional) {
351         bitstream_put_ui(bs, 0, 1); /* full_pel_forward_vector, always 0 for MPEG-2 */
352         bitstream_put_ui(bs, 7, 3); /* forward_f_code, always 7 for MPEG-2 */
353     }
354
355     if (pic_param->picture_type == VAEncPictureTypeBidirectional) {
356         bitstream_put_ui(bs, 0, 1); /* full_pel_backward_vector, always 0 for MPEG-2 */
357         bitstream_put_ui(bs, 7, 3); /* backward_f_code, always 7 for MPEG-2 */
358     }
359      
360     bitstream_put_ui(bs, 0, 1); /* extra_bit_picture, 0 */
361
362     bitstream_byte_aligning(bs, 0);
363
364     bitstream_put_ui(bs, START_CODE_EXT, 32);
365     bitstream_put_ui(bs, 8, 4); /* Picture Coding Extension ID: 8 */
366     bitstream_put_ui(bs, pic_param->f_code[0][0], 4);
367     bitstream_put_ui(bs, pic_param->f_code[0][1], 4);
368     bitstream_put_ui(bs, pic_param->f_code[1][0], 4);
369     bitstream_put_ui(bs, pic_param->f_code[1][1], 4);
370
371     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.intra_dc_precision, 2);
372     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.picture_structure, 2);
373     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.top_field_first, 1);
374     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.frame_pred_frame_dct, 1);
375     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.concealment_motion_vectors, 1);
376     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.q_scale_type, 1);
377     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.intra_vlc_format, 1);
378     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.alternate_scan, 1);
379     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.repeat_first_field, 1);
380     bitstream_put_ui(bs, chroma_420_type, 1);
381     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.progressive_frame, 1);
382     bitstream_put_ui(bs, pic_param->picture_coding_extension.bits.composite_display_flag, 1);
383
384     bitstream_byte_aligning(bs, 0);
385 }
386
387 static int
388 build_packed_pic_buffer(const VAEncSequenceParameterBufferMPEG2 *seq_param,
389                         const VAEncPictureParameterBufferMPEG2 *pic_param,
390                         unsigned char **header_buffer)
391 {
392     bitstream bs;
393
394     bitstream_start(&bs);
395     pps_rbsp(seq_param, pic_param, &bs);
396     bitstream_end(&bs);
397
398     *header_buffer = (unsigned char *)bs.buffer;
399     return bs.bit_offset;
400 }
401
402 static int
403 build_packed_seq_buffer(struct mpeg2enc_context *ctx,
404                         const VAEncSequenceParameterBufferMPEG2 *seq_param,
405                         unsigned char **header_buffer)
406 {
407     bitstream bs;
408
409     bitstream_start(&bs);
410     sps_rbsp(ctx, seq_param, &bs);
411     bitstream_end(&bs);
412
413     *header_buffer = (unsigned char *)bs.buffer;
414     return bs.bit_offset;
415 }
416
417 /*
418  * mpeg2enc
419  */
420 #define SID_INPUT_PICTURE_0                     0
421 #define SID_INPUT_PICTURE_1                     1
422 #define SID_REFERENCE_PICTURE_L0                2
423 #define SID_REFERENCE_PICTURE_L1                3
424 #define SID_RECON_PICTURE                       4
425 #define SID_NUMBER                              SID_RECON_PICTURE + 1
426
427 static VASurfaceID surface_ids[SID_NUMBER];
428
429 /*
430  * upload thread function
431  */
432 static void *
433 upload_yuv_to_surface(void *data)
434 {
435     struct mpeg2enc_context *ctx = data;
436     VAImage surface_image;
437     VAStatus va_status;
438     void *surface_p = NULL;
439     unsigned char *y_src, *u_src, *v_src;
440     unsigned char *y_dst, *u_dst, *v_dst;
441     int y_size = ctx->width * ctx->height;
442     int u_size = (ctx->width >> 1) * (ctx->height >> 1);
443     int row, col;
444     size_t n_items;
445
446     do {
447         n_items = fread(ctx->frame_data_buffer, ctx->frame_size, 1, ctx->ifp);
448     } while (n_items != 1);
449
450     va_status = vaDeriveImage(ctx->va_dpy, surface_ids[ctx->current_upload_surface], &surface_image);
451     CHECK_VASTATUS(va_status,"vaDeriveImage");
452
453     vaMapBuffer(ctx->va_dpy, surface_image.buf, &surface_p);
454     assert(VA_STATUS_SUCCESS == va_status);
455         
456     y_src = ctx->frame_data_buffer;
457     u_src = ctx->frame_data_buffer + y_size; /* UV offset for NV12 */
458     v_src = ctx->frame_data_buffer + y_size + u_size;
459
460     y_dst = surface_p + surface_image.offsets[0];
461     u_dst = surface_p + surface_image.offsets[1]; /* UV offset for NV12 */
462     v_dst = surface_p + surface_image.offsets[2];
463
464     /* Y plane */
465     for (row = 0; row < surface_image.height; row++) {
466         memcpy(y_dst, y_src, surface_image.width);
467         y_dst += surface_image.pitches[0];
468         y_src += ctx->width;
469     }
470
471     if (surface_image.format.fourcc == VA_FOURCC_NV12) { /* UV plane */
472         for (row = 0; row < surface_image.height / 2; row++) {
473             for (col = 0; col < surface_image.width / 2; col++) {
474                 u_dst[col * 2] = u_src[col];
475                 u_dst[col * 2 + 1] = v_src[col];
476             }
477
478             u_dst += surface_image.pitches[1];
479             u_src += (ctx->width / 2);
480             v_src += (ctx->width / 2);
481         }
482     } else {
483         for (row = 0; row < surface_image.height / 2; row++) {
484             for (col = 0; col < surface_image.width / 2; col++) {
485                 u_dst[col] = u_src[col];
486                 v_dst[col] = v_src[col];
487             }
488
489             u_dst += surface_image.pitches[1];
490             v_dst += surface_image.pitches[2];
491             u_src += (ctx->width / 2);
492             v_src += (ctx->width / 2);
493         }
494     }
495
496     vaUnmapBuffer(ctx->va_dpy, surface_image.buf);
497     vaDestroyImage(ctx->va_dpy, surface_image.image_id);
498
499     return NULL;
500 }
501
502 static void 
503 mpeg2enc_exit(struct mpeg2enc_context *ctx, int exit_code)
504 {
505     if (ctx->frame_data_buffer) {
506         free(ctx->frame_data_buffer);
507         ctx->frame_data_buffer = NULL;
508     }
509
510     if (ctx->ifp) {
511         fclose(ctx->ifp);
512         ctx->ifp = NULL;
513     }
514
515     if (ctx->ofp) {
516         fclose(ctx->ofp);
517         ctx->ofp = NULL;
518     }
519
520     exit(exit_code);
521 }
522
523 static void 
524 usage(char *program)
525 {   
526     fprintf(stderr, "Usage: %s --help\n", program);
527     fprintf(stderr, "\t--help   print this message\n");
528     fprintf(stderr, "Usage: %s <width> <height> <ifile> <ofile> [options]\n", program);
529     fprintf(stderr, "\t<width>  specifies the frame width\n");
530     fprintf(stderr, "\t<height> specifies the frame height\n");
531     fprintf(stderr, "\t<ifile>  specifies the I420/IYUV YUV file\n");
532     fprintf(stderr, "\t<ofile>  specifies the encoded MPEG-2 file\n");
533     fprintf(stderr, "where options include:\n");
534     fprintf(stderr, "\t--cqp <QP>       const qp mode with specified <QP>\n");
535     fprintf(stderr, "\t--fps <FPS>      specify the frame rate\n");
536     fprintf(stderr, "\t--mode <MODE>    specify the mode 0 (I), 1 (I/P) and 2 (I/P/B)\n");
537     fprintf(stderr, "\t--profile <PROFILE>      specify the profile 0(Simple), or 1(Main, default)\n");
538     fprintf(stderr, "\t--level <LEVEL>  specify the level 0(Low), 1(Main, default) or 2(High)\n");    
539 }
540
541 void
542 mpeg2_profile_level(struct mpeg2enc_context *ctx,
543                     int profile,
544                     int level)
545 {
546     int l = 2, p;
547
548     for (p = profile; p < 2; p++) {
549         for (l = level; l < 3; l++) {
550             if (ctx->width <= mpeg2_upper_samplings[p][l].samplers_per_line &&
551                 ctx->height <= mpeg2_upper_samplings[p][l].line_per_frame &&
552                 ctx->fps <= mpeg2_upper_samplings[p][l].frame_per_sec) {
553                 
554                 goto __find;
555                 break;
556             }
557         }
558     }
559
560     if (p == 2) {
561         fprintf(stderr, "Warning: can't find a proper profile and level for the specified width/height/fps\n");
562         p = 1;
563         l = 2;
564     }
565
566 __find:    
567     ctx->profile = mpeg2_va_profiles[p];
568     ctx->level = l;
569 }
570
571 static void 
572 parse_args(struct mpeg2enc_context *ctx, int argc, char **argv)
573 {
574     int c, tmp;
575     int option_index = 0;
576     long file_size;
577     int profile = 1, level = 1;
578
579     static struct option long_options[] = {
580         {"help",        no_argument,            0,      'h'},
581         {"cqp",         required_argument,      0,      'c'},
582         {"fps",         required_argument,      0,      'f'},
583         {"mode",        required_argument,      0,      'm'},
584         {"profile",     required_argument,      0,      'p'},
585         {"level",       required_argument,      0,      'l'},
586         { NULL,         0,                      NULL,   0 }
587     };
588
589     if ((argc == 2 && strcmp(argv[1], "--help") == 0) ||
590         (argc < 5))
591         goto print_usage;
592
593     ctx->width = atoi(argv[1]);
594     ctx->height = atoi(argv[2]);
595
596     if (ctx->width <= 0 || ctx->height <= 0) {
597         fprintf(stderr, "<width> and <height> must be greater than 0\n");
598         goto err_exit;
599     }
600
601     ctx->ifp = fopen(argv[3], "rb");
602
603     if (ctx->ifp == NULL) {
604         fprintf(stderr, "Can't open the input file\n");
605         goto err_exit;
606     }
607
608     fseek(ctx->ifp, 0l, SEEK_END);
609     file_size = ftell(ctx->ifp);
610     ctx->frame_size = ctx->width * ctx->height * 3 / 2;
611
612     if ((file_size < ctx->frame_size) ||
613         (file_size % ctx->frame_size)) {
614         fprintf(stderr, "The input file size %ld isn't a multiple of the frame size %d\n", file_size, ctx->frame_size);
615         goto err_exit;
616     }
617
618     ctx->num_pictures = file_size / ctx->frame_size;
619     fseek(ctx->ifp, 0l, SEEK_SET);
620     
621     ctx->ofp = fopen(argv[4], "wb");
622     
623     if (ctx->ofp == NULL) {
624         fprintf(stderr, "Can't create the output file\n");
625         goto err_exit;
626     }
627
628     opterr = 0;
629     ctx->fps = 30;
630     ctx->qp = 8;
631     ctx->rate_control_mode = VA_RC_CQP;
632     ctx->mode = MPEG2_MODE_IP;
633     ctx->profile = VAProfileMPEG2Main;
634     ctx->level = MPEG2_LEVEL_MAIN;
635
636     optind = 5;
637
638     while((c = getopt_long(argc, argv,
639                            "",
640                            long_options, 
641                            &option_index)) != -1) {
642         switch(c) {
643         case 'c':
644             tmp = atoi(optarg);
645
646             /* only support q_scale_type = 0 */
647             if (tmp > 62 || tmp < 2) {
648                 fprintf(stderr, "Warning: QP must be in [2, 62]\n");
649
650                 if (tmp > 62)
651                     tmp = 62;
652
653                 if (tmp < 2)
654                     tmp = 2;
655             }
656
657             ctx->qp = tmp & 0xFE;
658             ctx->rate_control_mode = VA_RC_CQP;
659
660             break;
661
662         case 'f':
663             tmp = atoi(optarg);
664
665             if (tmp <= 0)
666                 fprintf(stderr, "Warning: FPS must be greater than 0\n");
667             else
668                 ctx->fps = tmp;
669
670             ctx->rate_control_mode = VA_RC_CBR;
671
672             break;
673
674         case 'm':
675             tmp = atoi(optarg);
676             
677             if (tmp < MPEG2_MODE_I || tmp > MPEG2_MODE_IPB)
678                 fprintf(stderr, "Waning: MODE must be 0, 1, or 2\n");
679             else
680                 ctx->mode = tmp;
681
682             break;
683
684         case 'p':
685             tmp = atoi(optarg);
686             
687             if (tmp < 0 || tmp > 1)
688                 fprintf(stderr, "Waning: PROFILE must be 0 or 1\n");
689             else
690                 profile = tmp;
691
692             break;
693
694         case 'l':
695             tmp = atoi(optarg);
696             
697             if (tmp < MPEG2_LEVEL_LOW || tmp > MPEG2_LEVEL_HIGH)
698                 fprintf(stderr, "Waning: LEVEL must be 0, 1, or 2\n");
699             else
700                 level = tmp;
701
702             break;
703
704         case '?':
705             fprintf(stderr, "Error: unkown command options\n");
706
707         case 'h':
708             goto print_usage;
709         }
710     }
711
712     mpeg2_profile_level(ctx, profile, level);
713
714     return;
715
716 print_usage:    
717     usage(argv[0]);
718 err_exit:
719     mpeg2enc_exit(ctx, 1);
720 }
721
722 /*
723  * init
724  */
725 void
726 mpeg2enc_init_sequence_parameter(struct mpeg2enc_context *ctx,
727                                 VAEncSequenceParameterBufferMPEG2 *seq_param)
728 {
729     int profile = 4, level = 8;
730
731     switch (ctx->profile) {
732     case VAProfileMPEG2Simple:
733         profile = 5;
734         break;
735
736     case VAProfileMPEG2Main:
737         profile = 4;
738         break;
739
740     default:
741         assert(0);
742         break;
743     }
744
745     switch (ctx->level) {
746     case MPEG2_LEVEL_LOW:
747         level = 10;
748         break;
749
750     case MPEG2_LEVEL_MAIN:
751         level = 8;
752         break;
753
754     case MPEG2_LEVEL_HIGH:
755         level = 4;
756         break;
757
758     default:
759         assert(0);
760         break;
761     }
762         
763     seq_param->intra_period = ctx->intra_period;
764     seq_param->ip_period = ctx->ip_period;   /* FIXME: ??? */
765     seq_param->picture_width = ctx->width;
766     seq_param->picture_height = ctx->height;
767
768     if (ctx->bit_rate > 0)
769         seq_param->bits_per_second = 1024 * ctx->bit_rate; /* use kbps as input */
770     else
771         seq_param->bits_per_second = 0x3FFFF * 400;
772
773     seq_param->frame_rate = ctx->fps;
774     seq_param->aspect_ratio_information = 1;
775     seq_param->vbv_buffer_size = 3; /* B = 16 * 1024 * vbv_buffer_size */
776
777     seq_param->sequence_extension.bits.profile_and_level_indication = profile << 4 | level;
778     seq_param->sequence_extension.bits.progressive_sequence = 1; /* progressive frame-pictures */
779     seq_param->sequence_extension.bits.chroma_format = CHROMA_FORMAT_420; /* 4:2:0 */
780     seq_param->sequence_extension.bits.low_delay = 0; /* FIXME */
781     seq_param->sequence_extension.bits.frame_rate_extension_n = 0;
782     seq_param->sequence_extension.bits.frame_rate_extension_d = 0;
783
784     seq_param->gop_header.bits.time_code = (1 << 12); /* bit12: marker_bit */
785     seq_param->gop_header.bits.closed_gop = 0;
786     seq_param->gop_header.bits.broken_link = 0;    
787 }
788
789 static void
790 mpeg2enc_init_picture_parameter(struct mpeg2enc_context *ctx,
791                                VAEncPictureParameterBufferMPEG2 *pic_param)
792 {
793     pic_param->forward_reference_picture = VA_INVALID_ID;
794     pic_param->backward_reference_picture = VA_INVALID_ID;
795     pic_param->reconstructed_picture = VA_INVALID_ID;
796     pic_param->coded_buf = VA_INVALID_ID;
797     pic_param->picture_type = VAEncPictureTypeIntra;
798
799     pic_param->temporal_reference = 0;
800     pic_param->f_code[0][0] = 0xf;
801     pic_param->f_code[0][1] = 0xf;
802     pic_param->f_code[1][0] = 0xf;
803     pic_param->f_code[1][1] = 0xf;
804
805     pic_param->picture_coding_extension.bits.intra_dc_precision = 0; /* 8bits */
806     pic_param->picture_coding_extension.bits.picture_structure = 3; /* frame picture */
807     pic_param->picture_coding_extension.bits.top_field_first = 0; 
808     pic_param->picture_coding_extension.bits.frame_pred_frame_dct = 1; /* FIXME */
809     pic_param->picture_coding_extension.bits.concealment_motion_vectors = 0;
810     pic_param->picture_coding_extension.bits.q_scale_type = 0;
811     pic_param->picture_coding_extension.bits.intra_vlc_format = 0;
812     pic_param->picture_coding_extension.bits.alternate_scan = 0;
813     pic_param->picture_coding_extension.bits.repeat_first_field = 0;
814     pic_param->picture_coding_extension.bits.progressive_frame = 1;
815     pic_param->picture_coding_extension.bits.composite_display_flag = 0;
816 }
817
818 static void 
819 mpeg2enc_alloc_va_resources(struct mpeg2enc_context *ctx)
820 {
821     VAEntrypoint *entrypoint_list;
822     VAConfigAttrib attrib_list[2];
823     VAStatus va_status;
824     int max_entrypoints, num_entrypoints, entrypoint;
825     int major_ver, minor_ver;
826
827     ctx->va_dpy = va_open_display();
828     va_status = vaInitialize(ctx->va_dpy,
829                              &major_ver,
830                              &minor_ver);
831     CHECK_VASTATUS(va_status, "vaInitialize");
832
833     max_entrypoints = vaMaxNumEntrypoints(ctx->va_dpy);
834     entrypoint_list = malloc(max_entrypoints * sizeof(VAEntrypoint));
835     vaQueryConfigEntrypoints(ctx->va_dpy,
836                              ctx->profile,
837                              entrypoint_list,
838                              &num_entrypoints);
839
840     for (entrypoint = 0; entrypoint < num_entrypoints; entrypoint++) {
841         if (entrypoint_list[entrypoint] == VAEntrypointEncSlice)
842             break;
843     }
844
845     free(entrypoint_list);
846
847     if (entrypoint == num_entrypoints) {
848         /* not find Slice entry point */
849         assert(0);
850     }
851
852     /* find out the format for the render target, and rate control mode */
853     attrib_list[0].type = VAConfigAttribRTFormat;
854     attrib_list[1].type = VAConfigAttribRateControl;
855     vaGetConfigAttributes(ctx->va_dpy,
856                           ctx->profile,
857                           VAEntrypointEncSlice,
858                           &attrib_list[0],
859                           2);
860
861     if ((attrib_list[0].value & VA_RT_FORMAT_YUV420) == 0) {
862         /* not find desired YUV420 RT format */
863         assert(0);
864     }
865
866     if ((attrib_list[1].value & ctx->rate_control_mode) == 0) {
867         /* Can't find matched RC mode */
868         fprintf(stderr, "RC mode %d isn't found, exit\n", ctx->rate_control_mode);
869         assert(0);
870     }
871
872     attrib_list[0].value = VA_RT_FORMAT_YUV420; /* set to desired RT format */
873     attrib_list[1].value = ctx->rate_control_mode; /* set to desired RC mode */
874
875     va_status = vaCreateConfig(ctx->va_dpy,
876                                ctx->profile,
877                                VAEntrypointEncSlice,
878                                attrib_list,
879                                2,
880                                &ctx->config_id);
881     CHECK_VASTATUS(va_status, "vaCreateConfig");
882
883     /* Create a context for this decode pipe */
884     va_status = vaCreateContext(ctx->va_dpy,
885                                 ctx->config_id,
886                                 ctx->width,
887                                 ctx->height,
888                                 VA_PROGRESSIVE, 
889                                 0,
890                                 0,
891                                 &ctx->context_id);
892     CHECK_VASTATUS(va_status, "vaCreateContext");
893
894     va_status = vaCreateSurfaces(ctx->va_dpy,
895                                  ctx->width,
896                                  ctx->height,
897                                  VA_RT_FORMAT_YUV420,
898                                  SID_NUMBER,
899                                  surface_ids);
900     CHECK_VASTATUS(va_status, "vaCreateSurfaces");
901 }
902
903 static void 
904 mpeg2enc_init(struct mpeg2enc_context *ctx)
905 {
906     int i;
907
908     ctx->frame_data_buffer = (unsigned char *)malloc(ctx->frame_size);
909     ctx->seq_param_buf_id = VA_INVALID_ID;
910     ctx->pic_param_buf_id = VA_INVALID_ID;
911     ctx->packed_seq_header_param_buf_id = VA_INVALID_ID;
912     ctx->packed_seq_buf_id = VA_INVALID_ID;
913     ctx->packed_pic_header_param_buf_id = VA_INVALID_ID;
914     ctx->packed_pic_buf_id = VA_INVALID_ID;
915     ctx->codedbuf_buf_id = VA_INVALID_ID;
916     ctx->codedbuf_i_size = ctx->frame_size;
917     ctx->codedbuf_pb_size = 0;
918     ctx->next_display_order = 0;
919     ctx->next_type = VAEncPictureTypeIntra;
920
921     if (ctx->mode == MPEG2_MODE_I) {
922         ctx->intra_period = 1;
923         ctx->ip_period = 0;
924     } else if (ctx->mode == MPEG2_MODE_IP) {
925         ctx->intra_period = 16;
926         ctx->ip_period = 0;
927     } else {
928         ctx->intra_period = 16;
929         ctx->ip_period = 2;
930     }
931
932     ctx->next_bframes = ctx->ip_period;
933
934     ctx->new_sequence = 1;
935     ctx->new_gop_header = 1;
936     ctx->gop_header_in_display_order = 0;
937
938     ctx->bit_rate = -1;
939
940     for (i = 0; i < MAX_SLICES; i++) {
941         ctx->slice_param_buf_id[i] = VA_INVALID_ID;
942     }
943
944     mpeg2enc_init_sequence_parameter(ctx, &ctx->seq_param);
945     mpeg2enc_init_picture_parameter(ctx, &ctx->pic_param);
946     mpeg2enc_alloc_va_resources(ctx);
947
948     /* thread */
949     ctx->current_input_surface = SID_INPUT_PICTURE_0;
950     ctx->current_upload_surface = SID_INPUT_PICTURE_1;
951     ctx->upload_thread_value = pthread_create(&ctx->upload_thread_id,
952                                               NULL,
953                                               upload_yuv_to_surface,
954                                               ctx);
955 }
956
957 static int 
958 mpeg2enc_time_code(VAEncSequenceParameterBufferMPEG2 *seq_param,
959                    int num_frames)
960 {
961     int fps = (int)(seq_param->frame_rate + 0.5);
962     int time_code = 0;
963     int time_code_pictures, time_code_seconds, time_code_minutes, time_code_hours;
964     int drop_frame_flag = 0;
965
966     assert(fps <= 60);
967
968     time_code_seconds = num_frames / fps;
969     time_code_pictures = num_frames % fps;
970     time_code |= time_code_pictures;
971
972     time_code_minutes = time_code_seconds / 60;
973     time_code_seconds = time_code_seconds % 60;
974     time_code |= (time_code_seconds << 6);
975
976     time_code_hours = time_code_minutes / 60;
977     time_code_minutes = time_code_minutes % 60;
978
979     time_code |= (1 << 12);     /* marker_bit */
980     time_code |= (time_code_minutes << 13);
981
982     time_code_hours = time_code_hours % 24;
983     time_code |= (time_code_hours << 19);
984
985     time_code |= (drop_frame_flag << 24);
986
987     return time_code;
988 }
989
990 /*
991  * run
992  */
993 static void
994 mpeg2enc_update_sequence_parameter(struct mpeg2enc_context *ctx,
995                                    VAEncPictureType picture_type,
996                                    int coded_order,
997                                    int display_order)
998 {
999     VAEncSequenceParameterBufferMPEG2 *seq_param = &ctx->seq_param;
1000
1001     /* update the time_code info for the new GOP */
1002     if (ctx->new_gop_header) {
1003         seq_param->gop_header.bits.time_code = mpeg2enc_time_code(seq_param, display_order);
1004     }
1005 }
1006
1007 static void
1008 mpeg2enc_update_picture_parameter(struct mpeg2enc_context *ctx,
1009                                   VAEncPictureType picture_type,
1010                                   int coded_order,
1011                                   int display_order)
1012 {
1013     VAEncPictureParameterBufferMPEG2 *pic_param = &ctx->pic_param;
1014
1015     pic_param->picture_type = picture_type;
1016     pic_param->temporal_reference = (display_order - ctx->gop_header_in_display_order) & 0x3FF;
1017     pic_param->reconstructed_picture = surface_ids[SID_RECON_PICTURE];
1018     pic_param->forward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L0];
1019     pic_param->backward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L1];
1020
1021     if (pic_param->picture_type == VAEncPictureTypeIntra) {
1022         pic_param->f_code[0][0] = 0xf;
1023         pic_param->f_code[0][1] = 0xf;
1024         pic_param->f_code[1][0] = 0xf;
1025         pic_param->f_code[1][1] = 0xf;
1026         pic_param->forward_reference_picture = VA_INVALID_SURFACE;
1027         pic_param->backward_reference_picture = VA_INVALID_SURFACE;
1028
1029     } else if (pic_param->picture_type == VAEncPictureTypePredictive) {
1030         pic_param->f_code[0][0] = 0x1;
1031         pic_param->f_code[0][1] = 0x1;
1032         pic_param->f_code[1][0] = 0xf;
1033         pic_param->f_code[1][1] = 0xf;
1034         pic_param->forward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L0];
1035         pic_param->backward_reference_picture = VA_INVALID_SURFACE;
1036     } else if (pic_param->picture_type == VAEncPictureTypeBidirectional) {
1037         pic_param->f_code[0][0] = 0x1;
1038         pic_param->f_code[0][1] = 0x1;
1039         pic_param->f_code[1][0] = 0x1;
1040         pic_param->f_code[1][1] = 0x1;
1041         pic_param->forward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L0];
1042         pic_param->backward_reference_picture = surface_ids[SID_REFERENCE_PICTURE_L1];
1043     } else {
1044         assert(0);
1045     }
1046 }
1047
1048 static void
1049 mpeg2enc_update_picture_parameter_buffer(struct mpeg2enc_context *ctx,
1050                                          VAEncPictureType picture_type,
1051                                          int coded_order,
1052                                          int display_order)
1053 {
1054     VAEncPictureParameterBufferMPEG2 *pic_param = &ctx->pic_param;
1055     VAStatus va_status;
1056
1057     /* update the coded buffer id */
1058     pic_param->coded_buf = ctx->codedbuf_buf_id;
1059     va_status = vaCreateBuffer(ctx->va_dpy,
1060                                ctx->context_id,
1061                                VAEncPictureParameterBufferType,
1062                                sizeof(*pic_param),
1063                                1,
1064                                pic_param,
1065                                &ctx->pic_param_buf_id);
1066     CHECK_VASTATUS(va_status, "vaCreateBuffer");
1067 }
1068
1069 static void 
1070 mpeg2enc_update_slice_parameter(struct mpeg2enc_context *ctx, VAEncPictureType picture_type)
1071 {
1072     VAEncSequenceParameterBufferMPEG2 *seq_param;
1073     VAEncPictureParameterBufferMPEG2 *pic_param;
1074     VAEncSliceParameterBufferMPEG2 *slice_param;
1075     VAStatus va_status;
1076     int i, width_in_mbs, height_in_mbs;
1077
1078     pic_param = &ctx->pic_param;
1079     assert(pic_param->picture_coding_extension.bits.q_scale_type == 0);
1080
1081     seq_param = &ctx->seq_param;
1082     width_in_mbs = (seq_param->picture_width + 15) / 16;
1083     height_in_mbs = (seq_param->picture_height + 15) / 16;
1084     ctx->num_slice_groups = 1;
1085
1086     for (i = 0; i < height_in_mbs; i++) {
1087         slice_param = &ctx->slice_param[i];
1088         slice_param->macroblock_address = i * width_in_mbs;
1089         slice_param->num_macroblocks = width_in_mbs;
1090         slice_param->is_intra_slice = (picture_type == VAEncPictureTypeIntra);
1091         slice_param->quantiser_scale_code = ctx->qp / 2;
1092     }
1093
1094     va_status = vaCreateBuffer(ctx->va_dpy,
1095                                ctx->context_id,
1096                                VAEncSliceParameterBufferType,
1097                                sizeof(*slice_param),
1098                                height_in_mbs,
1099                                ctx->slice_param,
1100                                ctx->slice_param_buf_id);
1101     CHECK_VASTATUS(va_status, "vaCreateBuffer");;
1102 }
1103
1104 static int 
1105 begin_picture(struct mpeg2enc_context *ctx,
1106               int coded_order,
1107               int display_order,
1108               VAEncPictureType picture_type)
1109 {
1110     VAStatus va_status;
1111     int tmp;
1112     VAEncPackedHeaderParameterBuffer packed_header_param_buffer;
1113     unsigned int length_in_bits;
1114     unsigned char *packed_seq_buffer = NULL, *packed_pic_buffer = NULL;
1115
1116     if (ctx->upload_thread_value != 0) {
1117         fprintf(stderr, "FATAL error!!!\n");
1118         exit(1);
1119     }
1120     
1121     pthread_join(ctx->upload_thread_id, NULL);
1122
1123     ctx->upload_thread_value = -1;
1124     tmp = ctx->current_input_surface;
1125     ctx->current_input_surface = ctx->current_upload_surface;
1126     ctx->current_upload_surface = tmp;
1127
1128     mpeg2enc_update_sequence_parameter(ctx, picture_type, coded_order, display_order);
1129     mpeg2enc_update_picture_parameter(ctx, picture_type, coded_order, display_order);
1130
1131     if (ctx->new_sequence || ctx->new_gop_header) {
1132         assert(picture_type == VAEncPictureTypeIntra);
1133         length_in_bits = build_packed_seq_buffer(ctx, &ctx->seq_param, &packed_seq_buffer);
1134         packed_header_param_buffer.type = VAEncPackedHeaderMPEG2_SPS;
1135         packed_header_param_buffer.has_emulation_bytes = 0;
1136         packed_header_param_buffer.bit_length = length_in_bits;
1137         va_status = vaCreateBuffer(ctx->va_dpy,
1138                                    ctx->context_id,
1139                                    VAEncPackedHeaderParameterBufferType,
1140                                    sizeof(packed_header_param_buffer), 1, &packed_header_param_buffer,
1141                                    &ctx->packed_seq_header_param_buf_id);
1142         CHECK_VASTATUS(va_status,"vaCreateBuffer");
1143
1144         va_status = vaCreateBuffer(ctx->va_dpy,
1145                                    ctx->context_id,
1146                                    VAEncPackedHeaderDataBufferType,
1147                                    (length_in_bits + 7) / 8, 1, packed_seq_buffer,
1148                                    &ctx->packed_seq_buf_id);
1149         CHECK_VASTATUS(va_status,"vaCreateBuffer");
1150
1151         free(packed_seq_buffer);
1152     }
1153
1154     length_in_bits = build_packed_pic_buffer(&ctx->seq_param, &ctx->pic_param, &packed_pic_buffer);
1155     packed_header_param_buffer.type = VAEncPackedHeaderMPEG2_PPS;
1156     packed_header_param_buffer.has_emulation_bytes = 0;
1157     packed_header_param_buffer.bit_length = length_in_bits;
1158
1159     va_status = vaCreateBuffer(ctx->va_dpy,
1160                                ctx->context_id,
1161                                VAEncPackedHeaderParameterBufferType,
1162                                sizeof(packed_header_param_buffer), 1, &packed_header_param_buffer,
1163                                &ctx->packed_pic_header_param_buf_id);
1164     CHECK_VASTATUS(va_status,"vaCreateBuffer");
1165
1166     va_status = vaCreateBuffer(ctx->va_dpy,
1167                                ctx->context_id,
1168                                VAEncPackedHeaderDataBufferType,
1169                                (length_in_bits + 7) / 8, 1, packed_pic_buffer,
1170                                &ctx->packed_pic_buf_id);
1171     CHECK_VASTATUS(va_status,"vaCreateBuffer");
1172
1173     free(packed_pic_buffer);
1174
1175     /* sequence parameter set */
1176     VAEncSequenceParameterBufferMPEG2 *seq_param = &ctx->seq_param;
1177     va_status = vaCreateBuffer(ctx->va_dpy,
1178                                ctx->context_id,
1179                                VAEncSequenceParameterBufferType,
1180                                sizeof(*seq_param),
1181                                1,
1182                                seq_param,
1183                                &ctx->seq_param_buf_id);
1184     CHECK_VASTATUS(va_status,"vaCreateBuffer");;
1185
1186     /* slice parameter */
1187     mpeg2enc_update_slice_parameter(ctx, picture_type);
1188
1189     return 0;
1190 }
1191
1192 static int 
1193 mpeg2enc_render_picture(struct mpeg2enc_context *ctx)
1194 {
1195     VAStatus va_status;
1196     VABufferID va_buffers[16];
1197     unsigned int num_va_buffers = 0;
1198
1199     va_buffers[num_va_buffers++] = ctx->seq_param_buf_id;
1200     va_buffers[num_va_buffers++] = ctx->pic_param_buf_id;
1201
1202     if (ctx->packed_seq_header_param_buf_id != VA_INVALID_ID)
1203         va_buffers[num_va_buffers++] = ctx->packed_seq_header_param_buf_id;
1204
1205     if (ctx->packed_seq_buf_id != VA_INVALID_ID)
1206         va_buffers[num_va_buffers++] = ctx->packed_seq_buf_id;
1207
1208     if (ctx->packed_pic_header_param_buf_id != VA_INVALID_ID)
1209         va_buffers[num_va_buffers++] = ctx->packed_pic_header_param_buf_id;
1210
1211     if (ctx->packed_pic_buf_id != VA_INVALID_ID)
1212         va_buffers[num_va_buffers++] = ctx->packed_pic_buf_id;
1213
1214     va_status = vaBeginPicture(ctx->va_dpy,
1215                                ctx->context_id,
1216                                surface_ids[ctx->current_input_surface]);
1217     CHECK_VASTATUS(va_status,"vaBeginPicture");
1218
1219     va_status = vaRenderPicture(ctx->va_dpy,
1220                                 ctx->context_id,
1221                                 va_buffers,
1222                                 num_va_buffers);
1223     CHECK_VASTATUS(va_status,"vaRenderPicture");
1224
1225     va_status = vaRenderPicture(ctx->va_dpy,
1226                                 ctx->context_id,
1227                                 &ctx->slice_param_buf_id[0],
1228                                 ctx->num_slice_groups);
1229     CHECK_VASTATUS(va_status,"vaRenderPicture");
1230
1231     va_status = vaEndPicture(ctx->va_dpy, ctx->context_id);
1232     CHECK_VASTATUS(va_status,"vaEndPicture");
1233
1234     return 0;
1235 }
1236
1237 static int 
1238 mpeg2enc_destroy_buffers(struct mpeg2enc_context *ctx, VABufferID *va_buffers, unsigned int num_va_buffers)
1239 {
1240     VAStatus va_status;
1241     unsigned int i;
1242
1243     for (i = 0; i < num_va_buffers; i++) {
1244         if (va_buffers[i] != VA_INVALID_ID) {
1245             va_status = vaDestroyBuffer(ctx->va_dpy, va_buffers[i]);
1246             CHECK_VASTATUS(va_status,"vaDestroyBuffer");
1247             va_buffers[i] = VA_INVALID_ID;
1248         }
1249     }
1250
1251     return 0;
1252 }
1253
1254 static void
1255 end_picture(struct mpeg2enc_context *ctx, VAEncPictureType picture_type, int next_is_bpic)
1256 {
1257     VABufferID tempID;
1258
1259     /* Prepare for next picture */
1260     tempID = surface_ids[SID_RECON_PICTURE];  
1261
1262     if (picture_type != VAEncPictureTypeBidirectional) {
1263         if (next_is_bpic) {
1264             surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L1]; 
1265             surface_ids[SID_REFERENCE_PICTURE_L1] = tempID;     
1266         } else {
1267             surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L0]; 
1268             surface_ids[SID_REFERENCE_PICTURE_L0] = tempID;
1269         }
1270     } else {
1271         if (!next_is_bpic) {
1272             surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L0]; 
1273             surface_ids[SID_REFERENCE_PICTURE_L0] = surface_ids[SID_REFERENCE_PICTURE_L1];
1274             surface_ids[SID_REFERENCE_PICTURE_L1] = tempID;
1275         }
1276     }
1277
1278     mpeg2enc_destroy_buffers(ctx, &ctx->seq_param_buf_id, 1);
1279     mpeg2enc_destroy_buffers(ctx, &ctx->pic_param_buf_id, 1);
1280     mpeg2enc_destroy_buffers(ctx, &ctx->packed_seq_header_param_buf_id, 1);
1281     mpeg2enc_destroy_buffers(ctx, &ctx->packed_seq_buf_id, 1);
1282     mpeg2enc_destroy_buffers(ctx, &ctx->packed_pic_header_param_buf_id, 1);
1283     mpeg2enc_destroy_buffers(ctx, &ctx->packed_pic_buf_id, 1);
1284     mpeg2enc_destroy_buffers(ctx, &ctx->slice_param_buf_id[0], ctx->num_slice_groups);
1285     mpeg2enc_destroy_buffers(ctx, &ctx->codedbuf_buf_id, 1);
1286     memset(ctx->slice_param, 0, sizeof(ctx->slice_param));
1287     ctx->num_slice_groups = 0;
1288 }
1289
1290 static int
1291 store_coded_buffer(struct mpeg2enc_context *ctx, VAEncPictureType picture_type)
1292 {
1293     VACodedBufferSegment *coded_buffer_segment;
1294     unsigned char *coded_mem;
1295     int slice_data_length;
1296     VAStatus va_status;
1297     VASurfaceStatus surface_status;
1298     size_t w_items;
1299
1300     va_status = vaSyncSurface(ctx->va_dpy, surface_ids[ctx->current_input_surface]);
1301     CHECK_VASTATUS(va_status,"vaSyncSurface");
1302
1303     surface_status = 0;
1304     va_status = vaQuerySurfaceStatus(ctx->va_dpy, surface_ids[ctx->current_input_surface], &surface_status);
1305     CHECK_VASTATUS(va_status,"vaQuerySurfaceStatus");
1306
1307     va_status = vaMapBuffer(ctx->va_dpy, ctx->codedbuf_buf_id, (void **)(&coded_buffer_segment));
1308     CHECK_VASTATUS(va_status,"vaMapBuffer");
1309     coded_mem = coded_buffer_segment->buf;
1310
1311     if (coded_buffer_segment->status & VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK) {
1312         if (picture_type == VAEncPictureTypeIntra)
1313             ctx->codedbuf_i_size *= 2;
1314         else
1315             ctx->codedbuf_pb_size *= 2;
1316
1317         vaUnmapBuffer(ctx->va_dpy, ctx->codedbuf_buf_id);
1318         return -1;
1319     }
1320
1321     slice_data_length = coded_buffer_segment->size;
1322
1323     do {
1324         w_items = fwrite(coded_mem, slice_data_length, 1, ctx->ofp);
1325     } while (w_items != 1);
1326
1327     if (picture_type == VAEncPictureTypeIntra) {
1328         if (ctx->codedbuf_i_size > slice_data_length * 3 / 2) {
1329             ctx->codedbuf_i_size = slice_data_length * 3 / 2;
1330         }
1331         
1332         if (ctx->codedbuf_pb_size < slice_data_length) {
1333             ctx->codedbuf_pb_size = slice_data_length;
1334         }
1335     } else {
1336         if (ctx->codedbuf_pb_size > slice_data_length * 3 / 2) {
1337             ctx->codedbuf_pb_size = slice_data_length * 3 / 2;
1338         }
1339     }
1340
1341     vaUnmapBuffer(ctx->va_dpy, ctx->codedbuf_buf_id);
1342
1343     return 0;
1344 }
1345
1346 static void
1347 encode_picture(struct mpeg2enc_context *ctx,
1348                int coded_order,
1349                int display_order,
1350                VAEncPictureType picture_type,
1351                int next_is_bpic,
1352                int next_display_order)
1353 {
1354     VAStatus va_status;
1355     int ret = 0, codedbuf_size;
1356     
1357     begin_picture(ctx, coded_order, display_order, picture_type);
1358
1359     if (1) {
1360         /* upload YUV data to VA surface for next frame */
1361         if (next_display_order >= ctx->num_pictures)
1362             next_display_order = ctx->num_pictures - 1;
1363
1364         fseek(ctx->ifp, ctx->frame_size * next_display_order, SEEK_SET);
1365         ctx->upload_thread_value = pthread_create(&ctx->upload_thread_id,
1366                                                   NULL,
1367                                                   upload_yuv_to_surface,
1368                                                   ctx);
1369     }
1370
1371     do {
1372         mpeg2enc_destroy_buffers(ctx, &ctx->codedbuf_buf_id, 1);
1373         mpeg2enc_destroy_buffers(ctx, &ctx->pic_param_buf_id, 1);
1374
1375
1376         if (VAEncPictureTypeIntra == picture_type) {
1377             codedbuf_size = ctx->codedbuf_i_size;
1378         } else {
1379             codedbuf_size = ctx->codedbuf_pb_size;
1380         }
1381
1382         /* coded buffer */
1383         va_status = vaCreateBuffer(ctx->va_dpy,
1384                                    ctx->context_id,
1385                                    VAEncCodedBufferType,
1386                                    codedbuf_size, 1, NULL,
1387                                    &ctx->codedbuf_buf_id);
1388         CHECK_VASTATUS(va_status,"vaCreateBuffer");
1389
1390         /* picture parameter set */
1391         mpeg2enc_update_picture_parameter_buffer(ctx, picture_type, coded_order, display_order);
1392
1393         mpeg2enc_render_picture(ctx);
1394
1395         ret = store_coded_buffer(ctx, picture_type);
1396     } while (ret);
1397
1398     end_picture(ctx, picture_type, next_is_bpic);
1399 }
1400
1401 static void
1402 update_next_frame_info(struct mpeg2enc_context *ctx,
1403                        VAEncPictureType curr_type,
1404                        int curr_coded_order,
1405                        int curr_display_order)
1406 {
1407     if (((curr_coded_order + 1) % ctx->intra_period) == 0) {
1408         ctx->next_type = VAEncPictureTypeIntra;
1409         ctx->next_display_order = curr_coded_order + 1;
1410         
1411         return;
1412     }
1413
1414     if (curr_type == VAEncPictureTypeIntra) {
1415         assert(curr_display_order == curr_coded_order);
1416         ctx->next_type = VAEncPictureTypePredictive;
1417         ctx->next_bframes = ctx->ip_period;
1418         ctx->next_display_order = curr_display_order + ctx->next_bframes + 1;
1419     } else if (curr_type == VAEncPictureTypePredictive) {
1420         if (ctx->ip_period == 0) {
1421             assert(curr_display_order == curr_coded_order);
1422             ctx->next_type = VAEncPictureTypePredictive;
1423             ctx->next_display_order = curr_display_order + 1;
1424         } else {
1425             ctx->next_type = VAEncPictureTypeBidirectional;
1426             ctx->next_display_order = curr_display_order - ctx->next_bframes;
1427             ctx->next_bframes--;
1428         }
1429     } else if (curr_type == VAEncPictureTypeBidirectional) {
1430         if (ctx->next_bframes == 0) {
1431             ctx->next_type = VAEncPictureTypePredictive;
1432             ctx->next_bframes = ctx->ip_period;
1433             ctx->next_display_order = curr_display_order + ctx->next_bframes + 2;
1434         } else {
1435             ctx->next_type = VAEncPictureTypeBidirectional;
1436             ctx->next_display_order = curr_display_order + 1;
1437             ctx->next_bframes--;
1438         }
1439     }
1440
1441     if (ctx->next_display_order >= ctx->num_pictures) {
1442         int rtmp = ctx->next_display_order - (ctx->num_pictures - 1);
1443         ctx->next_display_order = ctx->num_pictures - 1;
1444         ctx->next_bframes -= rtmp;
1445     }
1446 }
1447
1448 static void
1449 mpeg2enc_run(struct mpeg2enc_context *ctx)
1450 {
1451     int display_order = 0, coded_order = 0;
1452     VAEncPictureType type;
1453
1454     ctx->new_sequence = 1;
1455     ctx->new_gop_header = 1;
1456     ctx->gop_header_in_display_order = display_order;
1457
1458     while (coded_order < ctx->num_pictures) {
1459         type = ctx->next_type;
1460         display_order = ctx->next_display_order;
1461         /* follow the IPBxxBPBxxB mode */
1462         update_next_frame_info(ctx, type, coded_order, display_order);
1463         encode_picture(ctx,
1464                        coded_order,
1465                        display_order,
1466                        type,
1467                        ctx->next_type == VAEncPictureTypeBidirectional,
1468                        ctx->next_display_order);
1469
1470         /* update gop_header */
1471         ctx->new_sequence = 0;
1472         ctx->new_gop_header = ctx->next_type == VAEncPictureTypeIntra;
1473
1474         if (ctx->new_gop_header)
1475             ctx->gop_header_in_display_order += ctx->intra_period;
1476
1477         coded_order++;
1478
1479         fprintf(stderr, "\r %d/%d ...", coded_order, ctx->num_pictures);
1480         fflush(stdout);
1481     }
1482 }
1483
1484 /*
1485  * end
1486  */
1487 static void
1488 mpeg2enc_release_va_resources(struct mpeg2enc_context *ctx)
1489 {
1490     vaDestroySurfaces(ctx->va_dpy, surface_ids, SID_NUMBER);    
1491     vaDestroyContext(ctx->va_dpy, ctx->context_id);
1492     vaDestroyConfig(ctx->va_dpy, ctx->config_id);
1493     vaTerminate(ctx->va_dpy);
1494     va_close_display(ctx->va_dpy);
1495 }
1496
1497 static void
1498 mpeg2enc_end(struct mpeg2enc_context *ctx)
1499 {
1500     pthread_join(ctx->upload_thread_id, NULL);
1501     mpeg2enc_release_va_resources(ctx);
1502 }
1503
1504 int 
1505 main(int argc, char *argv[])
1506 {
1507     struct mpeg2enc_context ctx;
1508     struct timeval tpstart, tpend; 
1509     float timeuse;
1510
1511     gettimeofday(&tpstart, NULL);
1512
1513     memset(&ctx, 0, sizeof(ctx));
1514     parse_args(&ctx, argc, argv);
1515     mpeg2enc_init(&ctx);
1516     mpeg2enc_run(&ctx);
1517     mpeg2enc_end(&ctx);
1518
1519     gettimeofday(&tpend, NULL);
1520     timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
1521     timeuse /= 1000000;
1522     fprintf(stderr, "\ndone!\n");
1523     fprintf(stderr, "encode %d frames in %f secondes, FPS is %.1f\n", ctx.num_pictures, timeuse, ctx.num_pictures / timeuse);
1524
1525     mpeg2enc_exit(&ctx, 0);
1526
1527     return 0;
1528 }