summaryrefslogtreecommitdiff
path: root/gst-libs/gst/vaapi/gstvaapiencoder.c
blob: bdb8d9ef49d4119a0e9cb9e6b907e9b1995c155e (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
/*
 *  gstvaapiencoder.c - VA encoder abstraction
 *
 *  Copyright (C) 2013-2014 Intel Corporation
 *    Author: Wind Yuan <feng.yuan@intel.com>
 *    Author: Gwenole Beauchesne <gwenole.beauchesne@intel.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301 USA
 */

#include "sysdeps.h"
#include "gstvaapicompat.h"
#include "gstvaapiencoder.h"
#include "gstvaapiencoder_priv.h"
#include "gstvaapicontext.h"
#include "gstvaapidisplay_priv.h"
#include "gstvaapiutils.h"
#include "gstvaapiutils_core.h"
#include "gstvaapivalue.h"

#define DEBUG 1
#include "gstvaapidebug.h"

/* Helper function to create a new encoder property object */
static GstVaapiEncoderPropData *
prop_new (gint id, GParamSpec * pspec)
{
  GstVaapiEncoderPropData *prop;

  if (!id || !pspec)
    return NULL;

  prop = g_slice_new (GstVaapiEncoderPropData);
  if (!prop)
    return NULL;

  prop->prop = id;
  prop->pspec = g_param_spec_ref_sink (pspec);
  return prop;
}

/* Helper function to release a property object and any memory held herein */
static void
prop_free (GstVaapiEncoderPropData * prop)
{
  if (!prop)
    return;

  if (prop->pspec) {
    g_param_spec_unref (prop->pspec);
    prop->pspec = NULL;
  }
  g_slice_free (GstVaapiEncoderPropData, prop);
}

/* Helper function to lookup the supplied property specification */
static GParamSpec *
prop_find_pspec (GstVaapiEncoder * encoder, gint prop_id)
{
  GPtrArray *const props = encoder->properties;
  guint i;

  if (props) {
    for (i = 0; i < props->len; i++) {
      GstVaapiEncoderPropInfo *const prop = g_ptr_array_index (props, i);
      if (prop->prop == prop_id)
        return prop->pspec;
    }
  }
  return NULL;
}

/* Create a new array of properties, or NULL on error */
GPtrArray *
gst_vaapi_encoder_properties_append (GPtrArray * props, gint prop_id,
    GParamSpec * pspec)
{
  GstVaapiEncoderPropData *prop;

  if (!props) {
    props = g_ptr_array_new_with_free_func ((GDestroyNotify) prop_free);
    if (!props)
      return NULL;
  }

  prop = prop_new (prop_id, pspec);
  if (!prop)
    goto error_allocation_failed;
  g_ptr_array_add (props, prop);
  return props;

  /* ERRORS */
error_allocation_failed:
  {
    GST_ERROR ("failed to allocate encoder property info structure");
    g_ptr_array_unref (props);
    return NULL;
  }
}

/* Generate the common set of encoder properties */
GPtrArray *
gst_vaapi_encoder_properties_get_default (const GstVaapiEncoderClass * klass)
{
  const GstVaapiEncoderClassData *const cdata = klass->class_data;
  GPtrArray *props = NULL;

  g_assert (cdata->rate_control_get_type != NULL);

  /**
   * GstVaapiEncoder:rate-control:
   *
   * The desired rate control mode, expressed as a #GstVaapiRateControl.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_RATECONTROL,
      g_param_spec_enum ("rate-control",
          "Rate Control", "Rate control mode",
          cdata->rate_control_get_type (), cdata->default_rate_control,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:bitrate:
   *
   * The desired bitrate, expressed in kbps.
   * This is available when rate-control is CBR or VBR.
   *
   * CBR: This applies equally to minimum, maximum and target bitrate in the driver.
   * VBR: This applies to maximum bitrate in the driver.
   *      Minimum bitrate will be calculated like the following in the driver.
   *          if (target percentage < 50) minimum bitrate = 0
   *          else minimum bitrate = maximum bitrate * (2 * target percentage -100) / 100
   *      Target bitrate will be calculated like the following in the driver.
   *          target bitrate = maximum bitrate * target percentage / 100
   *
   * Note that target percentage is set as 70 currently in GStreamer VA-API.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_BITRATE,
      g_param_spec_uint ("bitrate",
          "Bitrate (kbps)",
          "The desired bitrate expressed in kbps (0: auto-calculate)",
          0, 100 * 1024, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:keyframe-period:
   *
   * The maximal distance between two keyframes.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_KEYFRAME_PERIOD,
      g_param_spec_uint ("keyframe-period",
          "Keyframe Period",
          "Maximal distance between two keyframes (0: auto-calculate)", 1, 300,
          30, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:tune:
   *
   * The desired encoder tuning option.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_TUNE,
      g_param_spec_enum ("tune",
          "Encoder Tuning",
          "Encoder tuning option",
          cdata->encoder_tune_get_type (), cdata->default_encoder_tune,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:quality-level:
   *
   * The Encoding quality level.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_QUALITY_LEVEL,
      g_param_spec_uint ("quality-level",
          "Quality Level", "Encoding Quality Level "
          "(lower value means higher-quality/slow-encode, "
          " higher value means lower-quality/fast-encode)",
          1, 7, 4, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  return props;
}

gboolean
gst_vaapi_encoder_ensure_param_quality_level (GstVaapiEncoder * encoder,
    GstVaapiEncPicture * picture)
{
#if VA_CHECK_VERSION(0,36,0)
  GstVaapiEncMiscParam *misc;

  /* quality level param is not supported */
  if (GST_VAAPI_ENCODER_QUALITY_LEVEL (encoder) == 0)
    return TRUE;

  misc = GST_VAAPI_ENC_QUALITY_LEVEL_MISC_PARAM_NEW (encoder);
  if (!misc)
    return FALSE;
  memcpy (misc->data, &encoder->va_quality_level,
      sizeof (encoder->va_quality_level));
  gst_vaapi_enc_picture_add_misc_param (picture, misc);
  gst_vaapi_codec_object_replace (&misc, NULL);
#endif
  return TRUE;
}

gboolean
gst_vaapi_encoder_ensure_param_control_rate (GstVaapiEncoder * encoder,
    GstVaapiEncPicture * picture)
{
  GstVaapiEncMiscParam *misc;

  if (GST_VAAPI_ENCODER_RATE_CONTROL (encoder) == GST_VAAPI_RATECONTROL_CQP)
    return TRUE;

  /* RateControl params */
  misc = GST_VAAPI_ENC_MISC_PARAM_NEW (RateControl, encoder);
  if (!misc)
    return FALSE;
  memcpy (misc->data, &GST_VAAPI_ENCODER_VA_RATE_CONTROL (encoder),
      sizeof (VAEncMiscParameterRateControl));
  gst_vaapi_enc_picture_add_misc_param (picture, misc);
  gst_vaapi_codec_object_replace (&misc, NULL);

  /* HRD params */
  misc = GST_VAAPI_ENC_MISC_PARAM_NEW (HRD, encoder);
  if (!misc)
    return FALSE;
  memcpy (misc->data, &GST_VAAPI_ENCODER_VA_HRD (encoder),
      sizeof (VAEncMiscParameterHRD));
  gst_vaapi_enc_picture_add_misc_param (picture, misc);
  gst_vaapi_codec_object_replace (&misc, NULL);

  /* FrameRate params */
  if (GST_VAAPI_ENCODER_VA_FRAME_RATE (encoder).framerate == 0)
    return TRUE;

  misc = GST_VAAPI_ENC_MISC_PARAM_NEW (FrameRate, encoder);
  if (!misc)
    return FALSE;
  memcpy (misc->data, &GST_VAAPI_ENCODER_VA_FRAME_RATE (encoder),
      sizeof (VAEncMiscParameterFrameRate));
  gst_vaapi_enc_picture_add_misc_param (picture, misc);
  gst_vaapi_codec_object_replace (&misc, NULL);

  return TRUE;
}

/**
 * gst_vaapi_encoder_ref:
 * @encoder: a #GstVaapiEncoder
 *
 * Atomically increases the reference count of the given @encoder by one.
 *
 * Returns: The same @encoder argument
 */
GstVaapiEncoder *
gst_vaapi_encoder_ref (GstVaapiEncoder * encoder)
{
  return gst_vaapi_object_ref (encoder);
}

/**
 * gst_vaapi_encoder_unref:
 * @encoder: a #GstVaapiEncoder
 *
 * Atomically decreases the reference count of the @encoder by one. If
 * the reference count reaches zero, the encoder will be free'd.
 */
void
gst_vaapi_encoder_unref (GstVaapiEncoder * encoder)
{
  gst_vaapi_object_unref (encoder);
}

/**
 * gst_vaapi_encoder_replace:
 * @old_encoder_ptr: a pointer to a #GstVaapiEncoder
 * @new_encoder: a #GstVaapiEncoder
 *
 * Atomically replaces the encoder encoder held in @old_encoder_ptr
 * with @new_encoder. This means that @old_encoder_ptr shall reference
 * a valid encoder. However, @new_encoder can be NULL.
 */
void
gst_vaapi_encoder_replace (GstVaapiEncoder ** old_encoder_ptr,
    GstVaapiEncoder * new_encoder)
{
  gst_vaapi_object_replace (old_encoder_ptr, new_encoder);
}

/* Notifies gst_vaapi_encoder_create_coded_buffer() that a new buffer is free */
static void
_coded_buffer_proxy_released_notify (GstVaapiEncoder * encoder)
{
  g_mutex_lock (&encoder->mutex);
  g_cond_signal (&encoder->codedbuf_free);
  g_mutex_unlock (&encoder->mutex);
}

/* Creates a new VA coded buffer object proxy, backed from a pool */
static GstVaapiCodedBufferProxy *
gst_vaapi_encoder_create_coded_buffer (GstVaapiEncoder * encoder)
{
  GstVaapiCodedBufferPool *const pool =
      GST_VAAPI_CODED_BUFFER_POOL (encoder->codedbuf_pool);
  GstVaapiCodedBufferProxy *codedbuf_proxy;

  g_mutex_lock (&encoder->mutex);
  do {
    codedbuf_proxy = gst_vaapi_coded_buffer_proxy_new_from_pool (pool);
    if (codedbuf_proxy)
      break;

    /* Wait for a free coded buffer to become available */
    g_cond_wait (&encoder->codedbuf_free, &encoder->mutex);
    codedbuf_proxy = gst_vaapi_coded_buffer_proxy_new_from_pool (pool);
  } while (0);
  g_mutex_unlock (&encoder->mutex);
  if (!codedbuf_proxy)
    return NULL;

  gst_vaapi_coded_buffer_proxy_set_destroy_notify (codedbuf_proxy,
      (GDestroyNotify) _coded_buffer_proxy_released_notify, encoder);
  return codedbuf_proxy;
}

/* Notifies gst_vaapi_encoder_create_surface() that a new surface is free */
static void
_surface_proxy_released_notify (GstVaapiEncoder * encoder)
{
  g_mutex_lock (&encoder->mutex);
  g_cond_signal (&encoder->surface_free);
  g_mutex_unlock (&encoder->mutex);
}

/* Creates a new VA surface object proxy, backed from a pool and
   useful to allocate reconstructed surfaces */
GstVaapiSurfaceProxy *
gst_vaapi_encoder_create_surface (GstVaapiEncoder * encoder)
{
  GstVaapiSurfaceProxy *proxy;

  g_return_val_if_fail (encoder->context != NULL, NULL);

  g_mutex_lock (&encoder->mutex);
  for (;;) {
    proxy = gst_vaapi_context_get_surface_proxy (encoder->context);
    if (proxy)
      break;

    /* Wait for a free surface proxy to become available */
    g_cond_wait (&encoder->surface_free, &encoder->mutex);
  }
  g_mutex_unlock (&encoder->mutex);

  gst_vaapi_surface_proxy_set_destroy_notify (proxy,
      (GDestroyNotify) _surface_proxy_released_notify, encoder);
  return proxy;
}

/**
 * gst_vaapi_encoder_put_frame:
 * @encoder: a #GstVaapiEncoder
 * @frame: a #GstVideoCodecFrame
 *
 * Queues a #GstVideoCodedFrame to the HW encoder. The encoder holds
 * an extra reference to the @frame.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_put_frame (GstVaapiEncoder * encoder,
    GstVideoCodecFrame * frame)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);
  GstVaapiEncoderStatus status;
  GstVaapiEncPicture *picture;
  GstVaapiCodedBufferProxy *codedbuf_proxy;

  for (;;) {
    picture = NULL;
    status = klass->reordering (encoder, frame, &picture);
    if (status == GST_VAAPI_ENCODER_STATUS_NO_SURFACE)
      break;
    if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
      goto error_reorder_frame;

    codedbuf_proxy = gst_vaapi_encoder_create_coded_buffer (encoder);
    if (!codedbuf_proxy)
      goto error_create_coded_buffer;

    status = klass->encode (encoder, picture, codedbuf_proxy);
    if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
      goto error_encode;

    gst_vaapi_coded_buffer_proxy_set_user_data (codedbuf_proxy,
        picture, (GDestroyNotify) gst_vaapi_mini_object_unref);
    g_async_queue_push (encoder->codedbuf_queue, codedbuf_proxy);
    encoder->num_codedbuf_queued++;

    /* Try again with any pending reordered frame now available for encoding */
    frame = NULL;
  }
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_reorder_frame:
  {
    GST_ERROR ("failed to process reordered frames");
    return status;
  }
