|
| 1 | +// Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +// All rights reserved. |
| 3 | +// |
| 4 | +// This source code is licensed under the BSD-style license found in the |
| 5 | +// LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +#include "src/torchcodec/_core/SwsContext.h" |
| 8 | +#include "src/torchcodec/_core/FFMPEGCommon.h" |
| 9 | + |
| 10 | +extern "C" { |
| 11 | +#include <libswscale/swscale.h> |
| 12 | +} |
| 13 | + |
| 14 | +namespace facebook::torchcodec { |
| 15 | + |
| 16 | +SwsFrameContext::SwsFrameContext( |
| 17 | + int inputWidth, |
| 18 | + int inputHeight, |
| 19 | + AVPixelFormat inputFormat, |
| 20 | + int outputWidth, |
| 21 | + int outputHeight) |
| 22 | + : inputWidth(inputWidth), |
| 23 | + inputHeight(inputHeight), |
| 24 | + inputFormat(inputFormat), |
| 25 | + outputWidth(outputWidth), |
| 26 | + outputHeight(outputHeight) {} |
| 27 | + |
| 28 | +bool SwsFrameContext::operator==(const SwsFrameContext& other) const { |
| 29 | + return inputWidth == other.inputWidth && inputHeight == other.inputHeight && |
| 30 | + inputFormat == other.inputFormat && outputWidth == other.outputWidth && |
| 31 | + outputHeight == other.outputHeight; |
| 32 | +} |
| 33 | + |
| 34 | +bool SwsFrameContext::operator!=(const SwsFrameContext& other) const { |
| 35 | + return !(*this == other); |
| 36 | +} |
| 37 | + |
| 38 | +SwsContext* SwsScaler::getOrCreateContext( |
| 39 | + const UniqueAVFrame& avFrame, |
| 40 | + const FrameDims& outputDims, |
| 41 | + AVColorSpace colorspace, |
| 42 | + AVPixelFormat outputFormat, |
| 43 | + int swsFlags) { |
| 44 | + enum AVPixelFormat frameFormat = |
| 45 | + static_cast<enum AVPixelFormat>(avFrame->format); |
| 46 | + |
| 47 | + SwsFrameContext currentFrameContext( |
| 48 | + avFrame->width, |
| 49 | + avFrame->height, |
| 50 | + frameFormat, |
| 51 | + outputDims.width, |
| 52 | + outputDims.height); |
| 53 | + |
| 54 | + // Recreate swscale context only if frame properties changed |
| 55 | + if (!swsContext_ || prevFrameContext_ != currentFrameContext) { |
| 56 | + swsContext_ = createSwsContext( |
| 57 | + currentFrameContext, colorspace, outputFormat, swsFlags); |
| 58 | + prevFrameContext_ = currentFrameContext; |
| 59 | + } |
| 60 | + |
| 61 | + return swsContext_.get(); |
| 62 | +} |
| 63 | + |
| 64 | +} // namespace facebook::torchcodec |
0 commit comments