-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh264encode.c
2043 lines (1731 loc) · 75.2 KB
/
h264encode.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Modified dec 2023 vzvca
// Original source at https://github.com/intel/libva-utils.git
/*
* Copyright (c) 2007-2013 Intel Corporation. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#define LIBVA_UTILS_UPLOAD_DOWNLOAD_YUV_SURFACE 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <va/va.h>
#include <va/va_enc_h264.h>
#define CHECK_VASTATUS(va_status,func) \
if (va_status != VA_STATUS_SUCCESS) { \
fprintf(stderr,"%s:%s (%d) failed,exit\n", __func__, func, __LINE__); \
exit(1); \
}
#include "bitstream.h"
#include "loadsurface.h"
#define NAL_REF_IDC_NONE 0
#define NAL_REF_IDC_LOW 1
#define NAL_REF_IDC_MEDIUM 2
#define NAL_REF_IDC_HIGH 3
#define NAL_NON_IDR 1
#define NAL_IDR 5
#define NAL_SPS 7
#define NAL_PPS 8
#define NAL_SEI 6
#define SLICE_TYPE_P 0
#define SLICE_TYPE_B 1
#define SLICE_TYPE_I 2
#define IS_P_SLICE(type) (SLICE_TYPE_P == (type))
#define IS_B_SLICE(type) (SLICE_TYPE_B == (type))
#define IS_I_SLICE(type) (SLICE_TYPE_I == (type))
#define ENTROPY_MODE_CAVLC 0
#define ENTROPY_MODE_CABAC 1
#define PROFILE_IDC_BASELINE 66
#define PROFILE_IDC_MAIN 77
#define PROFILE_IDC_HIGH 100
#define SURFACE_NUM 16 /* 16 surfaces for source YUV */
static VADisplay va_dpy;
static VAProfile h264_profile = ~0;
static VAConfigAttrib attrib[VAConfigAttribTypeMax];
static VAConfigAttrib config_attrib[VAConfigAttribTypeMax];
static int config_attrib_num = 0, enc_packed_header_idx;
static VASurfaceID src_surface[SURFACE_NUM];
static VABufferID coded_buf[SURFACE_NUM];
static VASurfaceID ref_surface[SURFACE_NUM];
static VAConfigID config_id;
static VAContextID context_id;
static VAEncSequenceParameterBufferH264 seq_param;
static VAEncPictureParameterBufferH264 pic_param;
static VAEncSliceParameterBufferH264 slice_param;
static VAPictureH264 CurrentCurrPic;
static VAPictureH264 ReferenceFrames[16], RefPicList0_P[32], RefPicList0_B[32], RefPicList1_B[32];
#define N_REF_FRAMES (sizeof(ReferenceFrames) / sizeof(ReferenceFrames[0]))
#define N_REF_PICS_LIST0_P (sizeof(RefPicList0_P) / sizeof(RefPicList0_P[0]))
#define N_REF_PICS_LIST0_B (sizeof(RefPicList0_B) / sizeof(RefPicList0_B[0]))
#define N_REF_PICS_LIST1_B (sizeof(RefPicList1_B) / sizeof(RefPicList1_B[0]))
static unsigned int MaxFrameNum = (2 << 16);
static unsigned int MaxPicOrderCntLsb = (2 << 8);
static unsigned int Log2MaxFrameNum = 16;
static unsigned int Log2MaxPicOrderCntLsb = 8;
//static unsigned int num_ref_frames = 2;
static unsigned int num_ref_frames = 1;
static unsigned int numShortTerm = 0;
static int constraint_set_flag = 0;
static int h264_packedheader = 0; /* support pack header? */
static int h264_maxref = (1 << 16 | 1);
static int h264_entropy_mode = 1; /* cabac */
static char *coded_fn = NULL, *srcyuv_fn = NULL;
static FILE *coded_fp = NULL, *srcyuv_fp = NULL;
static unsigned long long srcyuv_frames = 0;
static int srcyuv_fourcc = VA_FOURCC_NV12;
static unsigned char *srcyuv_ptr = NULL;
static unsigned char *nv12 = NULL;
static int frame_width = 720;
static int frame_height = 576;
static int frame_width_mbaligned;
static int frame_height_mbaligned;
static int frame_rate = 30;
static unsigned int frame_count = 180; // default number of video frames captured
static unsigned int frame_coded = 0;
static unsigned int frame_bitrate = 0;
static unsigned int frame_slices = 1;
static double frame_size = 0;
static int initial_qp = 26;
static int minimal_qp = 0;
static int intra_period = 30;
static int intra_idr_period = 30;
//static int intra_idr_period = 60;
static int ip_period = 1;
static int rc_mode = -1;
static int rc_default_modes[] =
{
VA_RC_VBR,
VA_RC_CQP,
VA_RC_VBR_CONSTRAINED,
VA_RC_CBR,
VA_RC_VCM,
VA_RC_NONE,
};
static unsigned long long current_frame_encoding = 0;
static unsigned long long current_frame_display = 0;
static unsigned long long current_IDR_display = 0;
static unsigned int current_frame_num = 0;
static int current_frame_type;
#define current_slot (current_frame_display % SURFACE_NUM)
static int misc_priv_type = 0;
static int misc_priv_value = 0;
#define MIN(a, b) ((a)>(b)?(b):(a))
#define MAX(a, b) ((a)>(b)?(a):(b))
#define SRC_SURFACE_IN_ENCODING 0
static int srcsurface_status[SURFACE_NUM];
/* for performance profiling */
static unsigned int UploadPictureTicks = 0;
static unsigned int BeginPictureTicks = 0;
static unsigned int RenderPictureTicks = 0;
static unsigned int EndPictureTicks = 0;
static unsigned int SyncPictureTicks = 0;
static unsigned int SavePictureTicks = 0;
static unsigned int ProcessPictureTicks = 0;
static unsigned int TotalTicks = 0;
//Default entrypoint for Encode
static VAEntrypoint requested_entrypoint = -1;
static VAEntrypoint selected_entrypoint = -1;
// Default values
#define DEF_INTRA_PERIOD 20
#define DEF_INTRA_IDR_PERIOD 20
#define DEF_IP_PERIOD 1
/*
* --------------------------------------------------------------------------
* Prototypes
* --------------------------------------------------------------------------
*/
VADisplay va_open_display_drm(void);
void va_close_display_drm(VADisplay va_dpy);
void tfnv12 (int w, int h, unsigned char *rgba, unsigned char *y, unsigned char *uv);
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static void
rbsp_trailing_bits(bitstream *bs)
{
bitstream_put_ui(bs, 1, 1);
bitstream_byte_aligning(bs, 0);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static void nal_start_code_prefix(bitstream *bs)
{
bitstream_put_ui(bs, 0x00000001, 32);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static void nal_header(bitstream *bs, int nal_ref_idc, int nal_unit_type)
{
bitstream_put_ui(bs, 0, 1); /* forbidden_zero_bit: 0 */
bitstream_put_ui(bs, nal_ref_idc, 2);
bitstream_put_ui(bs, nal_unit_type, 5);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static void sps_rbsp(bitstream *bs)
{
int profile_idc = PROFILE_IDC_BASELINE;
if (h264_profile == VAProfileH264High)
profile_idc = PROFILE_IDC_HIGH;
else if (h264_profile == VAProfileH264Main)
profile_idc = PROFILE_IDC_MAIN;
bitstream_put_ui(bs, profile_idc, 8); /* profile_idc */
bitstream_put_ui(bs, !!(constraint_set_flag & 1), 1); /* constraint_set0_flag */
bitstream_put_ui(bs, !!(constraint_set_flag & 2), 1); /* constraint_set1_flag */
bitstream_put_ui(bs, !!(constraint_set_flag & 4), 1); /* constraint_set2_flag */
bitstream_put_ui(bs, !!(constraint_set_flag & 8), 1); /* constraint_set3_flag */
bitstream_put_ui(bs, 0, 4); /* reserved_zero_4bits */
bitstream_put_ui(bs, seq_param.level_idc, 8); /* level_idc */
bitstream_put_ue(bs, seq_param.seq_parameter_set_id); /* seq_parameter_set_id */
if (profile_idc == PROFILE_IDC_HIGH) {
bitstream_put_ue(bs, 1); /* chroma_format_idc = 1, 4:2:0 */
bitstream_put_ue(bs, 0); /* bit_depth_luma_minus8 */
bitstream_put_ue(bs, 0); /* bit_depth_chroma_minus8 */
bitstream_put_ui(bs, 0, 1); /* qpprime_y_zero_transform_bypass_flag */
bitstream_put_ui(bs, 0, 1); /* seq_scaling_matrix_present_flag */
}
bitstream_put_ue(bs, seq_param.seq_fields.bits.log2_max_frame_num_minus4); /* log2_max_frame_num_minus4 */
bitstream_put_ue(bs, seq_param.seq_fields.bits.pic_order_cnt_type); /* pic_order_cnt_type */
if (seq_param.seq_fields.bits.pic_order_cnt_type == 0)
bitstream_put_ue(bs, seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4); /* log2_max_pic_order_cnt_lsb_minus4 */
else {
assert(0);
}
bitstream_put_ue(bs, seq_param.max_num_ref_frames); /* num_ref_frames */
bitstream_put_ui(bs, 0, 1); /* gaps_in_frame_num_value_allowed_flag */
bitstream_put_ue(bs, seq_param.picture_width_in_mbs - 1); /* pic_width_in_mbs_minus1 */
bitstream_put_ue(bs, seq_param.picture_height_in_mbs - 1); /* pic_height_in_map_units_minus1 */
bitstream_put_ui(bs, seq_param.seq_fields.bits.frame_mbs_only_flag, 1); /* frame_mbs_only_flag */
if (!seq_param.seq_fields.bits.frame_mbs_only_flag) {
assert(0);
}
bitstream_put_ui(bs, seq_param.seq_fields.bits.direct_8x8_inference_flag, 1); /* direct_8x8_inference_flag */
bitstream_put_ui(bs, seq_param.frame_cropping_flag, 1); /* frame_cropping_flag */
if (seq_param.frame_cropping_flag) {
bitstream_put_ue(bs, seq_param.frame_crop_left_offset); /* frame_crop_left_offset */
bitstream_put_ue(bs, seq_param.frame_crop_right_offset); /* frame_crop_right_offset */
bitstream_put_ue(bs, seq_param.frame_crop_top_offset); /* frame_crop_top_offset */
bitstream_put_ue(bs, seq_param.frame_crop_bottom_offset); /* frame_crop_bottom_offset */
}
//if ( frame_bit_rate < 0 ) { //TODO EW: the vui header isn't correct
if (1) {
bitstream_put_ui(bs, 0, 1); /* vui_parameters_present_flag */
} else {
bitstream_put_ui(bs, 1, 1); /* vui_parameters_present_flag */
bitstream_put_ui(bs, 0, 1); /* aspect_ratio_info_present_flag */
bitstream_put_ui(bs, 0, 1); /* overscan_info_present_flag */
bitstream_put_ui(bs, 0, 1); /* video_signal_type_present_flag */
bitstream_put_ui(bs, 0, 1); /* chroma_loc_info_present_flag */
bitstream_put_ui(bs, 1, 1); /* timing_info_present_flag */
{
bitstream_put_ui(bs, 15, 32);
bitstream_put_ui(bs, 900, 32);
bitstream_put_ui(bs, 1, 1);
}
bitstream_put_ui(bs, 1, 1); /* nal_hrd_parameters_present_flag */
{
// hrd_parameters
bitstream_put_ue(bs, 0); /* cpb_cnt_minus1 */
bitstream_put_ui(bs, 4, 4); /* bit_rate_scale */
bitstream_put_ui(bs, 6, 4); /* cpb_size_scale */
bitstream_put_ue(bs, frame_bitrate - 1); /* bit_rate_value_minus1[0] */
bitstream_put_ue(bs, frame_bitrate * 8 - 1); /* cpb_size_value_minus1[0] */
bitstream_put_ui(bs, 1, 1); /* cbr_flag[0] */
bitstream_put_ui(bs, 23, 5); /* initial_cpb_removal_delay_length_minus1 */
bitstream_put_ui(bs, 23, 5); /* cpb_removal_delay_length_minus1 */
bitstream_put_ui(bs, 23, 5); /* dpb_output_delay_length_minus1 */
bitstream_put_ui(bs, 23, 5); /* time_offset_length */
}
bitstream_put_ui(bs, 0, 1); /* vcl_hrd_parameters_present_flag */
bitstream_put_ui(bs, 0, 1); /* low_delay_hrd_flag */
bitstream_put_ui(bs, 0, 1); /* pic_struct_present_flag */
bitstream_put_ui(bs, 0, 1); /* bitstream_restriction_flag */
}
rbsp_trailing_bits(bs); /* rbsp_trailing_bits */
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static void pps_rbsp(bitstream *bs)
{
bitstream_put_ue(bs, pic_param.pic_parameter_set_id); /* pic_parameter_set_id */
bitstream_put_ue(bs, pic_param.seq_parameter_set_id); /* seq_parameter_set_id */
bitstream_put_ui(bs, pic_param.pic_fields.bits.entropy_coding_mode_flag, 1); /* entropy_coding_mode_flag */
bitstream_put_ui(bs, 0, 1); /* pic_order_present_flag: 0 */
bitstream_put_ue(bs, 0); /* num_slice_groups_minus1 */
bitstream_put_ue(bs, pic_param.num_ref_idx_l0_active_minus1); /* num_ref_idx_l0_active_minus1 */
bitstream_put_ue(bs, pic_param.num_ref_idx_l1_active_minus1); /* num_ref_idx_l1_active_minus1 1 */
bitstream_put_ui(bs, pic_param.pic_fields.bits.weighted_pred_flag, 1); /* weighted_pred_flag: 0 */
bitstream_put_ui(bs, pic_param.pic_fields.bits.weighted_bipred_idc, 2); /* weighted_bipred_idc: 0 */
bitstream_put_se(bs, pic_param.pic_init_qp - 26); /* pic_init_qp_minus26 */
bitstream_put_se(bs, 0); /* pic_init_qs_minus26 */
bitstream_put_se(bs, 0); /* chroma_qp_index_offset */
bitstream_put_ui(bs, pic_param.pic_fields.bits.deblocking_filter_control_present_flag, 1); /* deblocking_filter_control_present_flag */
bitstream_put_ui(bs, 0, 1); /* constrained_intra_pred_flag */
bitstream_put_ui(bs, 0, 1); /* redundant_pic_cnt_present_flag */
/* more_rbsp_data */
bitstream_put_ui(bs, pic_param.pic_fields.bits.transform_8x8_mode_flag, 1); /*transform_8x8_mode_flag */
bitstream_put_ui(bs, 0, 1); /* pic_scaling_matrix_present_flag */
bitstream_put_se(bs, pic_param.second_chroma_qp_index_offset); /*second_chroma_qp_index_offset */
rbsp_trailing_bits(bs);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static void slice_header(bitstream *bs)
{
int first_mb_in_slice = slice_param.macroblock_address;
bitstream_put_ue(bs, first_mb_in_slice); /* first_mb_in_slice: 0 */
bitstream_put_ue(bs, slice_param.slice_type); /* slice_type */
bitstream_put_ue(bs, slice_param.pic_parameter_set_id); /* pic_parameter_set_id: 0 */
bitstream_put_ui(bs, pic_param.frame_num, seq_param.seq_fields.bits.log2_max_frame_num_minus4 + 4); /* frame_num */
/* frame_mbs_only_flag == 1 */
if (!seq_param.seq_fields.bits.frame_mbs_only_flag) {
/* FIXME: */
assert(0);
}
if (pic_param.pic_fields.bits.idr_pic_flag)
bitstream_put_ue(bs, slice_param.idr_pic_id); /* idr_pic_id: 0 */
if (seq_param.seq_fields.bits.pic_order_cnt_type == 0) {
bitstream_put_ui(bs, pic_param.CurrPic.TopFieldOrderCnt, seq_param.seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4 + 4);
/* pic_order_present_flag == 0 */
} else {
/* FIXME: */
assert(0);
}
/* redundant_pic_cnt_present_flag == 0 */
/* slice type */
if (IS_P_SLICE(slice_param.slice_type)) {
bitstream_put_ui(bs, slice_param.num_ref_idx_active_override_flag, 1); /* num_ref_idx_active_override_flag: */
if (slice_param.num_ref_idx_active_override_flag)
bitstream_put_ue(bs, slice_param.num_ref_idx_l0_active_minus1);
/* ref_pic_list_reordering */
bitstream_put_ui(bs, 0, 1); /* ref_pic_list_reordering_flag_l0: 0 */
} else if (IS_B_SLICE(slice_param.slice_type)) {
bitstream_put_ui(bs, slice_param.direct_spatial_mv_pred_flag, 1); /* direct_spatial_mv_pred: 1 */
bitstream_put_ui(bs, slice_param.num_ref_idx_active_override_flag, 1); /* num_ref_idx_active_override_flag: */
if (slice_param.num_ref_idx_active_override_flag) {
bitstream_put_ue(bs, slice_param.num_ref_idx_l0_active_minus1);
bitstream_put_ue(bs, slice_param.num_ref_idx_l1_active_minus1);
}
/* ref_pic_list_reordering */
bitstream_put_ui(bs, 0, 1); /* ref_pic_list_reordering_flag_l0: 0 */
bitstream_put_ui(bs, 0, 1); /* ref_pic_list_reordering_flag_l1: 0 */
}
if ((pic_param.pic_fields.bits.weighted_pred_flag &&
IS_P_SLICE(slice_param.slice_type)) ||
((pic_param.pic_fields.bits.weighted_bipred_idc == 1) &&
IS_B_SLICE(slice_param.slice_type))) {
/* FIXME: fill weight/offset table */
assert(0);
}
/* dec_ref_pic_marking */
if (pic_param.pic_fields.bits.reference_pic_flag) { /* nal_ref_idc != 0 */
unsigned char no_output_of_prior_pics_flag = 0;
unsigned char long_term_reference_flag = 0;
unsigned char adaptive_ref_pic_marking_mode_flag = 0;
if (pic_param.pic_fields.bits.idr_pic_flag) {
bitstream_put_ui(bs, no_output_of_prior_pics_flag, 1); /* no_output_of_prior_pics_flag: 0 */
bitstream_put_ui(bs, long_term_reference_flag, 1); /* long_term_reference_flag: 0 */
} else {
bitstream_put_ui(bs, adaptive_ref_pic_marking_mode_flag, 1); /* adaptive_ref_pic_marking_mode_flag: 0 */
}
}
if (pic_param.pic_fields.bits.entropy_coding_mode_flag &&
!IS_I_SLICE(slice_param.slice_type))
bitstream_put_ue(bs, slice_param.cabac_init_idc); /* cabac_init_idc: 0 */
bitstream_put_se(bs, slice_param.slice_qp_delta); /* slice_qp_delta: 0 */
/* ignore for SP/SI */
if (pic_param.pic_fields.bits.deblocking_filter_control_present_flag) {
bitstream_put_ue(bs, slice_param.disable_deblocking_filter_idc); /* disable_deblocking_filter_idc: 0 */
if (slice_param.disable_deblocking_filter_idc != 1) {
bitstream_put_se(bs, slice_param.slice_alpha_c0_offset_div2); /* slice_alpha_c0_offset_div2: 2 */
bitstream_put_se(bs, slice_param.slice_beta_offset_div2); /* slice_beta_offset_div2: 2 */
}
}
if (pic_param.pic_fields.bits.entropy_coding_mode_flag) {
bitstream_byte_aligning(bs, 1);
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static int
build_packed_pic_buffer(unsigned char **header_buffer)
{
bitstream bs;
bitstream_start(&bs);
nal_start_code_prefix(&bs);
nal_header(&bs, NAL_REF_IDC_HIGH, NAL_PPS);
pps_rbsp(&bs);
bitstream_end(&bs);
*header_buffer = (unsigned char *)bs.buffer;
return bs.bit_offset;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static int
build_packed_seq_buffer(unsigned char **header_buffer)
{
bitstream bs;
bitstream_start(&bs);
nal_start_code_prefix(&bs);
nal_header(&bs, NAL_REF_IDC_HIGH, NAL_SPS);
sps_rbsp(&bs);
bitstream_end(&bs);
*header_buffer = (unsigned char *)bs.buffer;
return bs.bit_offset;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static int build_packed_slice_buffer(unsigned char **header_buffer)
{
bitstream bs;
int is_idr = !!pic_param.pic_fields.bits.idr_pic_flag;
int is_ref = !!pic_param.pic_fields.bits.reference_pic_flag;
bitstream_start(&bs);
nal_start_code_prefix(&bs);
if (IS_I_SLICE(slice_param.slice_type)) {
nal_header(&bs, NAL_REF_IDC_HIGH, is_idr ? NAL_IDR : NAL_NON_IDR);
} else if (IS_P_SLICE(slice_param.slice_type)) {
nal_header(&bs, NAL_REF_IDC_MEDIUM, NAL_NON_IDR);
} else {
assert(IS_B_SLICE(slice_param.slice_type));
nal_header(&bs, is_ref ? NAL_REF_IDC_LOW : NAL_REF_IDC_NONE, NAL_NON_IDR);
}
slice_header(&bs);
bitstream_end(&bs);
*header_buffer = (unsigned char *)bs.buffer;
return bs.bit_offset;
}
/*
* Helper function for profiling purposes
*/
static unsigned int GetTickCount()
{
struct timeval tv;
if (gettimeofday(&tv, NULL))
return 0;
return tv.tv_usec / 1000 + tv.tv_sec * 1000;
}
/*
Assume frame sequence is: Frame#0,#1,#2,...,#M,...,#X,... (encoding order)
1) period between Frame #X and Frame #N = #X - #N
2) 0 means infinite for intra_period/intra_idr_period, and 0 is invalid for ip_period
3) intra_idr_period % intra_period (intra_period > 0) and intra_period % ip_period must be 0
4) intra_period and intra_idr_period take precedence over ip_period
5) if ip_period > 1, intra_period and intra_idr_period are not the strict periods
of I/IDR frames, see bellow examples
-------------------------------------------------------------------
intra_period intra_idr_period ip_period frame sequence (intra_period/intra_idr_period/ip_period)
0 ignored 1 IDRPPPPPPP ... (No IDR/I any more)
0 ignored >=2 IDR(PBB)(PBB)... (No IDR/I any more)
1 0 ignored IDRIIIIIII... (No IDR any more)
1 1 ignored IDR IDR IDR IDR...
1 >=2 ignored IDRII IDRII IDR... (1/3/ignore)
>=2 0 1 IDRPPP IPPP I... (3/0/1)
>=2 0 >=2 IDR(PBB)(PBB)(IBB) (6/0/3)
(PBB)(IBB)(PBB)(IBB)...
>=2 >=2 1 IDRPPPPP IPPPPP IPPPPP (6/18/1)
IDRPPPPP IPPPPP IPPPPP...
>=2 >=2 >=2 {IDR(PBB)(PBB)(IBB)(PBB)(IBB)(PBB)} (6/18/3)
{IDR(PBB)(PBB)(IBB)(PBB)(IBB)(PBB)}...
{IDR(PBB)(PBB)(IBB)(PBB)} (6/12/3)
{IDR(PBB)(PBB)(IBB)(PBB)}...
{IDR(PBB)(PBB)} (6/6/3)
{IDR(PBB)(PBB)}.
*/
/*
* Return displaying order with specified periods and encoding order
* displaying_order: displaying order
* frame_type: frame type
*/
#define FRAME_P 0
#define FRAME_B 1
#define FRAME_I 2
#define FRAME_IDR 7
void encoding2display_order(
unsigned long long encoding_order, int intra_period,
int intra_idr_period, int ip_period,
unsigned long long *displaying_order,
int *frame_type)
{
int encoding_order_gop = 0;
if (intra_period == 1) { /* all are I/IDR frames */
*displaying_order = encoding_order;
if (intra_idr_period == 0)
*frame_type = (encoding_order == 0) ? FRAME_IDR : FRAME_I;
else
*frame_type = (encoding_order % intra_idr_period == 0) ? FRAME_IDR : FRAME_I;
return;
}
if (intra_period == 0)
intra_idr_period = 0;
/* new sequence like
* IDR PPPPP IPPPPP
* IDR (PBB)(PBB)(IBB)(PBB)
*/
encoding_order_gop = (intra_idr_period == 0) ? encoding_order :
(encoding_order % (intra_idr_period + ((ip_period == 1) ? 0 : 1)));
if (encoding_order_gop == 0) { /* the first frame */
*frame_type = FRAME_IDR;
*displaying_order = encoding_order;
} else if (((encoding_order_gop - 1) % ip_period) != 0) { /* B frames */
*frame_type = FRAME_B;
*displaying_order = encoding_order - 1;
} else if ((intra_period != 0) && /* have I frames */
(encoding_order_gop >= 2) &&
((ip_period == 1 && encoding_order_gop % intra_period == 0) || /* for IDR PPPPP IPPPP */
/* for IDR (PBB)(PBB)(IBB) */
(ip_period >= 2 && ((encoding_order_gop - 1) / ip_period % (intra_period / ip_period)) == 0))) {
*frame_type = FRAME_I;
*displaying_order = encoding_order + ip_period - 1;
} else {
*frame_type = FRAME_P;
*displaying_order = encoding_order + ip_period - 1;
}
}
// -----------------------------------------------------------------------------
// Get friendly string rep for frame type
// -----------------------------------------------------------------------------
static char* get_frame_type (int ft)
{
switch (ft) {
case FRAME_P: return "P";
case FRAME_B: return "B";
case FRAME_I: return "I";
case FRAME_IDR: return "IDR";
default: return "UNK";
}
}
// -----------------------------------------------------------------------------
// Convert 4CC to string
// -----------------------------------------------------------------------------
static char *fourcc_to_string(int fourcc)
{
switch (fourcc) {
case VA_FOURCC_NV12:
return "NV12";
case VA_FOURCC_IYUV:
return "IYUV";
case VA_FOURCC_YV12:
return "YV12";
case VA_FOURCC_UYVY:
return "UYVY";
default:
return "Unknown";
}
}
// -----------------------------------------------------------------------------
// Convert string to 4CC
// -----------------------------------------------------------------------------
static int string_to_fourcc(char *str)
{
int fourcc;
if (!strncmp(str, "NV12", 4))
fourcc = VA_FOURCC_NV12;
else if (!strncmp(str, "IYUV", 4))
fourcc = VA_FOURCC_IYUV;
else if (!strncmp(str, "YV12", 4))
fourcc = VA_FOURCC_YV12;
else if (!strncmp(str, "UYVY", 4))
fourcc = VA_FOURCC_UYVY;
else {
printf("Unknow FOURCC\n");
fourcc = -1;
}
return fourcc;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static char *rc_to_string(int rcmode)
{
switch (rc_mode) {
case VA_RC_NONE:
return "NONE";
case VA_RC_CBR:
return "CBR";
case VA_RC_VBR:
return "VBR";
case VA_RC_VCM:
return "VCM";
case VA_RC_CQP:
return "CQP";
case VA_RC_VBR_CONSTRAINED:
return "VBR_CONSTRAINED";
default:
return "Unknown";
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static int string_to_rc(char *str)
{
int rc_mode;
if (!strncmp(str, "NONE", 4))
rc_mode = VA_RC_NONE;
else if (!strncmp(str, "CBR", 3))
rc_mode = VA_RC_CBR;
else if (!strncmp(str, "VBR", 3))
rc_mode = VA_RC_VBR;
else if (!strncmp(str, "VCM", 3))
rc_mode = VA_RC_VCM;
else if (!strncmp(str, "CQP", 3))
rc_mode = VA_RC_CQP;
else if (!strncmp(str, "VBR_CONSTRAINED", 15))
rc_mode = VA_RC_VBR_CONSTRAINED;
else {
printf("Unknown RC mode\n");
rc_mode = -1;
}
return rc_mode;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static int print_help(void)
{
printf("./h264encode <options>\n");
printf(" -w <width> -h <height>\n");
printf(" -framecount <frame number>\n");
printf(" -n <frame number>\n");
printf(" -o <coded file>\n");
printf(" -f <frame rate>\n");
printf(" --intra_period <number>\n");
printf(" --idr_period <number>\n");
printf(" --ip_period <number>\n");
printf(" --bitrate <bitrate>\n");
printf(" --initialqp <number>\n");
printf(" --minqp <number>\n");
printf(" --rcmode <NONE|CBR|VBR|VCM|CQP|VBR_CONTRAINED>\n");
printf(" --srcyuv <filename> load YUV from a file\n");
printf(" --entropy <0|1>, 1 means cabac, 0 cavlc\n");
printf(" --profile <BP|MP|HP>\n");
printf(" --low_power <num> 0: Normal mode, 1: Low power mode, others: auto mode\n");
return 0;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
static int process_cmdline(int argc, char *argv[])
{
int c;
const struct option long_opts[] = {
{"help", no_argument, NULL, 0 },
{"bitrate", required_argument, NULL, 1 },
{"minqp", required_argument, NULL, 2 },
{"initialqp", required_argument, NULL, 3 },
{"intra_period", required_argument, NULL, 4 },
{"idr_period", required_argument, NULL, 5 },
{"ip_period", required_argument, NULL, 6 },
{"rcmode", required_argument, NULL, 7 },
{"srcyuv", required_argument, NULL, 9 },
{"prit", required_argument, NULL, 14 },
{"priv", required_argument, NULL, 15 },
{"framecount", required_argument, NULL, 16 },
{"entropy", required_argument, NULL, 17 },
{"profile", required_argument, NULL, 18 },
{"low_power", required_argument, NULL, 19 },
{NULL, no_argument, NULL, 0 }
};
int long_index;
while ((c = getopt_long_only(argc, argv, "w:h:n:f:o:?", long_opts, &long_index)) != EOF) {
switch (c) {
case 'w':
frame_width = atoi(optarg);
break;
case 'h':
frame_height = atoi(optarg);
break;
case 'n':
case 16:
frame_count = atoi(optarg);
break;
case 'f':
frame_rate = atoi(optarg);
break;
case 'o':
if (!coded_fn)
coded_fn = strdup(optarg);
assert(coded_fn);
break;
case 0:
print_help();
exit(0);
case 1:
frame_bitrate = atoi(optarg);
break;
case 2:
minimal_qp = atoi(optarg);
break;
case 3:
initial_qp = atoi(optarg);
break;
case 4:
intra_period = atoi(optarg);
break;
case 5:
intra_idr_period = atoi(optarg);
break;
case 6:
ip_period = atoi(optarg);
break;
case 7:
rc_mode = string_to_rc(optarg);
if (rc_mode < 0) {
print_help();
exit(1);
}
break;
case 9:
if (!srcyuv_fn)
srcyuv_fn = strdup(optarg);
assert(srcyuv_fn);
break;
case 14:
misc_priv_type = strtol(optarg, NULL, 0);
break;
case 15:
misc_priv_value = strtol(optarg, NULL, 0);
break;
case 17:
h264_entropy_mode = atoi(optarg) ? 1 : 0;
break;
case 18:
if (strncmp(optarg, "BP", 2) == 0)
h264_profile = VAProfileH264ConstrainedBaseline;
else if (strncmp(optarg, "MP", 2) == 0)
h264_profile = VAProfileH264Main;
else if (strncmp(optarg, "HP", 2) == 0)
h264_profile = VAProfileH264High;
else
h264_profile = 0;
break;
case 19: {
int lp_option = atoi(optarg);
if (lp_option == 0)
requested_entrypoint = VAEntrypointEncSlice; //normal 0
else if (lp_option == 1)
requested_entrypoint = VAEntrypointEncSliceLP; //low power 1
else
requested_entrypoint = -1;
}
break;
case ':':
case '?':
print_help();
exit(0);
}
}
if (ip_period < 1) {
printf(" ip_period must be greater than 0\n");
exit(0);
}
if (intra_period != 1 && intra_period % ip_period != 0) {
printf(" intra_period must be a multiplier of ip_period\n");
exit(0);
}
if (intra_period != 0 && intra_idr_period % intra_period != 0) {
printf(" intra_idr_period must be a multiplier of intra_period\n");
exit(0);
}
if (frame_bitrate == 0)
frame_bitrate = (long long int) frame_width * frame_height * 12 * frame_rate / 50;
/* open source file */
if (!srcyuv_fn) srcyuv_fn = strdup("/tmp/frame");
srcyuv_fp = fopen(srcyuv_fn, "r");
if (srcyuv_fp == NULL) {
printf("Open source YUV file %s failed\n", srcyuv_fn);
exit (1);
}
else {
srcyuv_frames = 1; // <-- source file contains only one frame
int mmap_size = frame_width * frame_height * 4;
srcyuv_ptr = (unsigned char *)mmap(0, mmap_size, PROT_READ, MAP_SHARED,
fileno(srcyuv_fp), 0);
if (srcyuv_ptr == MAP_FAILED) {
printf("Failed to mmap YUV file (%s)\n", strerror(errno));
exit(1);
}
nv12 = (unsigned char*) malloc( 3*mmap_size / 8);
if (nv12 == NULL) {
fprintf (stderr, "memory allocation error.\n");
exit (1);
}
}
/* result h264 file */
if (coded_fn == NULL) {
struct stat buf;
if (stat("/tmp", &buf) == 0)
coded_fn = strdup("/tmp/test.h264");
else if (stat("/sdcard", &buf) == 0)
coded_fn = strdup("/sdcard/test.h264");
else
coded_fn = strdup("./test.h264");
assert(coded_fn);
}
/* store coded data into a file */
coded_fp = fopen(coded_fn, "w+");
if (coded_fp == NULL) {
printf("Open file %s failed, exit\n", coded_fn);
exit(1);
}
frame_width_mbaligned = (frame_width + 15) & (~15);
frame_height_mbaligned = (frame_height + 15) & (~15);
if (frame_width != frame_width_mbaligned ||
frame_height != frame_height_mbaligned) {
printf("Source frame is %dx%d and will code clip to %dx%d with crop\n",
frame_width, frame_height,
frame_width_mbaligned, frame_height_mbaligned
);
}
return 0;
}
// -----------------------------------------------------------------------------
// Init VA engine
// -----------------------------------------------------------------------------
static int init_va(void)
{
VAProfile profile_list[] = {VAProfileH264High, VAProfileH264Main, VAProfileH264ConstrainedBaseline};
VAEntrypoint *entrypoints;
int num_entrypoints, slice_entrypoint;
int support_encode = 0;
int major_ver, minor_ver;
VAStatus va_status;
unsigned int i;
va_dpy = va_open_display_drm();
va_status = vaInitialize(va_dpy, &major_ver, &minor_ver);
CHECK_VASTATUS(va_status, "vaInitialize");
num_entrypoints = vaMaxNumEntrypoints(va_dpy);
entrypoints = malloc(num_entrypoints * sizeof(*entrypoints));
if (!entrypoints) {
fprintf(stderr, "error: failed to initialize VA entrypoints array\n");
exit(1);
}
/* use the highest profile */
for (i = 0; i < sizeof(profile_list) / sizeof(profile_list[0]); i++) {
if ((h264_profile != ~0) && h264_profile != profile_list[i])
continue;
h264_profile = profile_list[i];
vaQueryConfigEntrypoints(va_dpy, h264_profile, entrypoints, &num_entrypoints);
for (slice_entrypoint = 0; slice_entrypoint < num_entrypoints; slice_entrypoint++) {
if (requested_entrypoint == -1) {
//Select the entry point based on what is avaiable
if ((entrypoints[slice_entrypoint] == VAEntrypointEncSlice) ||
(entrypoints[slice_entrypoint] == VAEntrypointEncSliceLP)) {
support_encode = 1;
selected_entrypoint = entrypoints[slice_entrypoint];
break;
}
} else if ((entrypoints[slice_entrypoint] == requested_entrypoint)) {
//Select the entry point based on what was requested in cmd line option
support_encode = 1;
selected_entrypoint = entrypoints[slice_entrypoint];
break;
}
}
if (support_encode == 1) {
printf("Using EntryPoint - %d \n", selected_entrypoint);
break;
}
}
if (support_encode == 0) {
printf("Can't find VAEntrypointEncSlice or VAEntrypointEncSliceLP for H264 profiles\n");
exit(1);
} else {
switch (h264_profile) {
case VAProfileH264ConstrainedBaseline:
printf("Use profile VAProfileH264ConstrainedBaseline\n");
constraint_set_flag |= (1 << 0 | 1 << 1); /* Annex A.2.2 */