error_create_coded_buffer:
  {
    GST_ERROR ("failed to allocate coded buffer");
    gst_vaapi_enc_picture_unref (picture);
    return GST_VAAPI_ENCODER_STATUS_ERROR_ALLOCATION_FAILED;
  }
error_encode:
  {
    GST_ERROR ("failed to encode frame (status = %d)", status);
    gst_vaapi_enc_picture_unref (picture);
    gst_vaapi_coded_buffer_proxy_unref (codedbuf_proxy);
    return status;
  }
}

/**
 * gst_vaapi_encoder_get_buffer_with_timeout:
 * @encoder: a #GstVaapiEncoder
 * @out_codedbuf_proxy_ptr: the next coded buffer as a #GstVaapiCodedBufferProxy
 * @timeout: the number of microseconds to wait for the coded buffer, at most
 *
 * Upon successful return, *@out_codedbuf_proxy_ptr contains the next
 * coded buffer as a #GstVaapiCodedBufferProxy. The caller owns this
 * object, so gst_vaapi_coded_buffer_proxy_unref() shall be called
 * after usage. Otherwise, @GST_VAAPI_DECODER_STATUS_ERROR_NO_BUFFER
 * is returned if no coded buffer is available so far (timeout).
 *
 * The parent frame is available as a #GstVideoCodecFrame attached to
 * the user-data anchor of the output coded buffer. Ownership of the
 * frame is transferred to the coded buffer.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_get_buffer_with_timeout (GstVaapiEncoder * encoder,
    GstVaapiCodedBufferProxy ** out_codedbuf_proxy_ptr, guint64 timeout)
{
  GstVaapiEncPicture *picture;
  GstVaapiCodedBufferProxy *codedbuf_proxy;

  codedbuf_proxy = g_async_queue_timeout_pop (encoder->codedbuf_queue, timeout);
  if (!codedbuf_proxy)
    return GST_VAAPI_ENCODER_STATUS_NO_BUFFER;

  /* Wait for completion of all operations and report any error that occurred */
  picture = gst_vaapi_coded_buffer_proxy_get_user_data (codedbuf_proxy);
  if (!gst_vaapi_surface_sync (picture->surface))
    goto error_invalid_buffer;

  gst_vaapi_coded_buffer_proxy_set_user_data (codedbuf_proxy,
      gst_video_codec_frame_ref (picture->frame),
      (GDestroyNotify) gst_video_codec_frame_unref);

  if (out_codedbuf_proxy_ptr)
    *out_codedbuf_proxy_ptr = gst_vaapi_coded_buffer_proxy_ref (codedbuf_proxy);
  gst_vaapi_coded_buffer_proxy_unref (codedbuf_proxy);
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_invalid_buffer:
  {
    GST_ERROR ("failed to encode the frame");
    gst_vaapi_coded_buffer_proxy_unref (codedbuf_proxy);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_SURFACE;
  }
}

