OSDN Git Service

avcenc: correct the description for the mode parameter
[android-x86/hardware-intel-common-libva.git] / test / encode / avcenc.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 AVC encoder based on libVA.
26  *
27  * Usage:
28  * ./avcenc <width> <height> <input file> <output file> [qp]
29  */  
30
31 #include "sysdeps.h"
32 #include <stdio.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include <getopt.h>
36 #include <unistd.h>
37
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42 #include <assert.h>
43 #include <time.h>
44
45 #include <pthread.h>
46
47 #include <va/va.h>
48 #include "va_display.h"
49
50 #define NAL_REF_IDC_NONE        0
51 #define NAL_REF_IDC_LOW         1
52 #define NAL_REF_IDC_MEDIUM      2
53 #define NAL_REF_IDC_HIGH        3
54
55 #define NAL_NON_IDR             1
56 #define NAL_IDR                 5
57 #define NAL_SPS                 7
58 #define NAL_PPS                 8
59
60 #define SLICE_TYPE_P            0
61 #define SLICE_TYPE_B            1
62 #define SLICE_TYPE_I            2
63
64 #define ENTROPY_MODE_CAVLC      0
65 #define ENTROPY_MODE_CABAC      1
66
67 #define PROFILE_IDC_BASELINE    66
68 #define PROFILE_IDC_MAIN        77
69 #define PROFILE_IDC_HIGH        100
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 VADisplay va_dpy;
78
79 static int picture_width, picture_width_in_mbs;
80 static int picture_height, picture_height_in_mbs;
81 static int frame_size;
82 static unsigned char *newImageBuffer = 0;
83
84 static int qp_value = 26;
85
86 static int intra_period = 30;
87 static int pb_period = 5;
88 static int frame_bit_rate = -1;
89
90 #define BR_CBR          0
91 #define BR_VBR          1
92 #define BR_CQP          2
93
94 #define MAX_SLICES      32
95
96 static int
97 build_packed_pic_buffer(unsigned char **header_buffer);
98
99 static int
100 build_packed_seq_buffer(unsigned char **header_buffer);
101
102 struct upload_thread_param
103 {
104     FILE *yuv_fp;
105     VASurfaceID surface_id;
106 };
107
108 static void 
109 upload_yuv_to_surface(FILE *yuv_fp, VASurfaceID surface_id);
110
111 struct packed_data_format
112 {
113     unsigned int length_in_bits;
114     unsigned char flag;
115     unsigned char num_skip_bytes;
116     unsigned char pad[2];
117 };
118
119 struct {
120     VAEncSequenceParameterBufferH264Ext seq_param;
121     VAEncPictureParameterBufferH264Ext pic_param;
122     VAEncSliceParameterBufferH264Ext slice_param[MAX_SLICES];
123     VAEncH264DecRefPicMarkingBuffer dec_ref_pic_marking;
124     VAContextID context_id;
125     VAConfigID config_id;
126     VABufferID seq_param_buf_id;                /* Sequence level parameter */
127     VABufferID pic_param_buf_id;                /* Picture level parameter */
128     VABufferID slice_param_buf_id[MAX_SLICES];  /* Slice level parameter, multil slices */
129     VABufferID dec_ref_pic_marking_buf_id;
130     VABufferID codedbuf_buf_id;                 /* Output buffer, compressed data */
131     VABufferID packed_seq_buf_id;
132     VABufferID packed_pic_buf_id;
133     int num_slices;
134     int codedbuf_i_size;
135     int codedbuf_pb_size;
136     int current_input_surface;
137     struct upload_thread_param upload_thread_param;
138     pthread_t upload_thread_id;
139     int upload_thread_value;
140 } avcenc_context;
141
142 static void create_encode_pipe()
143 {
144     VAEntrypoint entrypoints[5];
145     int num_entrypoints,slice_entrypoint;
146     VAConfigAttrib attrib[2];
147     int major_ver, minor_ver;
148     VAStatus va_status;
149
150     va_dpy = va_open_display();
151     va_status = vaInitialize(va_dpy, &major_ver, &minor_ver);
152     CHECK_VASTATUS(va_status, "vaInitialize");
153
154     vaQueryConfigEntrypoints(va_dpy, VAProfileH264Baseline, entrypoints, 
155                              &num_entrypoints);
156
157     for (slice_entrypoint = 0; slice_entrypoint < num_entrypoints; slice_entrypoint++) {
158         if (entrypoints[slice_entrypoint] == VAEntrypointEncSlice)
159             break;
160     }
161
162     if (slice_entrypoint == num_entrypoints) {
163         /* not find Slice entry point */
164         assert(0);
165     }
166
167     /* find out the format for the render target, and rate control mode */
168     attrib[0].type = VAConfigAttribRTFormat;
169     attrib[1].type = VAConfigAttribRateControl;
170     vaGetConfigAttributes(va_dpy, VAProfileH264Baseline, VAEntrypointEncSlice,
171                           &attrib[0], 2);
172
173     if ((attrib[0].value & VA_RT_FORMAT_YUV420) == 0) {
174         /* not find desired YUV420 RT format */
175         assert(0);
176     }
177
178     if ((attrib[1].value & VA_RC_VBR) == 0) {
179         /* Can't find matched RC mode */
180         printf("VBR mode doesn't found, exit\n");
181         assert(0);
182     }
183
184     attrib[0].value = VA_RT_FORMAT_YUV420; /* set to desired RT format */
185     attrib[1].value = VA_RC_VBR; /* set to desired RC mode */
186
187     va_status = vaCreateConfig(va_dpy, VAProfileH264Baseline, VAEntrypointEncSlice,
188                                &attrib[0], 2,&avcenc_context.config_id);
189     CHECK_VASTATUS(va_status, "vaCreateConfig");
190
191     /* Create a context for this decode pipe */
192     va_status = vaCreateContext(va_dpy, avcenc_context.config_id,
193                                 picture_width, picture_height,
194                                 VA_PROGRESSIVE, 
195                                 0, 0,
196                                 &avcenc_context.context_id);
197     CHECK_VASTATUS(va_status, "vaCreateContext");
198 }
199
200 static void destory_encode_pipe()
201 {
202     vaDestroyContext(va_dpy,avcenc_context.context_id);
203     vaDestroyConfig(va_dpy,avcenc_context.config_id);
204     vaTerminate(va_dpy);
205     va_close_display(va_dpy);
206 }
207
208 /***************************************************
209  *
210  *  The encode pipe resource define 
211  *
212  ***************************************************/
213 #define SID_INPUT_PICTURE_0                     0
214 #define SID_INPUT_PICTURE_1                     1
215 #define SID_REFERENCE_PICTURE_L0                2
216 #define SID_REFERENCE_PICTURE_L1                3
217 #define SID_RECON_PICTURE                       4
218 #define SID_NUMBER                              SID_RECON_PICTURE + 1
219 static  VASurfaceID surface_ids[SID_NUMBER];
220
221 static int frame_number;
222 static int enc_frame_number;
223
224 /***************************************************/
225
226 static void *
227 upload_thread_function(void *data)
228 {
229     struct upload_thread_param *param = data;
230
231     upload_yuv_to_surface(param->yuv_fp, param->surface_id);
232
233     return NULL;
234 }
235
236 static void alloc_encode_resource(FILE *yuv_fp)
237 {
238     VAStatus va_status;
239
240     // Create surface
241     va_status = vaCreateSurfaces(va_dpy, picture_width, picture_height,
242                                  VA_RT_FORMAT_YUV420, SID_NUMBER, &surface_ids[0]);
243     CHECK_VASTATUS(va_status, "vaCreateSurfaces");
244
245     newImageBuffer = (unsigned char *)malloc(frame_size);
246
247     /* firstly upload YUV data to SID_INPUT_PICTURE_1 */
248     avcenc_context.upload_thread_param.yuv_fp = yuv_fp;
249     avcenc_context.upload_thread_param.surface_id = surface_ids[SID_INPUT_PICTURE_1];
250
251     avcenc_context.upload_thread_value = pthread_create(&avcenc_context.upload_thread_id,
252                                                         NULL,
253                                                         upload_thread_function, 
254                                                         (void*)&avcenc_context.upload_thread_param);
255 }
256
257 static void release_encode_resource()
258 {
259     free(newImageBuffer);
260
261     // Release all the surfaces resource
262     vaDestroySurfaces(va_dpy, &surface_ids[0], SID_NUMBER);     
263 }
264
265 static void avcenc_update_picture_parameter(int slice_type, int frame_num, int display_num, int is_idr)
266 {
267     VAEncPictureParameterBufferH264Ext *pic_param;
268     VAStatus va_status;
269
270     // Picture level
271     pic_param = &avcenc_context.pic_param;
272     pic_param->CurrPic.picture_id = surface_ids[SID_RECON_PICTURE];
273     pic_param->CurrPic.TopFieldOrderCnt = display_num * 2;
274     pic_param->ReferenceFrames[0].picture_id = surface_ids[SID_REFERENCE_PICTURE_L0];
275     pic_param->ReferenceFrames[1].picture_id = surface_ids[SID_REFERENCE_PICTURE_L1];
276     pic_param->ReferenceFrames[2].picture_id = VA_INVALID_ID;
277     assert(avcenc_context.codedbuf_buf_id != VA_INVALID_ID);
278     pic_param->CodedBuf = avcenc_context.codedbuf_buf_id;
279     pic_param->frame_num = frame_num;
280     pic_param->pic_fields.bits.idr_pic_flag = !!is_idr;
281     pic_param->pic_fields.bits.reference_pic_flag = (slice_type != SLICE_TYPE_B);
282
283     va_status = vaCreateBuffer(va_dpy,
284                                avcenc_context.context_id,
285                                VAEncPictureParameterBufferExtType,
286                                sizeof(*pic_param), 1, pic_param,
287                                &avcenc_context.pic_param_buf_id);
288     CHECK_VASTATUS(va_status,"vaCreateBuffer");
289 }
290
291 static void upload_yuv_to_surface(FILE *yuv_fp, VASurfaceID surface_id)
292 {
293     VAImage surface_image;
294     VAStatus va_status;
295     void *surface_p = NULL;
296     unsigned char *y_src, *u_src, *v_src;
297     unsigned char *y_dst, *u_dst, *v_dst;
298     int y_size = picture_width * picture_height;
299     int u_size = (picture_width >> 1) * (picture_height >> 1);
300     int row, col;
301     size_t n_items;
302
303     do {
304         n_items = fread(newImageBuffer, frame_size, 1, yuv_fp);
305     } while (n_items != 1);
306
307     va_status = vaDeriveImage(va_dpy, surface_id, &surface_image);
308     CHECK_VASTATUS(va_status,"vaDeriveImage");
309
310     vaMapBuffer(va_dpy, surface_image.buf, &surface_p);
311     assert(VA_STATUS_SUCCESS == va_status);
312         
313     y_src = newImageBuffer;
314     u_src = newImageBuffer + y_size; /* UV offset for NV12 */
315     v_src = newImageBuffer + y_size + u_size;
316
317     y_dst = surface_p + surface_image.offsets[0];
318     u_dst = surface_p + surface_image.offsets[1]; /* UV offset for NV12 */
319     v_dst = surface_p + surface_image.offsets[2];
320
321     /* Y plane */
322     for (row = 0; row < surface_image.height; row++) {
323         memcpy(y_dst, y_src, surface_image.width);
324         y_dst += surface_image.pitches[0];
325         y_src += picture_width;
326     }
327
328     if (surface_image.format.fourcc == VA_FOURCC_NV12) { /* UV plane */
329         for (row = 0; row < surface_image.height / 2; row++) {
330             for (col = 0; col < surface_image.width / 2; col++) {
331                 u_dst[col * 2] = u_src[col];
332                 u_dst[col * 2 + 1] = v_src[col];
333             }
334
335             u_dst += surface_image.pitches[1];
336             u_src += (picture_width / 2);
337             v_src += (picture_width / 2);
338         }
339     } else {
340         /* FIXME: fix this later */
341         assert(0);
342     }
343
344     vaUnmapBuffer(va_dpy, surface_image.buf);
345     vaDestroyImage(va_dpy, surface_image.image_id);
346 }
347
348 static void avcenc_update_slice_parameter(int slice_type)
349 {
350     VAEncSliceParameterBufferH264Ext *slice_param;
351     VAStatus va_status;
352     int i;
353
354     // Slice level
355     i = 0;
356     slice_param = &avcenc_context.slice_param[i];
357     slice_param->start_row_number = 0;
358     slice_param->slice_height = picture_height_in_mbs/16; /* Measured by MB */
359     slice_param->pic_parameter_set_id = 0;
360     slice_param->slice_type = slice_type;
361     slice_param->direct_spatial_mv_pred_flag = 0;
362     slice_param->num_ref_idx_l0_active_minus1 = 0;      /* FIXME: ??? */
363     slice_param->num_ref_idx_l1_active_minus1 = 0;
364     slice_param->cabac_init_idc = 0;
365     slice_param->slice_qp_delta = 0;
366     slice_param->disable_deblocking_filter_idc = 0;
367     slice_param->slice_alpha_c0_offset_div2 = 2;
368     slice_param->slice_beta_offset_div2 = 2;
369     slice_param->idr_pic_id = 0;
370
371     /* ref_pic_list_modification() */
372     slice_param->ref_pic_list_modification_flag_l0 = 0;
373     slice_param->ref_pic_list_modification_flag_l1 = 0;
374     /* FIXME: fill other fields */
375
376     va_status = vaCreateBuffer(va_dpy,
377                                avcenc_context.context_id,
378                                VAEncSliceParameterBufferExtType,
379                                sizeof(*slice_param), 1, slice_param,
380                                &avcenc_context.slice_param_buf_id[i]);
381     CHECK_VASTATUS(va_status,"vaCreateBuffer");;
382
383     i++;
384
385     avcenc_context.num_slices = i;
386 }
387
388 static int begin_picture(FILE *yuv_fp, int frame_num, int display_num, int slice_type, int is_idr)
389 {
390     VAStatus va_status;
391
392     if (avcenc_context.upload_thread_value != 0) {
393         fprintf(stderr, "FATAL error!!!\n");
394         exit(1);
395     }
396     
397     pthread_join(avcenc_context.upload_thread_id, NULL);
398
399     avcenc_context.upload_thread_value = -1;
400
401     if (avcenc_context.current_input_surface == SID_INPUT_PICTURE_0)
402         avcenc_context.current_input_surface = SID_INPUT_PICTURE_1;
403     else
404         avcenc_context.current_input_surface = SID_INPUT_PICTURE_0;
405
406     if (frame_num == 0) {
407         unsigned char *packed_seq_buffer = NULL, *packed_pic_buffer = NULL;
408         int seq_length, pic_length;
409
410         assert(slice_type == SLICE_TYPE_I);
411         seq_length = build_packed_seq_buffer(&packed_seq_buffer);
412         va_status = vaCreateBuffer(va_dpy,
413                                    avcenc_context.context_id,
414                                    VAEncPackedSequenceParameterBufferType,
415                                    (seq_length + 7) / 8, 1, packed_seq_buffer,
416                                    &avcenc_context.packed_seq_buf_id);
417         CHECK_VASTATUS(va_status,"vaCreateBuffer");;
418
419         pic_length = build_packed_pic_buffer(&packed_pic_buffer);
420         va_status = vaCreateBuffer(va_dpy,
421                                    avcenc_context.context_id,
422                                    VAEncPackedPictureParameterBufferType,
423                                    (pic_length + 7) / 8 , 1, packed_pic_buffer,
424                                    &avcenc_context.packed_pic_buf_id);
425         CHECK_VASTATUS(va_status,"vaCreateBuffer");;
426
427         free(packed_seq_buffer);
428         free(packed_pic_buffer);
429     }
430
431     /* sequence parameter set */
432     VAEncSequenceParameterBufferH264Ext *seq_param = &avcenc_context.seq_param;
433     va_status = vaCreateBuffer(va_dpy,
434                                avcenc_context.context_id,
435                                VAEncSequenceParameterBufferExtType,
436                                sizeof(*seq_param), 1, seq_param,
437                                &avcenc_context.seq_param_buf_id);
438     CHECK_VASTATUS(va_status,"vaCreateBuffer");;
439
440     /* slice parameter */
441     avcenc_update_slice_parameter(slice_type);
442
443     return 0;
444 }
445
446 int avcenc_render_picture()
447 {
448     VAStatus va_status;
449     VABufferID va_buffers[8];
450     unsigned int num_va_buffers = 0;
451
452     va_buffers[num_va_buffers++] = avcenc_context.seq_param_buf_id;
453     va_buffers[num_va_buffers++] = avcenc_context.pic_param_buf_id;
454
455     if (avcenc_context.dec_ref_pic_marking_buf_id != VA_INVALID_ID)
456         va_buffers[num_va_buffers++] = avcenc_context.dec_ref_pic_marking_buf_id;
457
458     if (avcenc_context.packed_seq_buf_id != VA_INVALID_ID)
459         va_buffers[num_va_buffers++] = avcenc_context.packed_seq_buf_id;
460
461     if (avcenc_context.packed_pic_buf_id != VA_INVALID_ID)
462         va_buffers[num_va_buffers++] = avcenc_context.packed_pic_buf_id;
463
464     va_status = vaBeginPicture(va_dpy,
465                                avcenc_context.context_id,
466                                surface_ids[avcenc_context.current_input_surface]);
467     CHECK_VASTATUS(va_status,"vaBeginPicture");
468
469     va_status = vaRenderPicture(va_dpy,
470                                 avcenc_context.context_id,
471                                 va_buffers,
472                                 num_va_buffers);
473     CHECK_VASTATUS(va_status,"vaRenderPicture");
474
475     va_status = vaRenderPicture(va_dpy,
476                                 avcenc_context.context_id,
477                                 &avcenc_context.slice_param_buf_id[0],
478                                 avcenc_context.num_slices);
479     CHECK_VASTATUS(va_status,"vaRenderPicture");
480
481     va_status = vaEndPicture(va_dpy, avcenc_context.context_id);
482     CHECK_VASTATUS(va_status,"vaEndPicture");
483
484     return 0;
485 }
486
487 static int avcenc_destroy_buffers(VABufferID *va_buffers, unsigned int num_va_buffers)
488 {
489     VAStatus va_status;
490     unsigned int i;
491
492     for (i = 0; i < num_va_buffers; i++) {
493         if (va_buffers[i] != VA_INVALID_ID) {
494             va_status = vaDestroyBuffer(va_dpy, va_buffers[i]);
495             CHECK_VASTATUS(va_status,"vaDestroyBuffer");
496             va_buffers[i] = VA_INVALID_ID;
497         }
498     }
499
500     return 0;
501 }
502
503 static void end_picture(int slice_type, int next_is_bpic)
504 {
505     VABufferID tempID;
506
507     /* Prepare for next picture */
508     tempID = surface_ids[SID_RECON_PICTURE];  
509
510     if (slice_type != SLICE_TYPE_B) {
511         if (next_is_bpic) {
512             surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L1]; 
513             surface_ids[SID_REFERENCE_PICTURE_L1] = tempID;     
514         } else {
515             surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L0]; 
516             surface_ids[SID_REFERENCE_PICTURE_L0] = tempID;
517         }
518     } else {
519         if (!next_is_bpic) {
520             surface_ids[SID_RECON_PICTURE] = surface_ids[SID_REFERENCE_PICTURE_L0]; 
521             surface_ids[SID_REFERENCE_PICTURE_L0] = surface_ids[SID_REFERENCE_PICTURE_L1];
522             surface_ids[SID_REFERENCE_PICTURE_L1] = tempID;
523         }
524     }
525
526     avcenc_destroy_buffers(&avcenc_context.seq_param_buf_id, 1);
527     avcenc_destroy_buffers(&avcenc_context.pic_param_buf_id, 1);
528     avcenc_destroy_buffers(&avcenc_context.dec_ref_pic_marking_buf_id, 1);
529     avcenc_destroy_buffers(&avcenc_context.packed_seq_buf_id, 1);
530     avcenc_destroy_buffers(&avcenc_context.packed_pic_buf_id, 1);
531     avcenc_destroy_buffers(&avcenc_context.slice_param_buf_id[0], avcenc_context.num_slices);
532     avcenc_destroy_buffers(&avcenc_context.codedbuf_buf_id, 1);
533     memset(avcenc_context.slice_param, 0, sizeof(avcenc_context.slice_param));
534     avcenc_context.num_slices = 0;
535 }
536
537 #define BITSTREAM_ALLOCATE_STEPPING     4096
538
539 struct __bitstream {
540     unsigned int *buffer;
541     int bit_offset;
542     int max_size_in_dword;
543 };
544
545 typedef struct __bitstream bitstream;
546
547 #if 0
548 static int 
549 get_coded_bitsteam_length(unsigned char *buffer, int buffer_length)
550 {
551     int i;
552
553     for (i = 0; i < buffer_length - 3; i++) {
554         if (!buffer[i] &&
555             !buffer[i + 1] &&
556             !buffer[i + 2] &&
557             !buffer[i + 3])
558             break;
559     }
560
561     return i;
562 }
563 #endif
564
565 static unsigned int 
566 va_swap32(unsigned int val)
567 {
568     unsigned char *pval = (unsigned char *)&val;
569
570     return ((pval[0] << 24)     |
571             (pval[1] << 16)     |
572             (pval[2] << 8)      |
573             (pval[3] << 0));
574 }
575
576 static void
577 bitstream_start(bitstream *bs)
578 {
579     bs->max_size_in_dword = BITSTREAM_ALLOCATE_STEPPING;
580     bs->buffer = calloc(bs->max_size_in_dword * sizeof(int), 1);
581     bs->bit_offset = sizeof(struct packed_data_format) * 8; /* the first 64 bits used for format */
582 }
583
584 static void
585 bitstream_end(bitstream *bs)
586 {
587     int pos = (bs->bit_offset >> 5);
588     int bit_offset = (bs->bit_offset & 0x1f);
589     int bit_left = 32 - bit_offset;
590     struct packed_data_format *format;
591
592     if (bit_offset) {
593         bs->buffer[pos] = va_swap32((bs->buffer[pos] << bit_left));
594     }
595
596     format = (struct packed_data_format *)bs->buffer;
597     format->length_in_bits = bs->bit_offset - sizeof(struct packed_data_format) * 8;
598     format->flag |= 1;
599     format->num_skip_bytes = 5; /* ignore start code & nal type for emulation prevetion check */
600 }
601  
602 static void
603 bitstream_put_ui(bitstream *bs, unsigned int val, int size_in_bits)
604 {
605     int pos = (bs->bit_offset >> 5);
606     int bit_offset = (bs->bit_offset & 0x1f);
607     int bit_left = 32 - bit_offset;
608
609     if (!size_in_bits)
610         return;
611
612     bs->bit_offset += size_in_bits;
613
614     if (bit_left > size_in_bits) {
615         bs->buffer[pos] = (bs->buffer[pos] << size_in_bits | val);
616     } else {
617         size_in_bits -= bit_left;
618         bs->buffer[pos] = (bs->buffer[pos] << bit_left) | (val >> size_in_bits);
619         bs->buffer[pos] = va_swap32(bs->buffer[pos]);
620
621         if (pos + 1 == bs->max_size_in_dword) {
622             bs->max_size_in_dword += BITSTREAM_ALLOCATE_STEPPING;
623             bs->buffer = realloc(bs->buffer, bs->max_size_in_dword * sizeof(unsigned int));
624         }
625
626         bs->buffer[pos + 1] = val;
627     }
628 }
629
630 static void
631 bitstream_put_ue(bitstream *bs, unsigned int val)
632 {
633     int size_in_bits = 0;
634     int tmp_val = ++val;
635
636     while (tmp_val) {
637         tmp_val >>= 1;
638         size_in_bits++;
639     }
640
641     bitstream_put_ui(bs, 0, size_in_bits - 1); // leading zero
642     bitstream_put_ui(bs, val, size_in_bits);
643 }
644
645 static void
646 bitstream_put_se(bitstream *bs, int val)
647 {
648     unsigned int new_val;
649
650     if (val <= 0)
651         new_val = -2 * val;
652     else
653         new_val = 2 * val - 1;
654
655     bitstream_put_ue(bs, new_val);
656 }
657
658 static void
659 bitstream_byte_aligning(bitstream *bs, int bit)
660 {
661     int bit_offset = (bs->bit_offset & 0x7);
662     int bit_left = 8 - bit_offset;
663     int new_val;
664
665     if (!bit_offset)
666         return;
667
668     assert(bit == 0 || bit == 1);
669
670     if (bit)
671         new_val = (1 << bit_left) - 1;
672     else
673         new_val = 0;
674
675     bitstream_put_ui(bs, new_val, bit_left);
676 }
677
678 static void 
679 rbsp_trailing_bits(bitstream *bs)
680 {
681     bitstream_put_ui(bs, 1, 1);
682     bitstream_byte_aligning(bs, 0);
683 }
684
685 static void nal_start_code_prefix(bitstream *bs)
686 {
687     bitstream_put_ui(bs, 0x00000001, 32);
688 }
689
690 static void nal_header(bitstream *bs, int nal_ref_idc, int nal_unit_type)
691 {
692     bitstream_put_ui(bs, 0, 1);                /* forbidden_zero_bit: 0 */
693     bitstream_put_ui(bs, nal_ref_idc, 2);
694     bitstream_put_ui(bs, nal_unit_type, 5);
695 }
696
697 static void sps_rbsp(bitstream *bs)
698 {
699     VAEncSequenceParameterBufferH264Ext *seq_param = &avcenc_context.seq_param;
700
701     bitstream_put_ui(bs, seq_param->profile_idc, 8);    /* profile_idc */
702     bitstream_put_ui(bs, 0, 1);                         /* constraint_set0_flag */
703     bitstream_put_ui(bs, 1, 1);                         /* constraint_set1_flag */
704     bitstream_put_ui(bs, 0, 1);                         /* constraint_set2_flag */
705     bitstream_put_ui(bs, 0, 1);                         /* constraint_set3_flag */
706     bitstream_put_ui(bs, 0, 4);                         /* reserved_zero_4bits */
707     bitstream_put_ui(bs, seq_param->level_idc, 8);      /* level_idc */
708     bitstream_put_ue(bs, seq_param->seq_parameter_set_id);      /* seq_parameter_set_id */
709
710     if (seq_param->profile_idc >= PROFILE_IDC_HIGH) {
711         /* FIXME: fix for high profile */
712         assert(0);
713     }
714
715     bitstream_put_ue(bs, seq_param->log2_max_frame_num_minus4); /* log2_max_frame_num_minus4 */
716     bitstream_put_ue(bs, seq_param->pic_order_cnt_type);        /* pic_order_cnt_type */
717
718     if (seq_param->pic_order_cnt_type == 0)
719         bitstream_put_ue(bs, seq_param->log2_max_pic_order_cnt_lsb_minus4);     /* log2_max_pic_order_cnt_lsb_minus4 */
720     else {
721         assert(0);
722     }
723
724     bitstream_put_ue(bs, seq_param->max_num_ref_frames);        /* num_ref_frames */
725     bitstream_put_ui(bs, 0, 1);                                 /* gaps_in_frame_num_value_allowed_flag */
726
727     bitstream_put_ue(bs, seq_param->picture_width_in_mbs - 1);  /* pic_width_in_mbs_minus1 */
728     bitstream_put_ue(bs, seq_param->picture_height_in_mbs - 1); /* pic_height_in_map_units_minus1 */
729     bitstream_put_ui(bs, seq_param->frame_mbs_only_flag, 1);    /* frame_mbs_only_flag */
730
731     if (!seq_param->frame_mbs_only_flag) {
732         assert(0);
733     }
734
735     bitstream_put_ui(bs, seq_param->direct_8x8_inference_flag, 1);      /* direct_8x8_inference_flag */
736     bitstream_put_ui(bs, seq_param->frame_cropping_flag, 1);            /* frame_cropping_flag */
737
738     if (seq_param->frame_cropping_flag) {
739         bitstream_put_ue(bs, seq_param->frame_crop_left_offset);        /* frame_crop_left_offset */
740         bitstream_put_ue(bs, seq_param->frame_crop_right_offset);       /* frame_crop_right_offset */
741         bitstream_put_ue(bs, seq_param->frame_crop_top_offset);         /* frame_crop_top_offset */
742         bitstream_put_ue(bs, seq_param->frame_crop_bottom_offset);      /* frame_crop_bottom_offset */
743     }
744
745     bitstream_put_ui(bs, 0, 1); /* vui_parameters_present_flag */
746     rbsp_trailing_bits(bs);     /* rbsp_trailing_bits */
747 }
748
749 #if 0
750 static void build_nal_sps(FILE *avc_fp)
751 {
752     bitstream bs;
753
754     bitstream_start(&bs);
755     nal_start_code_prefix(&bs);
756     nal_header(&bs, NAL_REF_IDC_HIGH, NAL_SPS);
757     sps_rbsp(&bs);
758     bitstream_end(&bs, avc_fp);
759 }
760 #endif
761
762 static void pps_rbsp(bitstream *bs)
763 {
764     VAEncPictureParameterBufferH264Ext *pic_param = &avcenc_context.pic_param;
765
766     bitstream_put_ue(bs, pic_param->pic_parameter_set_id);      /* pic_parameter_set_id */
767     bitstream_put_ue(bs, pic_param->seq_parameter_set_id);      /* seq_parameter_set_id */
768
769     bitstream_put_ui(bs, pic_param->pic_fields.bits.entropy_coding_mode_flag, 1);  /* entropy_coding_mode_flag */
770
771     bitstream_put_ui(bs, 0, 1);                         /* pic_order_present_flag: 0 */
772
773     bitstream_put_ue(bs, 0);                            /* num_slice_groups_minus1 */
774
775     bitstream_put_ue(bs, pic_param->num_ref_idx_l0_active_minus1);      /* num_ref_idx_l0_active_minus1 */
776     bitstream_put_ue(bs, pic_param->num_ref_idx_l1_active_minus1);      /* num_ref_idx_l1_active_minus1 1 */
777
778     bitstream_put_ui(bs, pic_param->pic_fields.bits.weighted_pred_flag, 1);     /* weighted_pred_flag: 0 */
779     bitstream_put_ui(bs, pic_param->pic_fields.bits.weighted_bipred_idc, 2);    /* weighted_bipred_idc: 0 */
780
781     bitstream_put_se(bs, pic_param->pic_init_qp - 26);  /* pic_init_qp_minus26 */
782     bitstream_put_se(bs, 0);                            /* pic_init_qs_minus26 */
783     bitstream_put_se(bs, 0);                            /* chroma_qp_index_offset */
784
785     bitstream_put_ui(bs, pic_param->pic_fields.bits.deblocking_filter_control_present_flag, 1); /* deblocking_filter_control_present_flag */
786     bitstream_put_ui(bs, 0, 1);                         /* constrained_intra_pred_flag */
787     bitstream_put_ui(bs, 0, 1);                         /* redundant_pic_cnt_present_flag */
788
789     rbsp_trailing_bits(bs);
790 }
791
792 #if 0
793 static void build_nal_pps(FILE *avc_fp)
794 {
795     bitstream bs;
796
797     bitstream_start(&bs);
798     nal_start_code_prefix(&bs);
799     nal_header(&bs, NAL_REF_IDC_HIGH, NAL_PPS);
800     pps_rbsp(&bs);
801     bitstream_end(&bs, avc_fp);
802 }
803
804 static void 
805 build_header(FILE *avc_fp)
806 {
807     build_nal_sps(avc_fp);
808     build_nal_pps(avc_fp);
809 }
810 #endif
811
812 static int
813 build_packed_pic_buffer(unsigned char **header_buffer)
814 {
815     bitstream bs;
816
817     bitstream_start(&bs);
818     nal_start_code_prefix(&bs);
819     nal_header(&bs, NAL_REF_IDC_HIGH, NAL_PPS);
820     pps_rbsp(&bs);
821     bitstream_end(&bs);
822
823     *header_buffer = (unsigned char *)bs.buffer;
824     return bs.bit_offset;
825 }
826
827 static int
828 build_packed_seq_buffer(unsigned char **header_buffer)
829 {
830     bitstream bs;
831
832     bitstream_start(&bs);
833     nal_start_code_prefix(&bs);
834     nal_header(&bs, NAL_REF_IDC_HIGH, NAL_SPS);
835     sps_rbsp(&bs);
836     bitstream_end(&bs);
837
838     *header_buffer = (unsigned char *)bs.buffer;
839     return bs.bit_offset;
840 }
841
842
843 #if 0
844 static void 
845 slice_header(bitstream *bs, int frame_num, int display_frame, int slice_type, int nal_ref_idc, int is_idr)
846 {
847     VAEncSequenceParameterBufferH264Ext *seq_param = &avcenc_context.seq_param;
848     VAEncPictureParameterBufferH264Ext *pic_param = &avcenc_context.pic_param;
849     int is_cabac = (pic_param->pic_fields.bits.entropy_coding_mode_flag == ENTROPY_MODE_CABAC);
850
851     bitstream_put_ue(bs, 0);                   /* first_mb_in_slice: 0 */
852     bitstream_put_ue(bs, slice_type);          /* slice_type */
853     bitstream_put_ue(bs, 0);                   /* pic_parameter_set_id: 0 */
854     bitstream_put_ui(bs, frame_num & 0x0F, seq_param->log2_max_frame_num_minus4 + 4);    /* frame_num */
855
856     /* frame_mbs_only_flag == 1 */
857     if (!seq_param->frame_mbs_only_flag) {
858         /* FIXME: */
859         assert(0);
860     }
861
862     if (is_idr)
863         bitstream_put_ue(bs, 0);                /* idr_pic_id: 0 */
864
865     if (seq_param->pic_order_cnt_type == 0) {
866         bitstream_put_ui(bs, (display_frame*2) & 0x3F, seq_param->log2_max_pic_order_cnt_lsb_minus4 + 4);
867         /* only support frame */
868     } else {
869         /* FIXME: */
870         assert(0);
871     }
872
873     /* redundant_pic_cnt_present_flag == 0 */
874     
875     /* slice type */
876     if (slice_type == SLICE_TYPE_P) {
877         bitstream_put_ui(bs, 0, 1);            /* num_ref_idx_active_override_flag: 0 */
878         /* ref_pic_list_reordering */
879         bitstream_put_ui(bs, 0, 1);            /* ref_pic_list_reordering_flag_l0: 0 */
880     } else if (slice_type == SLICE_TYPE_B) {
881         bitstream_put_ui(bs, 1, 1);            /* direct_spatial_mv_pred: 1 */
882         bitstream_put_ui(bs, 0, 1);            /* num_ref_idx_active_override_flag: 0 */
883         /* ref_pic_list_reordering */
884         bitstream_put_ui(bs, 0, 1);            /* ref_pic_list_reordering_flag_l0: 0 */
885         bitstream_put_ui(bs, 0, 1);            /* ref_pic_list_reordering_flag_l1: 0 */
886     } 
887
888     /* weighted_pred_flag == 0 */
889
890     /* dec_ref_pic_marking */
891     if (nal_ref_idc != 0) {
892         if ( is_idr) {
893             bitstream_put_ui(bs, 0, 1);            /* no_output_of_prior_pics_flag: 0 */
894             bitstream_put_ui(bs, 0, 1);            /* long_term_reference_flag: 0 */
895         } else {
896             bitstream_put_ui(bs, 0, 1);            /* adaptive_ref_pic_marking_mode_flag: 0 */
897         }
898     }
899
900     if (is_cabac && (slice_type != SLICE_TYPE_I))
901         bitstream_put_ue(bs, 0);               /* cabac_init_idc: 0 */
902
903     bitstream_put_se(bs, 0);                   /* slice_qp_delta: 0 */
904
905     if (pic_param->pic_fields.bits.deblocking_filter_control_present_flag == 1) {
906         bitstream_put_ue(bs, 0);               /* disable_deblocking_filter_idc: 0 */
907         bitstream_put_se(bs, 2);               /* slice_alpha_c0_offset_div2: 2 */
908         bitstream_put_se(bs, 2);               /* slice_beta_offset_div2: 2 */
909     }
910 }
911
912 static void 
913 slice_data(bitstream *bs)
914 {
915     VACodedBufferSegment *coded_buffer_segment;
916     unsigned char *coded_mem;
917     int i, slice_data_length;
918     VAStatus va_status;
919     VASurfaceStatus surface_status;
920
921     va_status = vaSyncSurface(va_dpy, surface_ids[avcenc_context.current_input_surface]);
922     CHECK_VASTATUS(va_status,"vaSyncSurface");
923
924     surface_status = 0;
925     va_status = vaQuerySurfaceStatus(va_dpy, surface_ids[avcenc_context.current_input_surface], &surface_status);
926     CHECK_VASTATUS(va_status,"vaQuerySurfaceStatus");
927
928     va_status = vaMapBuffer(va_dpy, avcenc_context.codedbuf_buf_id, (void **)(&coded_buffer_segment));
929     CHECK_VASTATUS(va_status,"vaMapBuffer");
930     coded_mem = coded_buffer_segment->buf;
931
932     slice_data_length = get_coded_bitsteam_length(coded_mem, codedbuf_size);
933
934     for (i = 0; i < slice_data_length; i++) {
935         bitstream_put_ui(bs, *coded_mem, 8);
936         coded_mem++;
937     }
938
939     vaUnmapBuffer(va_dpy, avcenc_context.codedbuf_buf_id);
940 }
941
942 static void 
943 build_nal_slice(FILE *avc_fp, int frame_num, int display_frame, int slice_type, int is_idr)
944 {
945     bitstream bs;
946
947     bitstream_start(&bs);
948     slice_data(&bs);
949     bitstream_end(&bs, avc_fp);
950 }
951
952 #endif
953
954 static int
955 store_coded_buffer(FILE *avc_fp, int slice_type)
956 {
957     VACodedBufferSegment *coded_buffer_segment;
958     unsigned char *coded_mem;
959     int slice_data_length;
960     VAStatus va_status;
961     VASurfaceStatus surface_status;
962     size_t w_items;
963
964     va_status = vaSyncSurface(va_dpy, surface_ids[avcenc_context.current_input_surface]);
965     CHECK_VASTATUS(va_status,"vaSyncSurface");
966
967     surface_status = 0;
968     va_status = vaQuerySurfaceStatus(va_dpy, surface_ids[avcenc_context.current_input_surface], &surface_status);
969     CHECK_VASTATUS(va_status,"vaQuerySurfaceStatus");
970
971     va_status = vaMapBuffer(va_dpy, avcenc_context.codedbuf_buf_id, (void **)(&coded_buffer_segment));
972     CHECK_VASTATUS(va_status,"vaMapBuffer");
973     coded_mem = coded_buffer_segment->buf;
974
975     if (coded_buffer_segment->status & VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK) {
976         if (slice_type == SLICE_TYPE_I)
977             avcenc_context.codedbuf_i_size *= 2;
978         else
979             avcenc_context.codedbuf_pb_size *= 2;
980
981         vaUnmapBuffer(va_dpy, avcenc_context.codedbuf_buf_id);
982         return -1;
983     }
984
985     slice_data_length = coded_buffer_segment->size;
986
987     do {
988         w_items = fwrite(coded_mem, slice_data_length, 1, avc_fp);
989     } while (w_items != 1);
990
991     if (slice_type == SLICE_TYPE_I) {
992         if (avcenc_context.codedbuf_i_size > slice_data_length * 3 / 2) {
993             avcenc_context.codedbuf_i_size = slice_data_length * 3 / 2;
994         }
995         
996         if (avcenc_context.codedbuf_pb_size < slice_data_length) {
997             avcenc_context.codedbuf_pb_size = slice_data_length;
998         }
999     } else {
1000         if (avcenc_context.codedbuf_pb_size > slice_data_length * 3 / 2) {
1001             avcenc_context.codedbuf_pb_size = slice_data_length * 3 / 2;
1002         }
1003     }
1004
1005     vaUnmapBuffer(va_dpy, avcenc_context.codedbuf_buf_id);
1006
1007     return 0;
1008 }
1009
1010 static void
1011 encode_picture(FILE *yuv_fp, FILE *avc_fp,
1012                int frame_num, int display_num,
1013                int is_idr,
1014                int slice_type, int next_is_bpic,
1015                int next_display_num)
1016 {
1017     VAStatus va_status;
1018     int ret = 0, codedbuf_size;
1019     
1020     begin_picture(yuv_fp, frame_num, display_num, slice_type, is_idr);
1021
1022     if (next_display_num < frame_number) {
1023         int index;
1024
1025         /* prepare for next frame */
1026         if (avcenc_context.current_input_surface == SID_INPUT_PICTURE_0)
1027             index = SID_INPUT_PICTURE_1;
1028         else
1029             index = SID_INPUT_PICTURE_0;
1030
1031         fseek(yuv_fp, frame_size * next_display_num, SEEK_SET);
1032
1033         avcenc_context.upload_thread_param.yuv_fp = yuv_fp;
1034         avcenc_context.upload_thread_param.surface_id = surface_ids[index];
1035
1036         avcenc_context.upload_thread_value = pthread_create(&avcenc_context.upload_thread_id,
1037                                                             NULL,
1038                                                             upload_thread_function, 
1039                                                             (void*)&avcenc_context.upload_thread_param);
1040     }
1041
1042     do {
1043         avcenc_destroy_buffers(&avcenc_context.codedbuf_buf_id, 1);
1044         avcenc_destroy_buffers(&avcenc_context.pic_param_buf_id, 1);
1045
1046
1047         if (SLICE_TYPE_I == slice_type) {
1048             codedbuf_size = avcenc_context.codedbuf_i_size;
1049         } else {
1050             codedbuf_size = avcenc_context.codedbuf_pb_size;
1051         }
1052
1053         /* coded buffer */
1054         va_status = vaCreateBuffer(va_dpy,
1055                                    avcenc_context.context_id,
1056                                    VAEncCodedBufferType,
1057                                    codedbuf_size, 1, NULL,
1058                                    &avcenc_context.codedbuf_buf_id);
1059         CHECK_VASTATUS(va_status,"vaCreateBuffer");
1060
1061         /* picture parameter set */
1062         avcenc_update_picture_parameter(slice_type, frame_num, display_num, is_idr);
1063
1064         avcenc_render_picture();
1065
1066         ret = store_coded_buffer(avc_fp, slice_type);
1067     } while (ret);
1068
1069     end_picture(slice_type, next_is_bpic);
1070 }
1071
1072 static void encode_i_picture(FILE *yuv_fp, FILE *avc_fp, int f, int is_idr)
1073 {
1074     encode_picture(yuv_fp, avc_fp,
1075                    enc_frame_number, f,
1076                    is_idr,
1077                    SLICE_TYPE_I, 0, f + 1);
1078 }
1079
1080 static void encode_p_picture(FILE *yuv_fp, FILE *avc_fp, int f)
1081 {
1082     encode_picture(yuv_fp, avc_fp,
1083                    enc_frame_number, f,
1084                    0,
1085                    SLICE_TYPE_P, 0, f + 1);
1086 }
1087
1088 static void encode_pb_pictures(FILE *yuv_fp, FILE *avc_fp, int f, int nbframes)
1089 {
1090     int i;
1091     encode_picture(yuv_fp, avc_fp,
1092                    enc_frame_number, f + nbframes,
1093                    0,
1094                    SLICE_TYPE_P, 1, f);
1095
1096     for( i = 0; i < nbframes - 1; i++) {
1097         encode_picture(yuv_fp, avc_fp,
1098                        enc_frame_number + 1, f + i,
1099                        0,
1100                        SLICE_TYPE_B, 1, f + i + 1);
1101     }
1102     
1103     encode_picture(yuv_fp, avc_fp,
1104                    enc_frame_number + 1, f + nbframes - 1,
1105                    0,
1106                    SLICE_TYPE_B, 0, f + nbframes + 1);
1107 }
1108
1109 static void show_help()
1110 {
1111     printf("Usage: avnenc <width> <height> <input_yuvfile> <output_avcfile> [qp=qpvalue|fb=framebitrate] [mode=0(I frames only)/1(I and P frames)/2(I, P and B frames)\n");
1112 }
1113
1114 static void avcenc_context_seq_param_init(VAEncSequenceParameterBufferH264Ext *seq_param,
1115                                           int width, int height)
1116
1117 {
1118     int width_in_mbs = (width + 15) / 16;
1119     int height_in_mbs = (height + 15) / 16;
1120     int frame_cropping_flag = 0;
1121     int frame_crop_bottom_offset = 0;
1122
1123     seq_param->seq_parameter_set_id = 0;
1124     seq_param->profile_idc = PROFILE_IDC_MAIN;
1125     seq_param->level_idc = 41;
1126     seq_param->intra_period = intra_period;
1127     seq_param->ip_period = 0;   /* FIXME: ??? */
1128     seq_param->max_num_ref_frames = 4;
1129     seq_param->picture_width_in_mbs = width_in_mbs;
1130     seq_param->picture_height_in_mbs = height_in_mbs;
1131     seq_param->frame_mbs_only_flag = 1;
1132     seq_param->target_usage = 1;
1133     
1134     /* 0:CBR, 1:VBR, 2:Constant QP */
1135     if (qp_value == -1)
1136         seq_param->rate_control_method = BR_CBR;
1137     else if (qp_value == -2)
1138         seq_param->rate_control_method = BR_VBR;
1139     else {
1140         assert(qp_value >= 0 && qp_value <= 51);
1141         seq_param->rate_control_method = BR_CQP;
1142     }
1143
1144     if (frame_bit_rate > 0)
1145         seq_param->bits_per_second = 30 * frame_bit_rate;
1146     else
1147         seq_param->bits_per_second = 0;
1148
1149     if (seq_param->rate_control_method == BR_VBR) {
1150         seq_param->max_bits_per_second = 0;     /* FIXME: set it later */
1151         seq_param->min_bits_per_second = 0;
1152     }
1153
1154     seq_param->initial_hrd_buffer_fullness = 0; /* FIXME: ??? */
1155     seq_param->hrd_buffer_size = 0;             /* FIXME: ??? */
1156     seq_param->time_scale = 900;
1157     seq_param->num_units_in_tick = 15;
1158
1159     if (height_in_mbs * 16 - height) {
1160         frame_cropping_flag = 1;
1161         frame_crop_bottom_offset = 
1162             (height_in_mbs * 16 - height) / (2 * (!seq_param->frame_mbs_only_flag + 1));
1163     }
1164
1165     seq_param->frame_cropping_flag = frame_cropping_flag;
1166     seq_param->frame_crop_left_offset = 0;
1167     seq_param->frame_crop_right_offset = 0;
1168     seq_param->frame_crop_top_offset = 0;
1169     seq_param->frame_crop_bottom_offset = frame_crop_bottom_offset;
1170
1171     seq_param->pic_order_cnt_type = 0;
1172     seq_param->direct_8x8_inference_flag = 0;
1173     
1174     seq_param->log2_max_frame_num_minus4 = 0;
1175     seq_param->log2_max_pic_order_cnt_lsb_minus4 = 2;
1176
1177     seq_param->vui_flag = 0;
1178 }
1179
1180 static void avcenc_context_pic_param_init(VAEncPictureParameterBufferH264Ext *pic_param)
1181 {
1182     pic_param->seq_parameter_set_id = 0;
1183     pic_param->pic_parameter_set_id = 0;
1184
1185     pic_param->last_picture = 0;
1186     pic_param->frame_num = 0;
1187     pic_param->coding_type = 0;
1188     
1189     pic_param->pic_init_qp = (qp_value >= 0 ?  qp_value : 26);
1190     pic_param->num_ref_idx_l0_active_minus1 = 0;
1191     pic_param->num_ref_idx_l1_active_minus1 = 0;
1192
1193     pic_param->pic_fields.bits.idr_pic_flag = 0;
1194     pic_param->pic_fields.bits.reference_pic_flag = 0;
1195     pic_param->pic_fields.bits.entropy_coding_mode_flag = ENTROPY_MODE_CABAC;
1196     pic_param->pic_fields.bits.weighted_pred_flag = 0;
1197     pic_param->pic_fields.bits.weighted_bipred_idc = 0;
1198     pic_param->pic_fields.bits.transform_8x8_mode_flag = 0;
1199     pic_param->pic_fields.bits.deblocking_filter_control_present_flag = 1;
1200 }
1201
1202 static void avcenc_context_init(int width, int height)
1203 {
1204     int i;
1205     memset(&avcenc_context, 0, sizeof(avcenc_context));
1206     avcenc_context.seq_param_buf_id = VA_INVALID_ID;
1207     avcenc_context.pic_param_buf_id = VA_INVALID_ID;
1208     avcenc_context.dec_ref_pic_marking_buf_id = VA_INVALID_ID;
1209     avcenc_context.packed_seq_buf_id = VA_INVALID_ID;
1210     avcenc_context.packed_pic_buf_id = VA_INVALID_ID;
1211     avcenc_context.codedbuf_buf_id = VA_INVALID_ID;
1212     avcenc_context.codedbuf_i_size = width * height;
1213     avcenc_context.codedbuf_pb_size = 0;
1214     avcenc_context.current_input_surface = SID_INPUT_PICTURE_0;
1215     avcenc_context.upload_thread_value = -1;
1216
1217     for (i = 0; i < MAX_SLICES; i++) {
1218         avcenc_context.slice_param_buf_id[i] = VA_INVALID_ID;
1219     }
1220
1221     avcenc_context_seq_param_init(&avcenc_context.seq_param, width, height);
1222     avcenc_context_pic_param_init(&avcenc_context.pic_param);
1223 }
1224
1225 int main(int argc, char *argv[])
1226 {
1227     int f;
1228     FILE *yuv_fp;
1229     FILE *avc_fp;
1230     long file_size;
1231     int i_frame_only=0,i_p_frame_only=1;
1232     int mode_value;
1233     struct timeval tpstart,tpend; 
1234     float  timeuse;
1235
1236     va_init_display_args(&argc, argv);
1237
1238     //TODO may be we should using option analytics library
1239     if(argc != 5 && argc != 6 && argc != 7) {
1240         show_help();
1241         return -1;
1242     }
1243
1244     picture_width = atoi(argv[1]);
1245     picture_height = atoi(argv[2]);
1246     picture_width_in_mbs = (picture_width + 15) / 16;
1247     picture_height_in_mbs = (picture_height + 15) / 16;
1248
1249     if (argc == 6 || argc == 7) {
1250         qp_value = -1;
1251         sscanf(argv[5], "qp=%d", &qp_value);
1252         if ( qp_value == -1 ) {
1253             frame_bit_rate = -1;
1254             sscanf(argv[5], "fb=%d", &frame_bit_rate);
1255             if (  frame_bit_rate == -1 ) {
1256                 show_help();
1257                 return -1;
1258             }
1259         } else if (qp_value > 51) {
1260             qp_value = 51;
1261         } else if (qp_value < 0) {
1262             qp_value = 0;
1263         }
1264     } else
1265         qp_value = 28;                          //default const QP mode
1266
1267     if (argc == 7) {
1268         sscanf(argv[6], "mode=%d", &mode_value);
1269         if ( mode_value == 0 ) {
1270                 i_frame_only = 1;
1271                 i_p_frame_only = 0;
1272         }
1273         else if ( mode_value == 1) {
1274                 i_frame_only = 0;
1275                 i_p_frame_only = 1;
1276         }
1277         else if ( mode_value == 2 ) {
1278                 i_frame_only = 0;
1279                 i_p_frame_only = 0;
1280         }
1281         else {
1282                 printf("mode_value=%d\n",mode_value);
1283                 show_help();
1284                 return -1;
1285         }
1286     }
1287
1288     yuv_fp = fopen(argv[3],"rb");
1289     if ( yuv_fp == NULL){
1290         printf("Can't open input YUV file\n");
1291         return -1;
1292     }
1293     fseek(yuv_fp,0l, SEEK_END);
1294     file_size = ftell(yuv_fp);
1295     frame_size = picture_width * picture_height +  ((picture_width * picture_height) >> 1) ;
1296
1297     if ( (file_size < frame_size) || (file_size % frame_size) ) {
1298         fclose(yuv_fp);
1299         printf("The YUV file's size is not correct\n");
1300         return -1;
1301     }
1302     frame_number = file_size / frame_size;
1303     fseek(yuv_fp, 0l, SEEK_SET);
1304
1305     avc_fp = fopen(argv[4], "wb");      
1306     if ( avc_fp == NULL) {
1307         fclose(yuv_fp);
1308         printf("Can't open output avc file\n");
1309         return -1;
1310     }   
1311     gettimeofday(&tpstart,NULL);        
1312     avcenc_context_init(picture_width, picture_height);
1313     create_encode_pipe();
1314     alloc_encode_resource(yuv_fp);
1315
1316     enc_frame_number = 0;
1317     for ( f = 0; f < frame_number; ) {          //picture level loop
1318         int is_intra = i_frame_only?1:(enc_frame_number % intra_period == 0);
1319         int is_idr = (f == 0);
1320         int is_bslice = 0;
1321                 
1322         if ( ! is_intra && pb_period > 0) {
1323             is_bslice = i_p_frame_only?0:(f % pb_period == 1) && (f < frame_number - 1);        
1324         }
1325         
1326         if ( is_intra ) {
1327             encode_i_picture(yuv_fp, avc_fp, f, is_idr);
1328             f++;
1329             enc_frame_number++;
1330         } else if ( is_bslice) {
1331             encode_pb_pictures(yuv_fp, avc_fp, f, 2);   //last parameter is continue B frames number
1332             f += (1 + 2);
1333             enc_frame_number++;
1334         } else {
1335             encode_p_picture(yuv_fp, avc_fp, f);
1336             f++;
1337             enc_frame_number++;
1338         }
1339        
1340         printf("\r %d/%d ...", f+1, frame_number);
1341         fflush(stdout);
1342     }
1343
1344     gettimeofday(&tpend,NULL);
1345     timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+ tpend.tv_usec-tpstart.tv_usec;
1346     timeuse/=1000000;
1347     printf("\ndone!\n");
1348     printf("encode %d frames in %f secondes, FPS is %.1f\n",frame_number, timeuse, frame_number/timeuse);
1349     release_encode_resource();
1350     destory_encode_pipe();
1351
1352     fclose(yuv_fp);
1353     fclose(avc_fp);
1354
1355     return 0;
1356 }