forked from HandBrake/HandBrake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
enc_qsv.c
2076 lines (1887 loc) · 72.3 KB
/
enc_qsv.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
/* ********************************************************************* *\
Copyright (C) 2013 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\* ********************************************************************* */
#ifdef USE_QSV
#include "hb.h"
#include "nal_units.h"
#include "qsv_common.h"
#include "qsv_memory.h"
#include "h264_common.h"
#include "h265_common.h"
/*
* The frame info struct remembers information about each frame across calls to
* the encoder. Since frames are uniquely identified by their timestamp, we use
* some bits of the timestamp as an index. The LSB is chosen so that two
* successive frames will have different values in the bits over any plausible
* range of frame rates (starting with bit 8 allows any frame rate slower than
* 352fps). The MSB determines the size of the array. It is chosen so that two
* frames can't use the same slot during the encoder's max frame delay so that,
* up to some minimum frame rate, frames are guaranteed to map to different
* slots (an MSB of 17 which is 2^(17-8+1) = 1024 slots guarantees no collisions
* down to a rate of 0.7 fps).
*/
#define FRAME_INFO_MAX2 (8) // 2^8 = 256; 90000/256 = 352 frames/sec
#define FRAME_INFO_MIN2 (17) // 2^17 = 128K; 90000/131072 = 0.7 frames/sec
#define FRAME_INFO_SIZE (1 << (FRAME_INFO_MIN2 - FRAME_INFO_MAX2 + 1))
#define FRAME_INFO_MASK (FRAME_INFO_SIZE - 1)
int encqsvInit (hb_work_object_t*, hb_job_t*);
int encqsvWork (hb_work_object_t*, hb_buffer_t**, hb_buffer_t**);
void encqsvClose(hb_work_object_t*);
hb_work_object_t hb_encqsv =
{
WORK_ENCQSV,
"Quick Sync Video encoder (Intel Media SDK)",
encqsvInit,
encqsvWork,
encqsvClose
};
struct hb_work_private_s
{
hb_job_t * job;
uint32_t frames_in;
uint32_t frames_out;
int64_t last_start;
hb_qsv_param_t param;
av_qsv_space enc_space;
hb_qsv_info_t * qsv_info;
hb_list_t * delayed_chapters;
int64_t next_chapter_pts;
#define BFRM_DELAY_MAX 16
int * init_delay;
int bfrm_delay;
int64_t init_pts[BFRM_DELAY_MAX + 1];
hb_list_t * list_dts;
int64_t frame_duration[FRAME_INFO_SIZE];
int async_depth;
int max_async_depth;
// if encode-only, system memory used
int is_sys_mem;
mfxSession mfx_session;
struct SwsContext * sws_context_to_nv12;
// whether to expect input from VPP or from QSV decode
int is_vpp_present;
// whether the encoder is initialized
int init_done;
hb_list_t * delayed_processing;
hb_buffer_list_t encoded_frames;
hb_list_t * loaded_plugins;
};
// used in delayed_chapters list
struct chapter_s
{
int index;
int64_t start;
};
static void hb_qsv_add_new_dts(hb_list_t *list, int64_t new_dts)
{
if (list != NULL)
{
int64_t *item = malloc(sizeof(int64_t));
if (item != NULL)
{
*item = new_dts;
hb_list_add(list, item);
}
}
}
static int64_t hb_qsv_pop_next_dts(hb_list_t *list)
{
int64_t next_dts = INT64_MIN;
if (list != NULL && hb_list_count(list) > 0)
{
int64_t *item = hb_list_item(list, 0);
if (item != NULL)
{
next_dts = *item;
hb_list_rem(list, item);
free(item);
}
}
return next_dts;
}
static void save_frame_duration(hb_work_private_t *pv, hb_buffer_t *buf)
{
int i = (buf->s.start >> FRAME_INFO_MAX2) & FRAME_INFO_MASK;
pv->frame_duration[i] = buf->s.stop - buf->s.start;
}
static int64_t get_frame_duration(hb_work_private_t *pv, hb_buffer_t *buf)
{
int i = (buf->s.start >> FRAME_INFO_MAX2) & FRAME_INFO_MASK;
return pv->frame_duration[i];
}
static void qsv_handle_breftype(hb_work_private_t *pv)
{
/*
* If B-pyramid is not possible (not supported, incompatible profile, etc.)
* we don't need to adjust any settings, just sanitize it to off and return.
*/
if (!(pv->qsv_info->capabilities & HB_QSV_CAP_B_REF_PYRAMID))
{
/* B-pyramid support not implemented */
goto unsupported;
}
else if (pv->param.videoParam->mfx.GopPicSize &&
pv->param.videoParam->mfx.GopPicSize <= 3)
{
/* GOP size must be at least 4 for B-pyramid */
goto unsupported;
}
else if (pv->param.videoParam->mfx.GopRefDist &&
pv->param.videoParam->mfx.GopRefDist <= 2)
{
/* We need 2 consecutive B-frames for B-pyramid (GopRefDist >= 3) */
goto unsupported;
}
else if (pv->param.videoParam->mfx.CodecId == MFX_CODEC_AVC)
{
switch (pv->param.videoParam->mfx.CodecProfile)
{
case MFX_PROFILE_AVC_BASELINE:
case MFX_PROFILE_AVC_CONSTRAINED_HIGH:
case MFX_PROFILE_AVC_CONSTRAINED_BASELINE:
goto unsupported; // B-frames not allowed by profile
default:
break;
}
}
else if (pv->param.videoParam->mfx.CodecId == MFX_CODEC_HEVC)
{
switch (pv->param.videoParam->mfx.CodecProfile)
{
case MFX_PROFILE_HEVC_MAINSP:
goto unsupported; // B-frames not allowed by profile
default:
break;
}
}
/* Handle B-pyramid auto (on for CQP, off otherwise) */
if (pv->param.gop.b_pyramid < 0)
{
pv->param.gop.b_pyramid = pv->param.videoParam->mfx.RateControlMethod == MFX_RATECONTROL_CQP;
}
if (pv->qsv_info->capabilities & HB_QSV_CAP_OPTION2_BREFTYPE)
{
/* B-pyramid can be controlled directly */
if (pv->param.gop.b_pyramid)
{
pv->param.codingOption2.BRefType = MFX_B_REF_PYRAMID;
}
else
{
pv->param.codingOption2.BRefType = MFX_B_REF_OFF;
}
}
else
{
/*
* We can't control B-pyramid directly, do it indirectly by
* adjusting GopRefDist, GopPicSize and NumRefFrame instead.
*/
pv->param.codingOption2.BRefType = MFX_B_REF_UNKNOWN;
/*
* pyramid_ref_dist is the closest B-pyramid compatible
* value (multiple of 2, >= 4) to the requested GopRefDist.
*/
int pyramid_ref_dist = 4;
while (pv->param.videoParam->mfx.GopRefDist > pyramid_ref_dist)
{
pyramid_ref_dist *= 2;
}
if (pv->param.gop.b_pyramid)
{
/* GopRefDist must be B-pyramid compatible */
pv->param.videoParam->mfx.GopRefDist = pyramid_ref_dist;
/*
* GopPicSize must be a multiple of GopRefDist.
*
* Note: GopPicSize == 0 should always result in a value
* that doesn't cause Media SDK to disable B-pyramid.
*/
if (pv->param.videoParam->mfx.GopPicSize)
{
pv->param.videoParam->mfx.GopPicSize = FFALIGN(pv->param.videoParam->mfx.GopPicSize,
pv->param.videoParam->mfx.GopRefDist);
}
/*
* NumRefFrame must be greater than 3 and than half of GopRefDist.
* Otherwise, Media SDK may sometimes decide to disable B-pyramid
* (whereas sometimes it will simply sanitize NumRefFrame instead).
*
* Note: Media SDK handles the NumRefFrame == 0 case for us.
*/
if (pv->param.videoParam->mfx.NumRefFrame)
{
pv->param.videoParam->mfx.NumRefFrame = FFMAX(pv->param.videoParam->mfx.NumRefFrame,
pv->param.videoParam->mfx.GopRefDist / 2);
pv->param.videoParam->mfx.NumRefFrame = FFMAX(pv->param.videoParam->mfx.NumRefFrame, 3);
}
}
else if (pv->param.videoParam->mfx.GopRefDist == 0 ||
pv->param.videoParam->mfx.GopRefDist == pyramid_ref_dist)
{
/*
* GopRefDist is either B-pyramid compatible or unknown (and thus
* potentially compatible), so adjust it to force-disable B-pyramid.
*/
pv->param.videoParam->mfx.GopRefDist = pyramid_ref_dist - 1;
}
}
return;
unsupported:
pv->param.gop.b_pyramid = 0;
pv->param.codingOption2.BRefType = MFX_B_REF_OFF;
}
static int qsv_hevc_make_header(hb_work_object_t *w, mfxSession session)
{
size_t len;
int ret = 0;
uint8_t *buf, *end;
mfxBitstream bitstream;
hb_buffer_t *bitstream_buf;
mfxStatus status;
mfxSyncPoint syncPoint;
mfxFrameSurface1 frameSurface1;
hb_work_private_t *pv = w->private_data;
memset(&bitstream, 0, sizeof(mfxBitstream));
memset(&syncPoint, 0, sizeof(mfxSyncPoint));
memset(&frameSurface1, 0, sizeof(mfxFrameSurface1));
/* The bitstream buffer should be able to hold any encoded frame */
bitstream_buf = hb_video_buffer_init(pv->job->width, pv->job->height);
if (bitstream_buf == NULL)
{
hb_log("qsv_hevc_make_header: hb_buffer_init failed");
ret = -1;
goto end;
}
bitstream.Data = bitstream_buf->data;
bitstream.MaxLength = bitstream_buf->size;
/* We only need to encode one frame, so we only need one surface */
mfxU16 Height = pv->param.videoParam->mfx.FrameInfo.Height;
mfxU16 Width = pv->param.videoParam->mfx.FrameInfo.Width;
frameSurface1.Info = pv->param.videoParam->mfx.FrameInfo;
frameSurface1.Data.VU = av_mallocz(Width * Height / 2);
frameSurface1.Data.Y = av_mallocz(Width * Height);
frameSurface1.Data.Pitch = Width;
/* Encode a single blank frame */
do
{
status = MFXVideoENCODE_EncodeFrameAsync(session, NULL,
&frameSurface1,
&bitstream,
&syncPoint);
if (status == MFX_ERR_MORE_DATA)
{
break; // more input needed, but we don't have any
}
if (status < MFX_ERR_NONE)
{
hb_log("qsv_hevc_make_header: MFXVideoENCODE_EncodeFrameAsync failed (%d)", status);
ret = -1;
goto end;
}
if (syncPoint)
{
break; // we have output
}
if (status == MFX_WRN_DEVICE_BUSY)
{
av_qsv_sleep(1);
}
}
while (status >= MFX_ERR_NONE);
/* If we don't have any output yet, flush the encoder */
if (!syncPoint)
{
do
{
status = MFXVideoENCODE_EncodeFrameAsync(session, NULL, NULL,
&bitstream,
&syncPoint);
if (status == MFX_ERR_MORE_DATA)
{
break; // done flushing
}
if (status < MFX_ERR_NONE)
{
hb_log("qsv_hevc_make_header: MFXVideoENCODE_EncodeFrameAsync failed (%d)", status);
ret = -1;
goto end;
}
if (syncPoint)
{
break; // we have output
}
if (status == MFX_WRN_DEVICE_BUSY)
{
av_qsv_sleep(1);
}
}
while (status >= MFX_ERR_NONE);
}
/* Still no data at this point, we can't proceed */
if (!syncPoint)
{
hb_log("qsv_hevc_make_header: no sync point");
ret = -1;
goto end;
}
do
{
status = MFXVideoCORE_SyncOperation(session, syncPoint, 100);
}
while (status == MFX_WRN_IN_EXECUTION);
if (status != MFX_ERR_NONE)
{
hb_log("qsv_hevc_make_header: MFXVideoCORE_SyncOperation failed (%d)", status);
ret = -1;
goto end;
}
if (!bitstream.DataLength)
{
hb_log("qsv_hevc_make_header: no bitstream data");
ret = -1;
goto end;
}
/* Include any parameter sets and SEI NAL units in the headers. */
len = bitstream.DataLength;
buf = bitstream.Data + bitstream.DataOffset;
end = bitstream.Data + bitstream.DataOffset + bitstream.DataLength;
w->config->h265.headers_length = 0;
while ((buf = hb_annexb_find_next_nalu(buf, &len)) != NULL)
{
switch ((buf[0] >> 1) & 0x3f)
{
case 32: // VPS_NUT
case 33: // SPS_NUT
case 34: // PPS_NUT
case 39: // PREFIX_SEI_NUT
case 40: // SUFFIX_SEI_NUT
break;
default:
len = end - buf;
continue;
}
size_t size = hb_nal_unit_write_annexb(NULL, buf, len) + w->config->h265.headers_length;
if (sizeof(w->config->h265.headers) < size)
{
/* Will never happen in practice */
hb_log("qsv_hevc_make_header: header too large (size: %lu, max: %lu)",
size, sizeof(w->config->h265.headers));
}
w->config->h265.headers_length += hb_nal_unit_write_annexb(w->config->h265.headers +
w->config->h265.headers_length, buf, len);
len = end - buf;
}
end:
hb_buffer_close(&bitstream_buf);
av_free(frameSurface1.Data.VU);
av_free(frameSurface1.Data.Y);
return ret;
}
int qsv_enc_init(hb_work_private_t *pv)
{
av_qsv_context *qsv = pv->job->qsv.ctx;
hb_job_t *job = pv->job;
mfxVersion version;
mfxStatus sts;
mfxIMPL impl;
int i;
if (pv->init_done)
{
return 0;
}
if (qsv == NULL)
{
if (!pv->is_sys_mem)
{
hb_error("qsv_enc_init: decode enabled but no context!");
return 3;
}
job->qsv.ctx = qsv = av_mallocz(sizeof(av_qsv_context));
}
av_qsv_space *qsv_encode = qsv->enc_space;
if (qsv_encode == NULL)
{
// if only for encode
if (pv->is_sys_mem)
{
// no need to use additional sync as encode only -> single thread
av_qsv_add_context_usage(qsv, 0);
// re-use the session from encqsvInit
qsv->mfx_session = pv->mfx_session;
}
qsv->enc_space = qsv_encode = &pv->enc_space;
}
if (!pv->is_sys_mem)
{
if (!pv->is_vpp_present && job->list_filter != NULL)
{
for (i = 0; i < hb_list_count(job->list_filter); i++)
{
hb_filter_object_t *filter = hb_list_item(job->list_filter, i);
if (filter->id == HB_FILTER_QSV_PRE ||
filter->id == HB_FILTER_QSV_POST ||
filter->id == HB_FILTER_QSV)
{
pv->is_vpp_present = 1;
break;
}
}
}
if (pv->is_vpp_present)
{
if (qsv->vpp_space == NULL)
{
return 2;
}
for (i = 0; i < av_qsv_list_count(qsv->vpp_space); i++)
{
av_qsv_space *vpp = av_qsv_list_item(qsv->vpp_space, i);
if (!vpp->is_init_done)
{
return 2;
}
}
}
av_qsv_space *dec_space = qsv->dec_space;
if (dec_space == NULL || !dec_space->is_init_done)
{
return 2;
}
}
else
{
pv->sws_context_to_nv12 = hb_sws_get_context(
job->width, job->height,
AV_PIX_FMT_YUV420P,
job->width, job->height,
AV_PIX_FMT_NV12,
SWS_LANCZOS|SWS_ACCURATE_RND);
}
// allocate tasks
qsv_encode->p_buf_max_size = AV_QSV_BUF_SIZE_DEFAULT;
qsv_encode->tasks = av_qsv_list_init(HAVE_THREADS);
for (i = 0; i < pv->max_async_depth; i++)
{
av_qsv_task *task = av_mallocz(sizeof(av_qsv_task));
task->bs = av_mallocz(sizeof(mfxBitstream));
task->bs->Data = av_mallocz(sizeof(uint8_t) * qsv_encode->p_buf_max_size);
task->bs->MaxLength = qsv_encode->p_buf_max_size;
task->bs->DataLength = 0;
task->bs->DataOffset = 0;
av_qsv_list_add(qsv_encode->tasks, task);
}
// plugins should be loaded before querying for surface allocation
if (pv->loaded_plugins == NULL)
{
if (MFXQueryVersion(qsv->mfx_session, &version) != MFX_ERR_NONE)
{
hb_error("qsv_enc_init: MFXQueryVersion failed");
*job->done_error = HB_ERROR_INIT;
*job->die = 1;
return -1;
}
pv->loaded_plugins = hb_qsv_load_plugins(pv->qsv_info, qsv->mfx_session, version);
if (pv->loaded_plugins == NULL)
{
hb_error("qsv_enc_init: hb_qsv_load_plugins failed");
*job->done_error = HB_ERROR_INIT;
*job->die = 1;
return -1;
}
}
// setup surface allocation
pv->param.videoParam->IOPattern = (pv->is_sys_mem ?
MFX_IOPATTERN_IN_SYSTEM_MEMORY :
MFX_IOPATTERN_IN_OPAQUE_MEMORY);
memset(&qsv_encode->request, 0, sizeof(mfxFrameAllocRequest) * 2);
sts = MFXVideoENCODE_QueryIOSurf(qsv->mfx_session,
pv->param.videoParam,
&qsv_encode->request[0]);
if (sts < MFX_ERR_NONE) // ignore warnings
{
hb_error("qsv_enc_init: MFXVideoENCODE_QueryIOSurf failed (%d)", sts);
*job->done_error = HB_ERROR_INIT;
*job->die = 1;
return -1;
}
// allocate surfaces
if (pv->is_sys_mem)
{
qsv_encode->surface_num = FFMIN(qsv_encode->request[0].NumFrameSuggested +
pv->max_async_depth, AV_QSV_SURFACE_NUM);
if (qsv_encode->surface_num <= 0)
{
qsv_encode->surface_num = AV_QSV_SURFACE_NUM;
}
for (i = 0; i < qsv_encode->surface_num; i++)
{
mfxFrameSurface1 *surface = av_mallocz(sizeof(mfxFrameSurface1));
mfxFrameInfo info = pv->param.videoParam->mfx.FrameInfo;
surface->Info = info;
surface->Data.Pitch = info.Width;
surface->Data.Y = av_mallocz(info.Width * info.Height);
surface->Data.VU = av_mallocz(info.Width * info.Height / 2);
qsv_encode->p_surfaces[i] = surface;
}
}
else
{
av_qsv_space *in_space = qsv->dec_space;
if (pv->is_vpp_present)
{
// we get our input from VPP instead
in_space = av_qsv_list_item(qsv->vpp_space,
av_qsv_list_count(qsv->vpp_space) - 1);
}
// introduced in API 1.3
memset(&qsv_encode->ext_opaque_alloc, 0, sizeof(mfxExtOpaqueSurfaceAlloc));
qsv_encode->ext_opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
qsv_encode->ext_opaque_alloc.Header.BufferSz = sizeof(mfxExtOpaqueSurfaceAlloc);
qsv_encode->ext_opaque_alloc.In.Surfaces = in_space->p_surfaces;
qsv_encode->ext_opaque_alloc.In.NumSurface = in_space->surface_num;
qsv_encode->ext_opaque_alloc.In.Type = qsv_encode->request[0].Type;
pv->param.videoParam->ExtParam[pv->param.videoParam->NumExtParam++] = (mfxExtBuffer*)&qsv_encode->ext_opaque_alloc;
}
// allocate sync points
qsv_encode->sync_num = (qsv_encode->surface_num ?
FFMIN(qsv_encode->surface_num, AV_QSV_SYNC_NUM) :
AV_QSV_SYNC_NUM);
for (i = 0; i < qsv_encode->sync_num; i++)
{
qsv_encode->p_syncp[i] = av_mallocz(sizeof(av_qsv_sync));
AV_QSV_CHECK_POINTER(qsv_encode->p_syncp[i], MFX_ERR_MEMORY_ALLOC);
qsv_encode->p_syncp[i]->p_sync = av_mallocz(sizeof(mfxSyncPoint));
AV_QSV_CHECK_POINTER(qsv_encode->p_syncp[i]->p_sync, MFX_ERR_MEMORY_ALLOC);
}
// initialize the encoder
sts = MFXVideoENCODE_Init(qsv->mfx_session, pv->param.videoParam);
if (sts < MFX_ERR_NONE) // ignore warnings
{
hb_error("qsv_enc_init: MFXVideoENCODE_Init failed (%d)", sts);
*job->done_error = HB_ERROR_INIT;
*job->die = 1;
return -1;
}
qsv_encode->is_init_done = 1;
// query and log actual implementation details
if ((MFXQueryIMPL (qsv->mfx_session, &impl) == MFX_ERR_NONE) &&
(MFXQueryVersion(qsv->mfx_session, &version) == MFX_ERR_NONE))
{
hb_log("qsv_enc_init: using '%s' implementation, API: %"PRIu16".%"PRIu16"",
hb_qsv_impl_get_name(impl), version.Major, version.Minor);
}
else
{
hb_log("qsv_enc_init: MFXQueryIMPL/MFXQueryVersion failure");
}
pv->init_done = 1;
return 0;
}
/***********************************************************************
* encqsvInit
***********************************************************************
*
**********************************************************************/
int encqsvInit(hb_work_object_t *w, hb_job_t *job)
{
hb_work_private_t *pv = calloc(1, sizeof(hb_work_private_t));
w->private_data = pv;
pv->job = job;
pv->is_sys_mem = hb_qsv_decode_is_enabled(job) == 0;
pv->qsv_info = hb_qsv_info_get(job->vcodec);
pv->delayed_processing = hb_list_init();
pv->last_start = INT64_MIN;
hb_buffer_list_clear(&pv->encoded_frames);
pv->next_chapter_pts = AV_NOPTS_VALUE;
pv->delayed_chapters = hb_list_init();
// default encoding parameters
if (hb_qsv_param_default_preset(&pv->param, &pv->enc_space.m_mfxVideoParam,
pv->qsv_info, job->encoder_preset))
{
hb_error("encqsvInit: hb_qsv_param_default_preset failed");
return -1;
}
// set AsyncDepth to match that of decode and VPP
pv->param.videoParam->AsyncDepth = job->qsv.async_depth;
// set and enable colorimetry (video signal information)
switch (job->color_matrix_code)
{
case 4:
// custom
pv->param.videoSignalInfo.ColourPrimaries = job->color_prim;
pv->param.videoSignalInfo.TransferCharacteristics = job->color_transfer;
pv->param.videoSignalInfo.MatrixCoefficients = job->color_matrix;
break;
case 3:
// ITU BT.709 HD content
pv->param.videoSignalInfo.ColourPrimaries = HB_COLR_PRI_BT709;
pv->param.videoSignalInfo.TransferCharacteristics = HB_COLR_TRA_BT709;
pv->param.videoSignalInfo.MatrixCoefficients = HB_COLR_MAT_BT709;
break;
case 2:
// ITU BT.601 DVD or SD TV content (PAL)
pv->param.videoSignalInfo.ColourPrimaries = HB_COLR_PRI_EBUTECH;
pv->param.videoSignalInfo.TransferCharacteristics = HB_COLR_TRA_BT709;
pv->param.videoSignalInfo.MatrixCoefficients = HB_COLR_MAT_SMPTE170M;
break;
case 1:
// ITU BT.601 DVD or SD TV content (NTSC)
pv->param.videoSignalInfo.ColourPrimaries = HB_COLR_PRI_SMPTEC;
pv->param.videoSignalInfo.TransferCharacteristics = HB_COLR_TRA_BT709;
pv->param.videoSignalInfo.MatrixCoefficients = HB_COLR_MAT_SMPTE170M;
break;
default:
// detected during scan
pv->param.videoSignalInfo.ColourPrimaries = job->title->color_prim;
pv->param.videoSignalInfo.TransferCharacteristics = job->title->color_transfer;
pv->param.videoSignalInfo.MatrixCoefficients = job->title->color_matrix;
break;
}
pv->param.videoSignalInfo.ColourDescriptionPresent = 1;
// parse user-specified encoder options, if present
if (job->encoder_options != NULL && *job->encoder_options)
{
hb_dict_t *options_list;
options_list = hb_encopts_to_dict(job->encoder_options, job->vcodec);
hb_dict_iter_t iter;
for (iter = hb_dict_iter_init(options_list);
iter != HB_DICT_ITER_DONE;
iter = hb_dict_iter_next(options_list, iter))
{
const char *key = hb_dict_iter_key(iter);
hb_value_t *value = hb_dict_iter_value(iter);
char *str = hb_value_get_string_xform(value);
switch (hb_qsv_param_parse(&pv->param, pv->qsv_info, key, str))
{
case HB_QSV_PARAM_OK:
break;
case HB_QSV_PARAM_BAD_NAME:
hb_log("encqsvInit: hb_qsv_param_parse: bad key %s", key);
break;
case HB_QSV_PARAM_BAD_VALUE:
hb_log("encqsvInit: hb_qsv_param_parse: bad value %s for key %s",
str, key);
break;
case HB_QSV_PARAM_UNSUPPORTED:
hb_log("encqsvInit: hb_qsv_param_parse: unsupported option %s",
key);
break;
case HB_QSV_PARAM_ERROR:
default:
hb_log("encqsvInit: hb_qsv_param_parse: unknown error");
break;
}
free(str);
}
hb_dict_free(&options_list);
}
// reload colorimetry in case values were set in encoder_options
if (pv->param.videoSignalInfo.ColourDescriptionPresent)
{
job->color_matrix_code = 4;
job->color_prim = pv->param.videoSignalInfo.ColourPrimaries;
job->color_transfer = pv->param.videoSignalInfo.TransferCharacteristics;
job->color_matrix = pv->param.videoSignalInfo.MatrixCoefficients;
}
else
{
job->color_matrix_code = 0;
job->color_prim = HB_COLR_PRI_UNDEF;
job->color_transfer = HB_COLR_TRA_UNDEF;
job->color_matrix = HB_COLR_MAT_UNDEF;
}
// sanitize values that may exceed the Media SDK variable size
hb_rational_t par;
hb_limit_rational(&par.num, &par.den,
job->par.num, job->par.den, UINT16_MAX);
// some encoding parameters are used by filters to configure their output
switch (pv->qsv_info->codec_id)
{
case MFX_CODEC_HEVC:
job->qsv.enc_info.align_width = AV_QSV_ALIGN32(job->width);
job->qsv.enc_info.align_height = AV_QSV_ALIGN32(job->height);
break;
case MFX_CODEC_AVC:
default:
job->qsv.enc_info.align_width = AV_QSV_ALIGN16(job->width);
job->qsv.enc_info.align_height = AV_QSV_ALIGN16(job->height);
break;
}
if (pv->param.videoParam->mfx.FrameInfo.PicStruct != MFX_PICSTRUCT_PROGRESSIVE)
{
// additional alignment may be required
switch (pv->qsv_info->codec_id)
{
case MFX_CODEC_AVC:
job->qsv.enc_info.align_height = AV_QSV_ALIGN32(job->qsv.enc_info.align_height);
break;
default:
break;
}
}
job->qsv.enc_info.pic_struct = pv->param.videoParam->mfx.FrameInfo.PicStruct;
job->qsv.enc_info.is_init_done = 1;
// set codec, profile/level and FrameInfo
pv->param.videoParam->mfx.CodecId = pv->qsv_info->codec_id;
pv->param.videoParam->mfx.CodecLevel = MFX_LEVEL_UNKNOWN;
pv->param.videoParam->mfx.CodecProfile = MFX_PROFILE_UNKNOWN;
pv->param.videoParam->mfx.FrameInfo.FourCC = MFX_FOURCC_NV12;
pv->param.videoParam->mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
pv->param.videoParam->mfx.FrameInfo.FrameRateExtN = job->vrate.num;
pv->param.videoParam->mfx.FrameInfo.FrameRateExtD = job->vrate.den;
pv->param.videoParam->mfx.FrameInfo.AspectRatioW = par.num;
pv->param.videoParam->mfx.FrameInfo.AspectRatioH = par.den;
pv->param.videoParam->mfx.FrameInfo.CropX = 0;
pv->param.videoParam->mfx.FrameInfo.CropY = 0;
pv->param.videoParam->mfx.FrameInfo.CropW = job->width;
pv->param.videoParam->mfx.FrameInfo.CropH = job->height;
pv->param.videoParam->mfx.FrameInfo.PicStruct = job->qsv.enc_info.pic_struct;
pv->param.videoParam->mfx.FrameInfo.Width = job->qsv.enc_info.align_width;
pv->param.videoParam->mfx.FrameInfo.Height = job->qsv.enc_info.align_height;
// parse user-specified codec profile and level
if (hb_qsv_profile_parse(&pv->param, pv->qsv_info, job->encoder_profile))
{
hb_error("encqsvInit: bad profile %s", job->encoder_profile);
return -1;
}
if (hb_qsv_level_parse(&pv->param, pv->qsv_info, job->encoder_level))
{
hb_error("encqsvInit: bad level %s", job->encoder_level);
return -1;
}
// interlaced encoding is not always possible
if (pv->param.videoParam->mfx.CodecId == MFX_CODEC_AVC &&
pv->param.videoParam->mfx.FrameInfo.PicStruct != MFX_PICSTRUCT_PROGRESSIVE)
{
if (pv->param.videoParam->mfx.CodecProfile == MFX_PROFILE_AVC_CONSTRAINED_BASELINE ||
pv->param.videoParam->mfx.CodecProfile == MFX_PROFILE_AVC_BASELINE ||
pv->param.videoParam->mfx.CodecProfile == MFX_PROFILE_AVC_PROGRESSIVE_HIGH)
{
hb_error("encqsvInit: profile %s doesn't support interlaced encoding",
hb_qsv_profile_name(MFX_CODEC_AVC,
pv->param.videoParam->mfx.CodecProfile));
return -1;
}
if ((pv->param.videoParam->mfx.CodecLevel >= MFX_LEVEL_AVC_1b &&
pv->param.videoParam->mfx.CodecLevel <= MFX_LEVEL_AVC_2) ||
(pv->param.videoParam->mfx.CodecLevel >= MFX_LEVEL_AVC_42))
{
hb_error("encqsvInit: level %s doesn't support interlaced encoding",
hb_qsv_level_name(MFX_CODEC_AVC,
pv->param.videoParam->mfx.CodecLevel));
return -1;
}
}
// sanitize ICQ
if (!(pv->qsv_info->capabilities & HB_QSV_CAP_RATECONTROL_ICQ))
{
// ICQ not supported
pv->param.rc.icq = 0;
}
else
{
pv->param.rc.icq = pv->param.rc.icq && job->vquality >= 0;
}
// sanitize lookahead
if (!(pv->qsv_info->capabilities & HB_QSV_CAP_RATECONTROL_LA))
{
// lookahead not supported
pv->param.rc.lookahead = 0;
}
else if ((pv->param.rc.lookahead) &&
(pv->qsv_info->capabilities & HB_QSV_CAP_RATECONTROL_LAi) == 0 &&
(pv->param.videoParam->mfx.FrameInfo.PicStruct != MFX_PICSTRUCT_PROGRESSIVE))
{
// lookahead enabled but we can't use it
hb_log("encqsvInit: LookAhead not used (LookAhead is progressive-only)");
pv->param.rc.lookahead = 0;
}
else
{
pv->param.rc.lookahead = pv->param.rc.lookahead && (pv->param.rc.icq || job->vquality < 0);
}
// set VBV here (this will be overridden for CQP and ignored for LA)
// only set BufferSizeInKB, InitialDelayInKB and MaxKbps if we have
// them - otheriwse Media SDK will pick values for us automatically
if (pv->param.rc.vbv_buffer_size > 0)
{
if (pv->param.rc.vbv_buffer_init > 1.0)
{
pv->param.videoParam->mfx.InitialDelayInKB = (pv->param.rc.vbv_buffer_init / 8);
}
else if (pv->param.rc.vbv_buffer_init > 0.0)
{
pv->param.videoParam->mfx.InitialDelayInKB = (pv->param.rc.vbv_buffer_size *
pv->param.rc.vbv_buffer_init / 8);
}
pv->param.videoParam->mfx.BufferSizeInKB = (pv->param.rc.vbv_buffer_size / 8);
}
if (pv->param.rc.vbv_max_bitrate > 0)
{
pv->param.videoParam->mfx.MaxKbps = pv->param.rc.vbv_max_bitrate;
}
// set rate control paremeters
if (job->vquality >= 0)
{
if (pv->param.rc.icq)
{
// introduced in API 1.8
if (pv->param.rc.lookahead)
{
pv->param.videoParam->mfx.RateControlMethod = MFX_RATECONTROL_LA_ICQ;
}
else
{
pv->param.videoParam->mfx.RateControlMethod = MFX_RATECONTROL_ICQ;
}
pv->param.videoParam->mfx.ICQQuality = HB_QSV_CLIP3(1, 51, job->vquality);
}
else
{
// introduced in API 1.1
pv->param.videoParam->mfx.RateControlMethod = MFX_RATECONTROL_CQP;
pv->param.videoParam->mfx.QPI = HB_QSV_CLIP3(0, 51, job->vquality + pv->param.rc.cqp_offsets[0]);
pv->param.videoParam->mfx.QPP = HB_QSV_CLIP3(0, 51, job->vquality + pv->param.rc.cqp_offsets[1]);
pv->param.videoParam->mfx.QPB = HB_QSV_CLIP3(0, 51, job->vquality + pv->param.rc.cqp_offsets[2]);
// CQP + ExtBRC can cause bad output
pv->param.codingOption2.ExtBRC = MFX_CODINGOPTION_OFF;
}
}
else if (job->vbitrate > 0)
{
if (pv->param.rc.lookahead)
{
// introduced in API 1.7
pv->param.videoParam->mfx.RateControlMethod = MFX_RATECONTROL_LA;
pv->param.videoParam->mfx.TargetKbps = job->vbitrate;
// ignored, but some drivers will change AsyncDepth because of it
pv->param.codingOption2.ExtBRC = MFX_CODINGOPTION_OFF;
}
else
{
// introduced in API 1.0
if (job->vbitrate == pv->param.rc.vbv_max_bitrate)
{
pv->param.videoParam->mfx.RateControlMethod = MFX_RATECONTROL_CBR;
}
else
{
pv->param.videoParam->mfx.RateControlMethod = MFX_RATECONTROL_VBR;
}
pv->param.videoParam->mfx.TargetKbps = job->vbitrate;
}
}
else
{
hb_error("encqsvInit: invalid rate control (%f, %d)",
job->vquality, job->vbitrate);
return -1;
}
// if VBV is enabled but ignored, log it
if (pv->param.rc.vbv_max_bitrate > 0 || pv->param.rc.vbv_buffer_size > 0)
{
switch (pv->param.videoParam->mfx.RateControlMethod)
{
case MFX_RATECONTROL_LA:
case MFX_RATECONTROL_LA_ICQ:
hb_log("encqsvInit: LookAhead enabled, ignoring VBV");
break;