/**
 * gst_vaapi_encoder_flush:
 * @encoder: a #GstVaapiEncoder
 *
 * Submits any pending (reordered) frame for encoding.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_flush (GstVaapiEncoder * encoder)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);

  return klass->flush (encoder);
}

/**
 * gst_vaapi_encoder_get_codec_data:
 * @encoder: a #GstVaapiEncoder
 * @out_codec_data_ptr: the pointer to the resulting codec-data (#GstBuffer)
 *
 * Returns a codec-data buffer that best represents the encoded
 * bitstream. Upon successful return, and if the @out_codec_data_ptr
 * contents is not NULL, then the caller function shall deallocates
 * that buffer with gst_buffer_unref().
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_get_codec_data (GstVaapiEncoder * encoder,
    GstBuffer ** out_codec_data_ptr)
{
  GstVaapiEncoderStatus ret = GST_VAAPI_ENCODER_STATUS_SUCCESS;
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);

  *out_codec_data_ptr = NULL;
  if (!klass->get_codec_data)
    return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  ret = klass->get_codec_data (encoder, out_codec_data_ptr);
  return ret;
}

/* Checks video info */
static GstVaapiEncoderStatus
check_video_info (GstVaapiEncoder * encoder, const GstVideoInfo * vip)
{
  if (!vip->width || !vip->height)
    goto error_invalid_resolution;
  if (vip->fps_n < 0 || vip->fps_d <= 0)
    goto error_invalid_framerate;
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_invalid_resolution:
  {
    GST_ERROR ("invalid resolution (%dx%d)", vip->width, vip->height);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;
  }
error_invalid_framerate:
  {
    GST_ERROR ("invalid framerate (%d/%d)", vip->fps_n, vip->fps_d);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;
  }
}

/* Gets a compatible profile for the active codec */
static GstVaapiProfile
get_compatible_profile (GstVaapiEncoder * encoder)
{
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;
  GstVaapiProfile profile;
  GArray *profiles;
  guint i;

  profiles = gst_vaapi_display_get_encode_profiles (encoder->display);
  if (!profiles)
    return GST_VAAPI_PROFILE_UNKNOWN;

  // Pick a profile matching the class codec
  for (i = 0; i < profiles->len; i++) {
    profile = g_array_index (profiles, GstVaapiProfile, i);
    if (gst_vaapi_profile_get_codec (profile) == cdata->codec)
      break;
  }
  if (i == profiles->len)
    profile = GST_VAAPI_PROFILE_UNKNOWN;

  g_array_unref (profiles);
  return profile;
}

/* Gets a supported profile for the active codec */
static GstVaapiProfile
get_profile (GstVaapiEncoder * encoder)
{
  if (!encoder->profile)
    encoder->profile = get_compatible_profile (encoder);
  return encoder->profile;
}

/* Gets config attribute for the supplied profile */
static gboolean
get_config_attribute (GstVaapiEncoder * encoder, VAConfigAttribType type,
    guint * out_value_ptr)
{
  GstVaapiProfile profile;
  VAProfile va_profile;
  VAEntrypoint va_entrypoint;

  profile = get_profile (encoder);
  if (!profile)
    return FALSE;
  va_profile = gst_vaapi_profile_get_va_profile (profile);

  va_entrypoint =
      gst_vaapi_entrypoint_get_va_entrypoint (encoder->context_info.entrypoint);

  return gst_vaapi_get_config_attribute (encoder->display, va_profile,
      va_entrypoint, type, out_value_ptr);
}

