1 /*
2 * Copyright 2019 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "experimental/ffmpeg/SkVideoDecoder.h"
9 #include "include/core/SkColorSpace.h"
10 #include "include/core/SkImage.h"
11 #include "include/core/SkYUVAPixmaps.h"
12
get_yuvspace(AVColorSpace space)13 static SkYUVColorSpace get_yuvspace(AVColorSpace space) {
14 // this is pretty incomplete -- TODO: look to convert more AVColorSpaces
15 switch (space) {
16 case AVCOL_SPC_RGB: return kIdentity_SkYUVColorSpace;
17 case AVCOL_SPC_BT709: return kRec709_SkYUVColorSpace;
18 case AVCOL_SPC_SMPTE170M:
19 case AVCOL_SPC_SMPTE240M:
20 case AVCOL_SPC_BT470BG: return kRec601_SkYUVColorSpace;
21 default: break;
22 }
23 return kRec709_SkYUVColorSpace;
24 }
25
26 struct av_transfer_characteristics {
27 // if x < beta delta * x
28 // else alpha * (x^gama)
29 float alpha, beta, gamma, delta;
30 };
31
32 // Tables extracted from vf_colorspace.c
33
34 const av_transfer_characteristics gTransfer[AVCOL_TRC_NB] = {
35 [AVCOL_TRC_BT709] = { 1.099, 0.018, 0.45, 4.5 },
36 [AVCOL_TRC_GAMMA22] = { 1.0, 0.0, 1.0 / 2.2, 0.0 },
37 [AVCOL_TRC_GAMMA28] = { 1.0, 0.0, 1.0 / 2.8, 0.0 },
38 [AVCOL_TRC_SMPTE170M] = { 1.099, 0.018, 0.45, 4.5 },
39 [AVCOL_TRC_SMPTE240M] = { 1.1115, 0.0228, 0.45, 4.0 },
40 [AVCOL_TRC_IEC61966_2_1] = { 1.055, 0.0031308, 1.0 / 2.4, 12.92 },
41 [AVCOL_TRC_IEC61966_2_4] = { 1.099, 0.018, 0.45, 4.5 },
42 [AVCOL_TRC_BT2020_10] = { 1.099, 0.018, 0.45, 4.5 },
43 [AVCOL_TRC_BT2020_12] = { 1.0993, 0.0181, 0.45, 4.5 },
44 };
45
compute_transfer(AVColorTransferCharacteristic t)46 static skcms_TransferFunction compute_transfer(AVColorTransferCharacteristic t) {
47 const av_transfer_characteristics* av = &gTransfer[AVCOL_TRC_BT709];
48 if ((unsigned)t < AVCOL_TRC_NB) {
49 av = &gTransfer[t];
50 }
51 if (av->alpha == 0) {
52 av = &gTransfer[AVCOL_TRC_BT709];
53 }
54
55 skcms_TransferFunction linear_to_encoded = {
56 av->gamma, sk_float_pow(av->alpha, 1/av->gamma), 0, av->delta, av->beta, 1 - av->alpha, 0,
57 };
58 skcms_TransferFunction encoded_to_linear;
59 bool success = skcms_TransferFunction_invert(&linear_to_encoded, &encoded_to_linear);
60 SkASSERT(success);
61
62 return encoded_to_linear;
63 }
64
65 enum Whitepoint {
66 WP_D65,
67 WP_C,
68 WP_DCI,
69 WP_E,
70 WP_NB,
71 };
72
73 const SkPoint gWP[WP_NB] = {
74 [WP_D65] = { 0.3127f, 0.3290f },
75 [WP_C] = { 0.3100f, 0.3160f },
76 [WP_DCI] = { 0.3140f, 0.3510f },
77 [WP_E] = { 1/3.0f, 1/3.0f },
78 };
79
80 #define ExpandWP(index) gWP[index].fX, gWP[index].fY
81
82 const SkColorSpacePrimaries gPrimaries[AVCOL_PRI_NB] = {
83 [AVCOL_PRI_BT709] = { 0.640f, 0.330f, 0.300f, 0.600f, 0.150f, 0.060f, ExpandWP(WP_D65) },
84 [AVCOL_PRI_BT470M] = { 0.670f, 0.330f, 0.210f, 0.710f, 0.140f, 0.080f, ExpandWP(WP_C) },
85 [AVCOL_PRI_BT470BG] = { 0.640f, 0.330f, 0.290f, 0.600f, 0.150f, 0.060f, ExpandWP(WP_D65) },
86 [AVCOL_PRI_SMPTE170M] = { 0.630f, 0.340f, 0.310f, 0.595f, 0.155f, 0.070f, ExpandWP(WP_D65) },
87 [AVCOL_PRI_SMPTE240M] = { 0.630f, 0.340f, 0.310f, 0.595f, 0.155f, 0.070f, ExpandWP(WP_D65) },
88 [AVCOL_PRI_SMPTE428] = { 0.735f, 0.265f, 0.274f, 0.718f, 0.167f, 0.009f, ExpandWP(WP_E) },
89 [AVCOL_PRI_SMPTE431] = { 0.680f, 0.320f, 0.265f, 0.690f, 0.150f, 0.060f, ExpandWP(WP_DCI) },
90 [AVCOL_PRI_SMPTE432] = { 0.680f, 0.320f, 0.265f, 0.690f, 0.150f, 0.060f, ExpandWP(WP_D65) },
91 [AVCOL_PRI_FILM] = { 0.681f, 0.319f, 0.243f, 0.692f, 0.145f, 0.049f, ExpandWP(WP_C) },
92 [AVCOL_PRI_BT2020] = { 0.708f, 0.292f, 0.170f, 0.797f, 0.131f, 0.046f, ExpandWP(WP_D65) },
93 [AVCOL_PRI_JEDEC_P22] = { 0.630f, 0.340f, 0.295f, 0.605f, 0.155f, 0.077f, ExpandWP(WP_D65) },
94 };
95
make_colorspace(AVColorPrimaries primaries,AVColorTransferCharacteristic transfer)96 sk_sp<SkColorSpace> make_colorspace(AVColorPrimaries primaries,
97 AVColorTransferCharacteristic transfer) {
98 if (primaries == AVCOL_PRI_BT709 && transfer == AVCOL_TRC_BT709) {
99 return SkColorSpace::MakeSRGB();
100 }
101
102 const SkColorSpacePrimaries* p = &gPrimaries[0];
103 if ((unsigned)primaries < (unsigned)AVCOL_PRI_NB) {
104 p = &gPrimaries[primaries];
105 }
106
107 skcms_Matrix3x3 matrix;
108 p->toXYZD50(&matrix);
109 return SkColorSpace::MakeRGB(compute_transfer(transfer), matrix);
110 }
111
112 // returns true on error (and may dump the particular error message)
check_err(int err,const int silentList[]=nullptr)113 static bool check_err(int err, const int silentList[] = nullptr) {
114 if (err >= 0) {
115 return false;
116 }
117
118 if (silentList) {
119 for (; *silentList; ++silentList) {
120 if (*silentList == err) {
121 return true; // we still report the error, but we don't printf
122 }
123 }
124 }
125
126 char errbuf[128];
127 const char *errbuf_ptr = errbuf;
128
129 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0) {
130 errbuf_ptr = strerror(AVUNERROR(err));
131 }
132 SkDebugf("%s\n", errbuf_ptr);
133 return true;
134 }
135
skstream_read_packet(void * ctx,uint8_t * dstBuffer,int dstSize)136 static int skstream_read_packet(void* ctx, uint8_t* dstBuffer, int dstSize) {
137 SkStream* stream = (SkStream*)ctx;
138 int result = (int)stream->read(dstBuffer, dstSize);
139 if (result == 0) {
140 result = AVERROR_EOF;
141 }
142 return result;
143 }
144
skstream_seek_packet(void * ctx,int64_t pos,int whence)145 static int64_t skstream_seek_packet(void* ctx, int64_t pos, int whence) {
146 SkStream* stream = (SkStream*)ctx;
147 switch (whence) {
148 case SEEK_SET:
149 break;
150 case SEEK_CUR:
151 pos = (int64_t)stream->getPosition() + pos;
152 break;
153 case SEEK_END:
154 pos = (int64_t)stream->getLength() + pos;
155 break;
156 default:
157 return -1;
158 }
159 return stream->seek(SkToSizeT(pos)) ? pos : -1;
160 }
161
make_yuv_420(GrRecordingContext * rContext,int w,int h,uint8_t * const data[],int const strides[],SkYUVColorSpace yuvSpace,sk_sp<SkColorSpace> cs)162 static sk_sp<SkImage> make_yuv_420(GrRecordingContext* rContext,
163 int w, int h,
164 uint8_t* const data[],
165 int const strides[],
166 SkYUVColorSpace yuvSpace,
167 sk_sp<SkColorSpace> cs) {
168 SkYUVAInfo yuvaInfo({w, h},
169 SkYUVAInfo::PlaneConfig::kY_U_V,
170 SkYUVAInfo::Subsampling::k420,
171 yuvSpace);
172 SkPixmap pixmaps[3];
173 pixmaps[0].reset(SkImageInfo::MakeA8(w, h), data[0], strides[0]);
174 w = (w + 1)/2;
175 h = (h + 1)/2;
176 pixmaps[1].reset(SkImageInfo::MakeA8(w, h), data[1], strides[1]);
177 pixmaps[2].reset(SkImageInfo::MakeA8(w, h), data[2], strides[2]);
178 auto yuvaPixmaps = SkYUVAPixmaps::FromExternalPixmaps(yuvaInfo, pixmaps);
179
180 return SkImage::MakeFromYUVAPixmaps(
181 rContext, yuvaPixmaps, GrMipMapped::kNo, false, std::move(cs));
182 }
183
184 // Init with illegal values, so our first compare will fail, forcing us to compute
185 // the skcolorspace.
ConvertedColorSpace()186 SkVideoDecoder::ConvertedColorSpace::ConvertedColorSpace()
187 : fPrimaries(AVCOL_PRI_NB), fTransfer(AVCOL_TRC_NB)
188 {}
189
update(AVColorPrimaries primaries,AVColorTransferCharacteristic transfer)190 void SkVideoDecoder::ConvertedColorSpace::update(AVColorPrimaries primaries,
191 AVColorTransferCharacteristic transfer) {
192 if (fPrimaries != primaries || fTransfer != transfer) {
193 fPrimaries = primaries;
194 fTransfer = transfer;
195 fCS = make_colorspace(primaries, transfer);
196 }
197 }
198
computeTimeStamp(const AVFrame * frame) const199 double SkVideoDecoder::computeTimeStamp(const AVFrame* frame) const {
200 AVRational base = fFormatCtx->streams[fStreamIndex]->time_base;
201 return 1.0 * frame->pts * base.num / base.den;
202 }
203
convertFrame(const AVFrame * frame)204 sk_sp<SkImage> SkVideoDecoder::convertFrame(const AVFrame* frame) {
205 auto yuv_space = get_yuvspace(frame->colorspace);
206
207 // we have a 1-entry cache for converting colorspaces
208 fCSCache.update(frame->color_primaries, frame->color_trc);
209
210 // Are these always true? If so, we don't need to check our "cache" on each frame...
211 SkASSERT(fDecoderCtx->colorspace == frame->colorspace);
212 SkASSERT(fDecoderCtx->color_primaries == frame->color_primaries);
213 SkASSERT(fDecoderCtx->color_trc == frame->color_trc);
214
215 // Is this always true? If so, we might take advantage of it, knowing up-front if we support
216 // the format for the whole stream, in which case we might have to ask ffmpeg to convert it
217 // to something more reasonable (for us)...
218 SkASSERT(fDecoderCtx->pix_fmt == frame->format);
219
220 switch (frame->format) {
221 case AV_PIX_FMT_YUV420P:
222 if (auto image = make_yuv_420(fRecordingContext, frame->width, frame->height,
223 frame->data, frame->linesize, yuv_space, fCSCache.fCS)) {
224 return image;
225 }
226 break;
227 default:
228 break;
229 }
230
231 // General N32 fallback.
232 const auto info = SkImageInfo::MakeN32(frame->width, frame->height,
233 SkAlphaType::kOpaque_SkAlphaType);
234
235 SkBitmap bm;
236 bm.allocPixels(info, info.minRowBytes());
237
238 constexpr auto fmt = SK_PMCOLOR_BYTE_ORDER(R,G,B,A) ? AV_PIX_FMT_RGBA : AV_PIX_FMT_BGRA;
239
240 // TODO: should we cache these?
241 auto* ctx = sws_getContext(frame->width, frame->height, (AVPixelFormat)frame->format,
242 info.width(), info.height(), fmt,
243 SWS_BILINEAR, nullptr, nullptr, nullptr);
244
245 uint8_t* dst[] = { (uint8_t*)bm.pixmap().writable_addr() };
246 int dst_stride[] = { SkToInt(bm.pixmap().rowBytes()) };
247
248 sws_scale(ctx, frame->data, frame->linesize, 0, frame->height, dst, dst_stride);
249
250 sws_freeContext(ctx);
251
252 bm.setImmutable();
253
254 return SkImage::MakeFromBitmap(bm);
255 }
256
nextImage(double * timeStamp)257 sk_sp<SkImage> SkVideoDecoder::nextImage(double* timeStamp) {
258 double dummyTimeStampStorage = 0;
259 if (!timeStamp) {
260 timeStamp = &dummyTimeStampStorage;
261 }
262
263 if (fFormatCtx == nullptr) {
264 return nullptr;
265 }
266
267 if (fMode == kProcessing_Mode) {
268 // We sit in a loop, waiting for the codec to have received enough data (packets)
269 // to have at least one frame available.
270 // Treat non-zero return as EOF (or error, which we will decide is also EOF)
271 while (!av_read_frame(fFormatCtx, &fPacket)) {
272 if (fPacket.stream_index != fStreamIndex) {
273 // got a packet for a stream other than our (video) stream, so continue
274 continue;
275 }
276
277 int ret = avcodec_send_packet(fDecoderCtx, &fPacket);
278 if (ret == AVERROR(EAGAIN)) {
279 // may signal that we have plenty already, encouraging us to call receive_frame
280 // so we don't treat this as an error.
281 ret = 0;
282 }
283 (void)check_err(ret); // we try to continue if there was an error
284
285 int silentList[] = {
286 -35, // Resource temporarily unavailable (need more packets)
287 0,
288 };
289 if (check_err(avcodec_receive_frame(fDecoderCtx, fFrame), silentList)) {
290 // this may be just "needs more input", so we try to continue
291 } else {
292 *timeStamp = this->computeTimeStamp(fFrame);
293 return this->convertFrame(fFrame);
294 }
295 }
296
297 fMode = kDraining_Mode;
298 (void)avcodec_send_packet(fDecoderCtx, nullptr); // signal to start draining
299 }
300 if (fMode == kDraining_Mode) {
301 if (avcodec_receive_frame(fDecoderCtx, fFrame) >= 0) {
302 *timeStamp = this->computeTimeStamp(fFrame);
303 return this->convertFrame(fFrame);
304 }
305 // else we decide we're done
306 fMode = kDone_Mode;
307 }
308 return nullptr;
309 }
310
SkVideoDecoder(GrRecordingContext * rContext)311 SkVideoDecoder::SkVideoDecoder(GrRecordingContext* rContext) : fRecordingContext(rContext) {}
312
~SkVideoDecoder()313 SkVideoDecoder::~SkVideoDecoder() {
314 this->reset();
315 }
316
reset()317 void SkVideoDecoder::reset() {
318 if (fFrame) {
319 av_frame_free(&fFrame);
320 fFrame = nullptr;
321 }
322 if (fDecoderCtx) {
323 avcodec_free_context(&fDecoderCtx);
324 fDecoderCtx = nullptr;
325 }
326 if (fFormatCtx) {
327 avformat_close_input(&fFormatCtx);
328 fFormatCtx = nullptr;
329 }
330 if (fStreamCtx) {
331 av_freep(&fStreamCtx->buffer);
332 avio_context_free(&fStreamCtx);
333 fStreamCtx = nullptr;
334 }
335
336 fStream.reset(nullptr);
337 fStreamIndex = -1;
338 fMode = kDone_Mode;
339 }
340
loadStream(std::unique_ptr<SkStream> stream)341 bool SkVideoDecoder::loadStream(std::unique_ptr<SkStream> stream) {
342 this->reset();
343 if (!stream) {
344 return false;
345 }
346
347 int bufferSize = 4 * 1024;
348 uint8_t* buffer = (uint8_t*)av_malloc(bufferSize);
349 if (!buffer) {
350 return false;
351 }
352
353 fStream = std::move(stream);
354 fStreamCtx = avio_alloc_context(buffer, bufferSize, 0, fStream.get(),
355 skstream_read_packet, nullptr, skstream_seek_packet);
356 if (!fStreamCtx) {
357 av_freep(buffer);
358 this->reset();
359 return false;
360 }
361
362 fFormatCtx = avformat_alloc_context();
363 if (!fFormatCtx) {
364 this->reset();
365 return false;
366 }
367 fFormatCtx->pb = fStreamCtx;
368
369 int err = avformat_open_input(&fFormatCtx, nullptr, nullptr, nullptr);
370 if (err < 0) {
371 SkDebugf("avformat_open_input failed %d\n", err);
372 return false;
373 }
374
375 AVCodec* codec;
376 fStreamIndex = av_find_best_stream(fFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);
377 if (fStreamIndex < 0) {
378 SkDebugf("av_find_best_stream failed %d\n", fStreamIndex);
379 this->reset();
380 return false;
381 }
382
383 SkASSERT(codec);
384 fDecoderCtx = avcodec_alloc_context3(codec);
385
386 AVStream* strm = fFormatCtx->streams[fStreamIndex];
387 if ((err = avcodec_parameters_to_context(fDecoderCtx, strm->codecpar)) < 0) {
388 SkDebugf("avcodec_parameters_to_context failed %d\n", err);
389 this->reset();
390 return false;
391 }
392
393 if ((err = avcodec_open2(fDecoderCtx, codec, nullptr)) < 0) {
394 SkDebugf("avcodec_open2 failed %d\n", err);
395 this->reset();
396 return false;
397 }
398
399 fFrame = av_frame_alloc();
400 SkASSERT(fFrame);
401
402 av_init_packet(&fPacket); // is there a "free" call?
403
404 fMode = kProcessing_Mode;
405
406 return true;
407 }
408
dimensions() const409 SkISize SkVideoDecoder::dimensions() const {
410 if (!fFormatCtx) {
411 return {0, 0};
412 }
413
414 AVStream* strm = fFormatCtx->streams[fStreamIndex];
415 return {strm->codecpar->width, strm->codecpar->height};
416 }
417
duration() const418 double SkVideoDecoder::duration() const {
419 if (!fFormatCtx) {
420 return 0;
421 }
422
423 AVStream* strm = fFormatCtx->streams[fStreamIndex];
424 AVRational base = strm->time_base;
425 return 1.0 * strm->duration * base.num / base.den;
426 }
427
rewind()428 bool SkVideoDecoder::rewind() {
429 auto stream = std::move(fStream);
430 this->reset();
431 if (stream) {
432 stream->rewind();
433 }
434 return this->loadStream(std::move(stream));
435 }
436