@@ -199,6 +199,70 @@ void CudaDeviceInterface::initializeContext(AVCodecContext* codecContext) {
199
199
return ;
200
200
}
201
201
202
+ std::unique_ptr<FiltersContext> CudaDeviceInterface::initializeFiltersContext (
203
+ const VideoStreamOptions& videoStreamOptions,
204
+ const UniqueAVFrame& avFrame,
205
+ const AVRational& timeBase) {
206
+ enum AVPixelFormat frameFormat =
207
+ static_cast <enum AVPixelFormat>(avFrame->format );
208
+
209
+ if (avFrame->format != AV_PIX_FMT_CUDA) {
210
+ auto cpuDevice = torch::Device (torch::kCPU );
211
+ auto cpuInterface = createDeviceInterface (cpuDevice);
212
+ return cpuInterface->initializeFiltersContext (
213
+ videoStreamOptions, avFrame, timeBase);
214
+ }
215
+
216
+ auto frameDims =
217
+ getHeightAndWidthFromOptionsOrAVFrame (videoStreamOptions, avFrame);
218
+ int height = frameDims.height ;
219
+ int width = frameDims.width ;
220
+
221
+ auto hwFramesCtx =
222
+ reinterpret_cast <AVHWFramesContext*>(avFrame->hw_frames_ctx ->data );
223
+ AVPixelFormat actualFormat = hwFramesCtx->sw_format ;
224
+
225
+ if (actualFormat == AV_PIX_FMT_NV12) {
226
+ return nullptr ;
227
+ }
228
+
229
+ std::unique_ptr<FiltersContext> filtersContext =
230
+ std::make_unique<FiltersContext>();
231
+
232
+ filtersContext->inputWidth = avFrame->width ;
233
+ filtersContext->inputHeight = avFrame->height ;
234
+ filtersContext->inputFormat = frameFormat;
235
+ filtersContext->inputAspectRatio = avFrame->sample_aspect_ratio ;
236
+ filtersContext->outputWidth = width;
237
+ filtersContext->outputHeight = height;
238
+ filtersContext->timeBase = timeBase;
239
+ filtersContext->hwFramesCtx .reset (av_buffer_ref (avFrame->hw_frames_ctx ));
240
+
241
+ std::stringstream filters;
242
+
243
+ unsigned version_int = avfilter_version ();
244
+ if (version_int < AV_VERSION_INT (8 , 0 , 103 )) {
245
+ // Color conversion support ('format=' option) was added to scale_cuda from
246
+ // n5.0. With the earlier version of ffmpeg we have no choice but use CPU
247
+ // filters. See:
248
+ // https://github.com/FFmpeg/FFmpeg/commit/62dc5df941f5e196164c151691e4274195523e95
249
+ filtersContext->outputFormat = AV_PIX_FMT_RGB24;
250
+
251
+ filters << " hwdownload,format=" << av_pix_fmt_desc_get (actualFormat)->name ;
252
+ filters << " ,scale=" << width << " :" << height;
253
+ filters << " :sws_flags=bilinear" ;
254
+ } else {
255
+ // Actual output color format will be set via filter options
256
+ filtersContext->outputFormat = AV_PIX_FMT_CUDA;
257
+
258
+ filters << " scale_cuda=" << width << " :" << height;
259
+ filters << " :format=nv12:interp_algo=bilinear" ;
260
+ }
261
+
262
+ filtersContext->filtergraphStr = filters.str ();
263
+ return filtersContext;
264
+ }
265
+
202
266
void CudaDeviceInterface::convertAVFrameToFrameOutput (
203
267
const VideoStreamOptions& videoStreamOptions,
204
268
[[maybe_unused]] const AVRational& timeBase,
0 commit comments