/* Determines the set of supported packed headers */
static guint
get_packed_headers (GstVaapiEncoder * encoder)
{
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;
  guint value;

  if (encoder->got_packed_headers)
    return encoder->packed_headers;

  if (!get_config_attribute (encoder, VAConfigAttribEncPackedHeaders, &value))
    value = 0;
  GST_INFO ("supported packed headers: 0x%08x", value);

  encoder->got_packed_headers = TRUE;
  encoder->packed_headers = cdata->packed_headers & value;

  if (cdata->codec == GST_VAAPI_CODEC_JPEG) {
#if !VA_CHECK_VERSION(0,37,1)
    encoder->packed_headers = VA_ENC_PACKED_HEADER_RAW_DATA;
    GST_DEBUG ("Hard coding the packed header flag value to "
        "VA_ENC_PACKED_HEADER_RAW_DATA. This is a work around for the driver "
        "bug");
#endif
  }

  return encoder->packed_headers;
}

static gboolean
get_roi_capability (GstVaapiEncoder * encoder, guint * num_roi_supported)
{
#if VA_CHECK_VERSION(0,39,1)
  VAConfigAttribValEncROI *roi_config;
  guint value;

  if (!get_config_attribute (encoder, VAConfigAttribEncROI, &value))
    return FALSE;

  roi_config = (VAConfigAttribValEncROI *) & value;

  if (roi_config->bits.num_roi_regions == 0 ||
      roi_config->bits.roi_rc_qp_delat_support == 0)
    return FALSE;

  GST_INFO ("Support for ROI - number of regions supported: %d",
      roi_config->bits.num_roi_regions);

  *num_roi_supported = roi_config->bits.num_roi_regions;
  return TRUE;
#else
  return FALSE;
#endif
}

static inline gboolean
is_chroma_type_supported (GstVaapiEncoder * encoder)
{
  GstVaapiContextInfo *const cip = &encoder->context_info;
  const GstVideoFormat fmt =
      GST_VIDEO_INFO_FORMAT (GST_VAAPI_ENCODER_VIDEO_INFO (encoder));
  guint format = 0;

  if (fmt == GST_VIDEO_FORMAT_ENCODED)
    return TRUE;

  if (cip->chroma_type != GST_VAAPI_CHROMA_TYPE_YUV420 &&
      cip->chroma_type != GST_VAAPI_CHROMA_TYPE_YUV422 &&
      cip->chroma_type != GST_VAAPI_CHROMA_TYPE_YUV420_10BPP)
    goto unsupported;

  if (!get_config_attribute (encoder, VAConfigAttribRTFormat, &format))
    return FALSE;

  if (!(format & from_GstVaapiChromaType (cip->chroma_type)))
    goto unsupported;

  return TRUE;

  /* ERRORS */
unsupported:
  {
    GST_ERROR ("We only support YUV 4:2:0 and YUV 4:2:2 for encoding. "
        "Please try to use vaapipostproc to convert the input format.");
    return FALSE;
  }
}

static guint
get_default_chroma_type (GstVaapiEncoder * encoder,
    const GstVaapiContextInfo * cip)
{
  guint value;

  if (!gst_vaapi_get_config_attribute (encoder->display,
          gst_vaapi_profile_get_va_profile (cip->profile),
          gst_vaapi_entrypoint_get_va_entrypoint (cip->entrypoint),
          VAConfigAttribRTFormat, &value))
    return 0;

  return to_GstVaapiChromaType (value);
}

static void
init_context_info (GstVaapiEncoder * encoder, GstVaapiContextInfo * cip,
    GstVaapiProfile profile)
{
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;

  cip->usage = GST_VAAPI_CONTEXT_USAGE_ENCODE;
  cip->profile = profile;
  if (cdata->codec == GST_VAAPI_CODEC_JPEG) {
    cip->entrypoint = GST_VAAPI_ENTRYPOINT_PICTURE_ENCODE;
  } else {
    if (cip->entrypoint != GST_VAAPI_ENTRYPOINT_SLICE_ENCODE_LP)
      cip->entrypoint = GST_VAAPI_ENTRYPOINT_SLICE_ENCODE;
  }
  cip->chroma_type = get_default_chroma_type (encoder, cip);
  cip->width = 0;
  cip->height = 0;
  cip->ref_frames = encoder->num_ref_frames;
}

/* Updates video context */
static gboolean
set_context_info (GstVaapiEncoder * encoder)
{
  GstVaapiContextInfo *const cip = &encoder->context_info;
  GstVaapiConfigInfoEncoder *const config = &cip->config.encoder;
  const GstVideoFormat format =
      GST_VIDEO_INFO_FORMAT (GST_VAAPI_ENCODER_VIDEO_INFO (encoder));

  init_context_info (encoder, cip, get_profile (encoder));

  cip->chroma_type = gst_vaapi_video_format_get_chroma_type (format);
  cip->width = GST_VAAPI_ENCODER_WIDTH (encoder);
  cip->height = GST_VAAPI_ENCODER_HEIGHT (encoder);

  if (!is_chroma_type_supported (encoder))
    goto error_unsupported_format;

  memset (config, 0, sizeof (*config));
  config->rc_mode = GST_VAAPI_ENCODER_RATE_CONTROL (encoder);
  config->packed_headers = get_packed_headers (encoder);
  config->roi_capability =
      get_roi_capability (encoder, &config->roi_num_supported);

  return TRUE;

  /* ERRORS */
error_unsupported_format:
  {
    GST_ERROR ("failed to determine chroma type for format %s",
        gst_vaapi_video_format_to_string (format));
    return FALSE;
  }
}

/* Ensures the underlying VA context for encoding is created */
static gboolean
gst_vaapi_encoder_ensure_context (GstVaapiEncoder * encoder)
{
  GstVaapiContextInfo *const cip = &encoder->context_info;

  if (!set_context_info (encoder))
    return FALSE;

  if (encoder->context) {
    if (!gst_vaapi_context_reset (encoder->context, cip))
      return FALSE;
  } else {
    encoder->context = gst_vaapi_context_new (encoder->display, cip);
    if (!encoder->context)
      return FALSE;
  }
  encoder->va_context = gst_vaapi_context_get_id (encoder->context);
  return TRUE;
}

/* Reconfigures the encoder with the new properties */
static GstVaapiEncoderStatus
gst_vaapi_encoder_reconfigure_internal (GstVaapiEncoder * encoder)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);
  GstVideoInfo *const vip = GST_VAAPI_ENCODER_VIDEO_INFO (encoder);
  GstVaapiEncoderStatus status;
  GstVaapiVideoPool *pool;
  guint codedbuf_size, target_percentage;
  guint fps_d, fps_n;
#if VA_CHECK_VERSION(0,36,0)
  guint quality_level_max = 0;
#endif

  fps_d = GST_VIDEO_INFO_FPS_D (vip);
  fps_n = GST_VIDEO_INFO_FPS_N (vip);

  /* Generate a keyframe every second */
  if (!encoder->keyframe_period)
    encoder->keyframe_period = (fps_n + fps_d - 1) / fps_d;

  /* Default frame rate parameter */
  if (fps_d > 0 && fps_n > 0)
    GST_VAAPI_ENCODER_VA_FRAME_RATE (encoder).framerate = fps_d << 16 | fps_n;

  target_percentage =
      (GST_VAAPI_ENCODER_RATE_CONTROL (encoder) == GST_VAAPI_RATECONTROL_CBR) ?
      100 : 70;

  /* *INDENT-OFF* */
  /* Default values for rate control parameter */
  GST_VAAPI_ENCODER_VA_RATE_CONTROL (encoder) = (VAEncMiscParameterRateControl) {
    .bits_per_second = encoder->bitrate * 1000,
    .target_percentage = target_percentage,
    .window_size = 500,
  };
  /* *INDENT-ON* */

  status = klass->reconfigure (encoder);
  if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
    return status;

  if (!gst_vaapi_encoder_ensure_context (encoder))
    goto error_reset_context;

#if VA_CHECK_VERSION(0,36,0)
  if (get_config_attribute (encoder, VAConfigAttribEncQualityRange,
          &quality_level_max) && quality_level_max > 0) {
    GST_VAAPI_ENCODER_QUALITY_LEVEL (encoder) =
        CLAMP (GST_VAAPI_ENCODER_QUALITY_LEVEL (encoder), 1, quality_level_max);
  } else {
    GST_VAAPI_ENCODER_QUALITY_LEVEL (encoder) = 0;
  }
  GST_INFO ("Quality level is fixed to %d",
      GST_VAAPI_ENCODER_QUALITY_LEVEL (encoder));
#endif

  codedbuf_size = encoder->codedbuf_pool ?
      gst_vaapi_coded_buffer_pool_get_buffer_size (GST_VAAPI_CODED_BUFFER_POOL
      (encoder)) : 0;
  if (codedbuf_size != encoder->codedbuf_size) {
    pool = gst_vaapi_coded_buffer_pool_new (encoder, encoder->codedbuf_size);
    if (!pool)
      goto error_alloc_codedbuf_pool;
    gst_vaapi_video_pool_set_capacity (pool, 5);
    gst_vaapi_video_pool_replace (&encoder->codedbuf_pool, pool);
    gst_vaapi_video_pool_unref (pool);
  }
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_alloc_codedbuf_pool:
  {
    GST_ERROR ("failed to initialize coded buffer pool");
    return GST_VAAPI_ENCODER_STATUS_ERROR_ALLOCATION_FAILED;
  }
error_reset_context:
  {
    GST_ERROR ("failed to update VA context");
    return GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED;
  }
}

/**
 * gst_vaapi_encoder_set_codec_state:
 * @encoder: a #GstVaapiEncoder
 * @state : a #GstVideoCodecState
 *
 * Notifies the encoder about the source surface properties. The
 * accepted set of properties is: video resolution, colorimetry,
 * pixel-aspect-ratio and framerate.
 *
 * This function is a synchronization point for codec configuration.
 * This means that, at this point, the encoder is reconfigured to
 * match the new properties and any other change beyond this point has
 * zero effect.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_set_codec_state (GstVaapiEncoder * encoder,
    GstVideoCodecState * state)
{
  GstVaapiEncoderStatus status;

  g_return_val_if_fail (encoder != NULL,
      GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER);
  g_return_val_if_fail (state != NULL,
      GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER);

  if (!gst_video_info_is_equal (&state->info, &encoder->video_info)) {
    status = check_video_info (encoder, &state->info);
    if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
      return status;
    encoder->video_info = state->info;
  }
  return gst_vaapi_encoder_reconfigure_internal (encoder);
}

/**
 * gst_vaapi_encoder_set_property:
 * @encoder: a #GstVaapiEncoder
 * @prop_id: the id of the property to change
 * @value: the new value to set
 *
 * Update the requested property, designed by @prop_id, with the
 * supplied @value. A @NULL value argument resets the property to its
 * default value.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
static GstVaapiEncoderStatus
set_property (GstVaapiEncoder * encoder, gint prop_id, const GValue * value)
{
  GstVaapiEncoderStatus status =
      GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;

  g_assert (value != NULL);

  /* Handle codec-specific properties */
  if (prop_id < 0) {
    GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);

    if (klass->set_property) {
      if (encoder->num_codedbuf_queued > 0)
        goto error_operation_failed;
      status = klass->set_property (encoder, prop_id, value);
    }
    return status;
  }

  /* Handle common properties */
  switch (prop_id) {
    case GST_VAAPI_ENCODER_PROP_RATECONTROL:
      status = gst_vaapi_encoder_set_rate_control (encoder,
          g_value_get_enum (value));
      break;
    case GST_VAAPI_ENCODER_PROP_BITRATE:
      status = gst_vaapi_encoder_set_bitrate (encoder,
          g_value_get_uint (value));
      break;
    case GST_VAAPI_ENCODER_PROP_KEYFRAME_PERIOD:
      status = gst_vaapi_encoder_set_keyframe_period (encoder,
          g_value_get_uint (value));
      break;
    case GST_VAAPI_ENCODER_PROP_TUNE:
      status = gst_vaapi_encoder_set_tuning (encoder, g_value_get_enum (value));
      break;
    case GST_VAAPI_ENCODER_PROP_QUALITY_LEVEL:
      status = gst_vaapi_encoder_set_quality_level (encoder,
          g_value_get_uint (value));
      break;
  }
  return status;

  /* ERRORS */
error_operation_failed:
  {
    GST_ERROR ("could not change codec state after encoding started");
    return GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED;
  }
}

GstVaapiEncoderStatus
gst_vaapi_encoder_set_property (GstVaapiEncoder * encoder, gint prop_id,
    const GValue * value)
{
  GstVaapiEncoderStatus status;
  GValue default_value = G_VALUE_INIT;

  g_return_val_if_fail (encoder != NULL,
      GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER);

  if (!value) {
    GParamSpec *const pspec = prop_find_pspec (encoder, prop_id);
    if (!pspec)
      goto error_invalid_property;

    g_value_init (&default_value, pspec->value_type);
    g_param_value_set_default (pspec, &default_value);
    value = &default_value;
  }

  status = set_property (encoder, prop_id, value);

  if (default_value.g_type)
    g_value_unset (&default_value);
  return status;

  /* ERRORS */
error_invalid_property:
  {
    GST_ERROR ("unsupported property (%d)", prop_id);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;
  }
}

/* Determine the supported rate control modes */
static guint
get_rate_control_mask (GstVaapiEncoder * encoder)
{
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;
  guint i, value, rate_control_mask = 0;

  if (encoder->got_rate_control_mask)
    return encoder->rate_control_mask;

  if (get_config_attribute (encoder, VAConfigAttribRateControl, &value)) {
    for (i = 0; i < 32; i++) {
      if (!(value & (1U << i)))
        continue;
      rate_control_mask |= 1 << to_GstVaapiRateControl (1 << i);
    }
    GST_INFO ("supported rate controls: 0x%08x", rate_control_mask);

    encoder->got_rate_control_mask = TRUE;
    encoder->rate_control_mask = cdata->rate_control_mask & rate_control_mask;
  }

  return encoder->rate_control_mask;
}

/**
 * gst_vaapi_encoder_set_rate_control:
 * @encoder: a #GstVaapiEncoder
 * @rate_control: the requested rate control
 *
 * Notifies the @encoder to use the supplied @rate_control mode.
 *
 * If the underlying encoder does not support that rate control mode,
 * then @GST_VAAPI_ENCODER_STATUS_ERROR_UNSUPPORTED_RATE_CONTROL is
 * returned.
 *
 * The rate control mode can only be specified before the first frame
 * is to be encoded. Afterwards, any change to this parameter is
 * invalid and @GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED is
 * returned.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_set_rate_control (GstVaapiEncoder * encoder,
    GstVaapiRateControl rate_control)
{
  guint32 rate_control_mask;

  g_return_val_if_fail (encoder != NULL,
      GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER);

  if (encoder->rate_control != rate_control && encoder->num_codedbuf_queued > 0)
    goto error_operation_failed;

  rate_control_mask = get_rate_control_mask (encoder);
  if (rate_control_mask && !(rate_control_mask & (1U << rate_control)))
    goto error_unsupported_rate_control;

  encoder->rate_control = rate_control;
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_operation_failed:
  {
    GST_ERROR ("could not change rate control mode after encoding started");
    return GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED;
  }
error_unsupported_rate_control:
  {
    GST_ERROR ("unsupported rate control mode (%d)", rate_control);
    return GST_VAAPI_ENCODER_STATUS_ERROR_UNSUPPORTED_RATE_CONTROL;
  }
}

/**
 * gst_vaapi_encoder_set_bitrate:
 * @encoder: a #GstVaapiEncoder
 * @bitrate: the requested bitrate (in kbps)
 *
 * Notifies the @encoder to use the supplied @bitrate value.
 *
 * Note: currently, the bitrate can only be specified before the first
 * frame is encoded. Afterwards, any change to this parameter is
 * invalid and @GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED is
 * returned.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_set_bitrate (GstVaapiEncoder * encoder, guint bitrate)
{
  g_return_val_if_fail (encoder != NULL, 0);

  if (encoder->bitrate != bitrate && encoder->num_codedbuf_queued > 0)
    goto error_operation_failed;

  encoder->bitrate = bitrate;
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_operation_failed:
  {
    GST_ERROR ("could not change bitrate value after encoding started");
    return GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED;
  }
}

/**
 * gst_vaapi_encoder_set_keyframe_period:
 * @encoder: a #GstVaapiEncoder
 * @keyframe_period: the maximal distance between two keyframes
 *
 * Notifies the @encoder to use the supplied @keyframe_period value.
 *
 * Note: currently, the keyframe period can only be specified before
 * the last call to gst_vaapi_encoder_set_codec_state(), which shall
 * occur before the first frame is encoded. Afterwards, any change to
 * this parameter causes gst_vaapi_encoder_set_keyframe_period() to
 * return @GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_set_keyframe_period (GstVaapiEncoder * encoder,
    guint keyframe_period)
{
  g_return_val_if_fail (encoder != NULL, 0);

  if (encoder->keyframe_period != keyframe_period
      && encoder->num_codedbuf_queued > 0)
    goto error_operation_failed;

  encoder->keyframe_period = keyframe_period;
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_operation_failed:
  {
    GST_ERROR ("could not change keyframe period after encoding started");
    return GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED;
  }
}

/**
 * gst_vaapi_encoder_set_tuning:
 * @encoder: a #GstVaapiEncoder
 * @tuning: the #GstVaapiEncoderTune option
 *
 * Notifies the @encoder to use the supplied @tuning option.
 *
 * Note: currently, the tuning option can only be specified before the
 * last call to gst_vaapi_encoder_set_codec_state(), which shall occur
 * before the first frame is encoded. Afterwards, any change to this
 * parameter causes gst_vaapi_encoder_set_tuning() to return
 * @GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_set_tuning (GstVaapiEncoder * encoder,
    GstVaapiEncoderTune tuning)
{
  g_return_val_if_fail (encoder != NULL, 0);

  if (encoder->tune != tuning && encoder->num_codedbuf_queued > 0)
    goto error_operation_failed;

  encoder->tune = tuning;
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_operation_failed:
  {
    GST_ERROR ("could not change tuning options after encoding started");
    return GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED;
  }
}

/**
 * gst_vaapi_encoder_set_quality_level:
 * @encoder: a #GstVaapiEncoder
 * @quality_level: the encoder quality level
 *
 * Notifies the @encoder to use the supplied @quality_level value.
 *
 * Note: currently, the quality_level can only be specified before
 * the last call to gst_vaapi_encoder_set_codec_state(), which shall
 * occur before the first frame is encoded. Afterwards, any change to
 * this parameter causes gst_vaapi_encoder_set_quality_level() to
 * return @GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_set_quality_level (GstVaapiEncoder * encoder,
    guint quality_level)
{
  g_return_val_if_fail (encoder != NULL, 0);

  if (GST_VAAPI_ENCODER_QUALITY_LEVEL (encoder) != quality_level
      && encoder->num_codedbuf_queued > 0)
    goto error_operation_failed;

  GST_VAAPI_ENCODER_QUALITY_LEVEL (encoder) = quality_level;
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_operation_failed:
  {
    GST_ERROR ("could not change quality level after encoding started");
    return GST_VAAPI_ENCODER_STATUS_ERROR_OPERATION_FAILED;
  }
}

/* Initialize default values for configurable properties */
static gboolean
gst_vaapi_encoder_init_properties (GstVaapiEncoder * encoder)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);
  GPtrArray *props;
  guint i;

  props = klass->get_default_properties ();
  if (!props)
    return FALSE;

  encoder->properties = props;
  for (i = 0; i < props->len; i++) {
    GstVaapiEncoderPropInfo *const prop = g_ptr_array_index (props, i);

    if (gst_vaapi_encoder_set_property (encoder, prop->prop,
            NULL) != GST_VAAPI_ENCODER_STATUS_SUCCESS)
      return FALSE;
  }
  return TRUE;
}

/* Base encoder initialization (internal) */
static gboolean
gst_vaapi_encoder_init (GstVaapiEncoder * encoder, GstVaapiDisplay * display)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);

  g_return_val_if_fail (display != NULL, FALSE);

#define CHECK_VTABLE_HOOK(FUNC) do {            \
    if (!klass->FUNC)                           \
      goto error_invalid_vtable;                \
  } while (0)

  CHECK_VTABLE_HOOK (init);
  CHECK_VTABLE_HOOK (finalize);
  CHECK_VTABLE_HOOK (get_default_properties);
  CHECK_VTABLE_HOOK (reconfigure);
  CHECK_VTABLE_HOOK (encode);
  CHECK_VTABLE_HOOK (reordering);
  CHECK_VTABLE_HOOK (flush);

#undef CHECK_VTABLE_HOOK

  encoder->display = gst_vaapi_display_ref (display);
  encoder->va_display = gst_vaapi_display_get_display (display);
  encoder->va_context = VA_INVALID_ID;

  gst_video_info_init (&encoder->video_info);

  g_mutex_init (&encoder->mutex);
  g_cond_init (&encoder->surface_free);
  g_cond_init (&encoder->codedbuf_free);

  encoder->codedbuf_queue = g_async_queue_new_full ((GDestroyNotify)
      gst_vaapi_coded_buffer_proxy_unref);
  if (!encoder->codedbuf_queue)
    return FALSE;

  if (!klass->init (encoder))
    return FALSE;
  if (!gst_vaapi_encoder_init_properties (encoder))
    return FALSE;
  return TRUE;

  /* ERRORS */
error_invalid_vtable:
  {
    GST_ERROR ("invalid subclass hook (internal error)");
    return FALSE;
  }
}

/* Base encoder cleanup (internal) */
void
gst_vaapi_encoder_finalize (GstVaapiEncoder * encoder)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);

  klass->finalize (encoder);

  if (encoder->roi_regions)
    g_list_free_full (encoder->roi_regions, g_free);

  gst_vaapi_object_replace (&encoder->context, NULL);
  gst_vaapi_display_replace (&encoder->display, NULL);
  encoder->va_display = NULL;

  if (encoder->properties) {
    g_ptr_array_unref (encoder->properties);
    encoder->properties = NULL;
  }

  gst_vaapi_video_pool_replace (&encoder->codedbuf_pool, NULL);
  if (encoder->codedbuf_queue) {
    g_async_queue_unref (encoder->codedbuf_queue);
    encoder->codedbuf_queue = NULL;
  }
  g_cond_clear (&encoder->surface_free);
  g_cond_clear (&encoder->codedbuf_free);
  g_mutex_clear (&encoder->mutex);
}

/* Helper function to create new GstVaapiEncoder instances (internal) */
GstVaapiEncoder *
gst_vaapi_encoder_new (const GstVaapiEncoderClass * klass,
    GstVaapiDisplay * display)
{
  GstVaapiEncoder *encoder;

  encoder = (GstVaapiEncoder *)
      gst_vaapi_mini_object_new0 (GST_VAAPI_MINI_OBJECT_CLASS (klass));
  if (!encoder)
    return NULL;

  if (!gst_vaapi_encoder_init (encoder, display))
    goto error;
  return encoder;

  /* ERRORS */
error:
  {
    gst_vaapi_encoder_unref (encoder);
    return NULL;
  }
}

static GstVaapiContext *
create_test_context_config (GstVaapiEncoder * encoder, GstVaapiProfile profile)
{
  GstVaapiContextInfo cip = { 0, };
  GstVaapiContext *ctxt;

  if (encoder->context)
    return gst_vaapi_object_ref (encoder->context);

  /* if there is no profile, let's figure out one */
  if (profile == GST_VAAPI_PROFILE_UNKNOWN)
    profile = get_profile (encoder);

  init_context_info (encoder, &cip, profile);
  ctxt = gst_vaapi_context_new (encoder->display, &cip);
  return ctxt;
}

static GArray *
get_profile_surface_formats (GstVaapiEncoder * encoder, GstVaapiProfile profile)
{
  GstVaapiContext *ctxt;
  GArray *formats;

  ctxt = create_test_context_config (encoder, profile);
  if (!ctxt)
    return NULL;
  formats = gst_vaapi_context_get_surface_formats (ctxt);
  gst_vaapi_object_unref (ctxt);
  return formats;
}

static gboolean
merge_profile_surface_formats (GstVaapiEncoder * encoder,
    GstVaapiProfile profile, GArray * formats)
{
  GArray *surface_fmts;
  guint i, j;
  GstVideoFormat fmt, sfmt;

  if (profile == GST_VAAPI_PROFILE_UNKNOWN)
    return FALSE;

  surface_fmts = get_profile_surface_formats (encoder, profile);
  if (!surface_fmts)
    return FALSE;

  for (i = 0; i < surface_fmts->len; i++) {
    sfmt = g_array_index (surface_fmts, GstVideoFormat, i);
    for (j = 0; j < formats->len; j++) {
      fmt = g_array_index (formats, GstVideoFormat, j);
      if (fmt == sfmt)
        break;
    }
    if (j >= formats->len)
      g_array_append_val (formats, sfmt);
  }

  g_array_unref (surface_fmts);
  return TRUE;
}

/**
 * gst_vaapi_encoder_get_surface_formats:
 * @encoder: a #GstVaapiEncoder instances
 *
 * Fetches the valid surface formats for the current VAConfig
 *
 * Returns: a #GArray of valid formats for the current VAConfig
 **/
GArray *
gst_vaapi_encoder_get_surface_formats (GstVaapiEncoder * encoder,
    GstVaapiProfile profile)
{
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;
  GArray *profiles, *formats;
  guint i;

  if (profile || encoder->context)
    return get_profile_surface_formats (encoder, profile);

  /* no specific context neither specific profile, let's iterate among
   * the codec's profiles */
  profiles = gst_vaapi_display_get_encode_profiles (encoder->display);
  if (!profiles)
    return NULL;

  formats = g_array_new (FALSE, FALSE, sizeof (GstVideoFormat));
  for (i = 0; i < profiles->len; i++) {
    profile = g_array_index (profiles, GstVaapiProfile, i);
    if (gst_vaapi_profile_get_codec (profile) == cdata->codec) {
      if (!merge_profile_surface_formats (encoder, profile, formats)) {
        g_array_unref (formats);
        formats = NULL;
        break;
      }
    }
  }

  g_array_unref (profiles);

  return formats;
}

/**
 * gst_vaapi_encoder_ensure_num_slices:
 * @encoder: a #GstVaapiEncoder
 * @profile: a #GstVaapiProfile
 * @entrypoint: a #GstVaapiEntrypoint
 * @media_max_slices: the number of the slices permitted by the stream
 * @num_slices: (out): the possible number of slices to process
 *
 * This function will clamp the @num_slices provided by the user,
 * according the limit of the number of slices permitted by the stream
 * and by the hardware.
 *
 * We need to pass the @profile and the @entrypoint, because at the
 * moment the encoder base class, still doesn't have them assigned,
 * and this function is meant to be called by the derived classes
 * while they are configured.
 *
 * Returns: %TRUE if the number of slices is different than zero.
 **/
gboolean
gst_vaapi_encoder_ensure_num_slices (GstVaapiEncoder * encoder,
    GstVaapiProfile profile, GstVaapiEntrypoint entrypoint,
    guint media_max_slices, guint * num_slices)
{
  VAProfile va_profile;
  VAEntrypoint va_entrypoint;
  guint max_slices, num;

  va_profile = gst_vaapi_profile_get_va_profile (profile);
  va_entrypoint = gst_vaapi_entrypoint_get_va_entrypoint (entrypoint);

  if (!gst_vaapi_get_config_attribute (encoder->display, va_profile,
          va_entrypoint, VAConfigAttribEncMaxSlices, &max_slices)) {
    *num_slices = 1;
    return TRUE;
  }

  num = *num_slices;
  if (num > max_slices)
    num = max_slices;
  if (num > media_max_slices)
    num = media_max_slices;

  if (num == 0)
    return FALSE;
  *num_slices = num;
  return TRUE;
}

/**
 * gst_vaapi_encoder_add_roi:
 * @encoder: a #GstVaapiEncoder
 * @roi: (transfer none): a #GstVaapiROI
 *
 * Adds a roi region provided by user.
 *
 * This can be called on running a pipeline,
 * Since vaapi encoder set roi regions at every frame encoding.
 * Note that if it exceeds number of supported roi in driver,
 * this will return FALSE.
 *
 * Return value: a #gboolean
 */
gboolean
gst_vaapi_encoder_add_roi (GstVaapiEncoder * encoder, GstVaapiROI * roi)
{
  GstVaapiContextInfo *const cip = &encoder->context_info;
  const GstVaapiConfigInfoEncoder *const config = &cip->config.encoder;
  GstVaapiROI *region = NULL;
  GList *walk;

  g_return_val_if_fail (roi != NULL, FALSE);

  if (!config->roi_capability)
    return FALSE;

  if (encoder->roi_regions &&
      g_list_length (encoder->roi_regions) > config->roi_num_supported)
    return FALSE;

  walk = encoder->roi_regions;
  while (walk) {
    GstVaapiROI *region_ptr = (GstVaapiROI *) walk->data;
    if (region_ptr->rect.x == roi->rect.x &&
        region_ptr->rect.y == roi->rect.y &&
        region_ptr->rect.width == roi->rect.width &&
        region_ptr->rect.height == roi->rect.height) {
      /* Duplicated region */
      goto end;
    }
    walk = walk->next;
  }

  region = g_malloc0 (sizeof (GstVaapiROI));
  if (G_UNLIKELY (!region))
    return FALSE;

  region->rect.x = roi->rect.x;
  region->rect.y = roi->rect.y;
  region->rect.width = roi->rect.width;
  region->rect.height = roi->rect.height;

  encoder->roi_regions = g_list_append (encoder->roi_regions, region);

end:
  return TRUE;
}

/**
 * gst_vaapi_encoder_del_roi:
 * @encoder: a #GstVaapiEncoder
 * @roi: (transfer none): a #GstVaapiROI
 *
 * Deletes a roi region provided by user.
 *
 * This can be called on running a pipeline,
 * Since vaapi encoder set roi regions at every frame encoding.
 *
 * Return value: a #gboolean
 */
gboolean
gst_vaapi_encoder_del_roi (GstVaapiEncoder * encoder, GstVaapiROI * roi)
{
  GstVaapiContextInfo *const cip = &encoder->context_info;
  const GstVaapiConfigInfoEncoder *const config = &cip->config.encoder;
  GList *walk;
  gboolean ret = FALSE;

  g_return_val_if_fail (roi != NULL, FALSE);

  if (!config->roi_capability)
    return FALSE;

  if (encoder->roi_regions && g_list_length (encoder->roi_regions) == 0)
    return FALSE;

  walk = encoder->roi_regions;
  while (walk) {
    GstVaapiROI *region = (GstVaapiROI *) walk->data;
    if (region->rect.x == roi->rect.x &&
        region->rect.y == roi->rect.y &&
        region->rect.width == roi->rect.width &&
        region->rect.height == roi->rect.height) {
      encoder->roi_regions = g_list_remove (encoder->roi_regions, region);
      g_free (region);
      ret = TRUE;
      break;
    }
    walk = walk->next;
  }

  return ret;
}

/** Returns a GType for the #GstVaapiEncoderTune set */
GType
gst_vaapi_encoder_tune_get_type (void)
{
  static volatile gsize g_type = 0;

  static const GEnumValue encoder_tune_values[] = {
    /* *INDENT-OFF* */
    { GST_VAAPI_ENCODER_TUNE_NONE,
      "None", "none" },
    { GST_VAAPI_ENCODER_TUNE_HIGH_COMPRESSION,
      "High compression", "high-compression" },
    { GST_VAAPI_ENCODER_TUNE_LOW_LATENCY,
      "Low latency", "low-latency" },
    { GST_VAAPI_ENCODER_TUNE_LOW_POWER,
      "Low power mode", "low-power" },
    { 0, NULL, NULL },
    /* *INDENT-ON* */
  };

  if (g_once_init_enter (&g_type)) {
    GType type =
        g_enum_register_static ("GstVaapiEncoderTune", encoder_tune_values);
    g_once_init_leave (&g_type, type);
  }
  return g_type;
}