Debian Codegraph @

src/vapoursynth/vapoursource4.cpp

raw symbols SCIP
1 // Copyright (c) 2012-2018 Fredrik Mellbin
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 // THE SOFTWARE.
20
21 #include "vapoursource4.h"
22 #include "VSHelper4.h"
23 #include "../core/utils.h"
24
25 #include <algorithm>
26 #include <cmath>
27 #include <stdexcept>
28 #include <string>
29 #include <utility>
30 #include <vector>
31
32 static int GetNumPixFmts() {
33 int n = 0;
34 while (av_get_pix_fmt_name((AVPixelFormat)n))
35 n++;
36 return n;
37 }
38
39 static bool IsRealNativeEndianPlanar(const AVPixFmtDescriptor &desc) {
40 // reject all special flags
41 if (desc.flags & (AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_BAYER | AV_PIX_FMT_FLAG_HWACCEL | AV_PIX_FMT_FLAG_BITSTREAM))
42 return false;
43 int used_planes = 0;
44 for (int i = 0; i < desc.nb_components; i++)
45 used_planes = std::max(used_planes, (int)desc.comp[i].plane + 1);
46 bool temp = (used_planes == desc.nb_components) && (desc.comp[0].depth >= 8);
47 if (!temp)
48 return false;
49 else if (desc.comp[0].depth == 8)
50 return temp;
51 else
52 return (AV_PIX_FMT_YUV420P10 == AV_PIX_FMT_YUV420P10BE ? !!(desc.flags & AV_PIX_FMT_FLAG_BE) : !(desc.flags & AV_PIX_FMT_FLAG_BE));
53 }
54
55 static int GetSampleType(const AVPixFmtDescriptor &desc) {
56 return (desc.flags & AV_PIX_FMT_FLAG_FLOAT) ? stFloat : stInteger;
57 }
58
59 static bool HasAlpha(const AVPixFmtDescriptor &desc) {
60 return !!(desc.flags & AV_PIX_FMT_FLAG_ALPHA);
61 }
62
63 static int GetColorFamily(const AVPixFmtDescriptor &desc) {
64 if (desc.nb_components <= 2)
65 return cfGray;
66 else if (desc.flags & AV_PIX_FMT_FLAG_RGB)
67 return cfRGB;
68 else
69 return cfYUV;
70 }
71
72 static int FormatConversionToPixelFormat(int id, bool alpha, VSCore *core, const VSAPI *vsapi) {
73 VSVideoFormat f;
74 vsapi->getVideoFormatByID(&f, id, core);
75 int npixfmt = GetNumPixFmts();
76 // Look for a suitable format without alpha first to not waste memory
77 if (!alpha) {
78 for (int i = 0; i < npixfmt; i++) {
79 const AVPixFmtDescriptor &desc = *av_pix_fmt_desc_get((AVPixelFormat)i);
80 if (IsRealNativeEndianPlanar(desc) && !HasAlpha(desc)
81 && GetColorFamily(desc) == f.colorFamily
82 && desc.comp[0].depth == f.bitsPerSample
83 && desc.log2_chroma_w == f.subSamplingW
84 && desc.log2_chroma_h == f.subSamplingH
85 && GetSampleType(desc) == f.sampleType)
86 return i;
87 }
88 }
89 // Try all remaining formats
90 for (int i = 0; i < npixfmt; i++) {
91 const AVPixFmtDescriptor &desc = *av_pix_fmt_desc_get((AVPixelFormat)i);
92 if (IsRealNativeEndianPlanar(desc) && HasAlpha(desc)
93 && GetColorFamily(desc) == f.colorFamily
94 && desc.comp[0].depth == f.bitsPerSample
95 && desc.log2_chroma_w == f.subSamplingW
96 && desc.log2_chroma_h == f.subSamplingH
97 && GetSampleType(desc) == f.sampleType)
98 return i;
99 }
100 return AV_PIX_FMT_NONE;
101 }
102
103 static void FormatConversionToVS(VSVideoFormat &f, int id, VSCore *core, const VSAPI *vsapi) {
104 const AVPixFmtDescriptor &desc = *av_pix_fmt_desc_get((AVPixelFormat)id);
105 vsapi->queryVideoFormat(&f,
106 GetColorFamily(desc),
107 GetSampleType(desc),
108 desc.comp[0].depth,
109 desc.log2_chroma_w,
110 desc.log2_chroma_h, core);
111 }
112
113 const VSFrame *VS_CC VSVideoSource4::GetVSFrame(int n, VSCore *core, const VSAPI *vsapi) {
114 char ErrorMsg[1024];
115 FFMS_ErrorInfo E;
116 E.Buffer = ErrorMsg;
117 E.BufferSize = sizeof(ErrorMsg);
118
119 VSFrame *Dst = vsapi->newVideoFrame(&VI[0].format, VI[0].width, VI[0].height, nullptr, core);
120 VSMap *Props = vsapi->getFramePropertiesRW(Dst);
121
122 const FFMS_Frame *Frame = nullptr;
123
124 if (FPSNum > 0 && FPSDen > 0) {
125 double currentTime = FFMS_GetVideoProperties(V)->FirstTime +
126 (double)(n * (int64_t)FPSDen) / FPSNum;
127 Frame = FFMS_GetFrameByTime(V, currentTime, &E);
128 vsapi->mapSetInt(Props, "_DurationNum", FPSDen, maReplace);
129 vsapi->mapSetInt(Props, "_DurationDen", FPSNum, maReplace);
130 vsapi->mapSetFloat(Props, "_AbsoluteTime", currentTime, maReplace);
131 } else {
132 Frame = FFMS_GetFrame(V, n, &E);
133 FFMS_Track *T = FFMS_GetTrackFromVideo(V);
134 const FFMS_TrackTimeBase *TB = FFMS_GetTimeBase(T);
135 int64_t num;
136 if (n + 1 < VI[0].numFrames)
137 num = FFMS_GetFrameInfo(T, n + 1)->PTS - FFMS_GetFrameInfo(T, n)->PTS;
138 else if (n > 0) // simply use the second to last frame's duration for the last one, should be good enough
139 num = FFMS_GetFrameInfo(T, n)->PTS - FFMS_GetFrameInfo(T, n - 1)->PTS;
140 else // just make it one timebase if it's a single frame clip
141 num = 1;
142 int64_t DurNum = TB->Num * num;
143 int64_t DurDen = TB->Den * 1000;
144 vsh::reduceRational(&DurNum, &DurDen);
145 vsapi->mapSetInt(Props, "_DurationNum", DurNum, maReplace);
146 vsapi->mapSetInt(Props, "_DurationDen", DurDen, maReplace);
147 vsapi->mapSetFloat(Props, "_AbsoluteTime", ((static_cast<double>(TB->Num) / 1000) * FFMS_GetFrameInfo(T, n)->PTS) / TB->Den, maReplace);
148 }
149
150 if (Frame == nullptr)
151 throw std::runtime_error(E.Buffer);
152
153 // Set AR variables
154 if (SARNum > 0 && SARDen > 0) {
155 vsapi->mapSetInt(Props, "_SARNum", SARNum, maReplace);
156 vsapi->mapSetInt(Props, "_SARDen", SARDen, maReplace);
157 }
158
159 vsapi->mapSetInt(Props, "_Matrix", Frame->ColorSpace, maReplace);
160 vsapi->mapSetInt(Props, "_Primaries", Frame->ColorPrimaries, maReplace);
161 vsapi->mapSetInt(Props, "_Transfer", Frame->TransferCharateristics, maReplace);
162 if (Frame->ChromaLocation > 0)
163 vsapi->mapSetInt(Props, "_ChromaLocation", Frame->ChromaLocation - 1, maReplace);
164
165 if (Frame->ColorRange == FFMS_CR_MPEG)
166 vsapi->mapSetInt(Props, "_ColorRange", 1, maReplace);
167 else if (Frame->ColorRange == FFMS_CR_JPEG)
168 vsapi->mapSetInt(Props, "_ColorRange", 0, maReplace);
169 vsapi->mapSetData(Props, "_PictType", &Frame->PictType, 1, dtUtf8, maReplace);
170
171 // Set field information
172 int FieldBased = 0;
173 if (Frame->InterlacedFrame)
174 FieldBased = (Frame->TopFieldFirst ? 2 : 1);
175 vsapi->mapSetInt(Props, "_FieldBased", FieldBased, maReplace);
176
177 if (Frame->HasMasteringDisplayPrimaries) {
178 vsapi->mapSetFloatArray(Props, "MasteringDisplayPrimariesX", Frame->MasteringDisplayPrimariesX, 3);
179 vsapi->mapSetFloatArray(Props, "MasteringDisplayPrimariesY", Frame->MasteringDisplayPrimariesY, 3);
180 vsapi->mapSetFloat(Props, "MasteringDisplayWhitePointX", Frame->MasteringDisplayWhitePointX, maReplace);
181 vsapi->mapSetFloat(Props, "MasteringDisplayWhitePointY", Frame->MasteringDisplayWhitePointY, maReplace);
182 }
183
184 if (Frame->HasMasteringDisplayLuminance) {
185 vsapi->mapSetFloat(Props, "MasteringDisplayMinLuminance", Frame->MasteringDisplayMinLuminance, maReplace);
186 vsapi->mapSetFloat(Props, "MasteringDisplayMaxLuminance", Frame->MasteringDisplayMaxLuminance, maReplace);
187 }
188
189 if (Frame->HasContentLightLevel) {
190 vsapi->mapSetFloat(Props, "ContentLightLevelMax", Frame->ContentLightLevelMax, maReplace);
191 vsapi->mapSetFloat(Props, "ContentLightLevelAverage", Frame->ContentLightLevelAverage, maReplace);
192 }
193
194 if (Frame->DolbyVisionRPU && Frame->DolbyVisionRPUSize > 0) {
195 vsapi->mapSetData(Props, "DolbyVisionRPU", reinterpret_cast<const char *>(Frame->DolbyVisionRPU), Frame->DolbyVisionRPUSize, dtBinary, maReplace);
196 }
197
198 if (Frame->HDR10Plus && Frame->HDR10PlusSize > 0) {
199 vsapi->mapSetData(Props, "HDR10Plus", reinterpret_cast<const char *>(Frame->HDR10Plus), Frame->HDR10PlusSize, dtBinary, maReplace);
200 }
201
202 OutputFrame(Frame, Dst, vsapi);
203 if (OutputAlpha) {
204 VSFrame *AlphaDst = vsapi->newVideoFrame(&VI[1].format, VI[1].width, VI[1].height, nullptr, core);
205 vsapi->mapSetInt(vsapi->getFramePropertiesRW(AlphaDst), "_ColorRange", 0, maReplace);
206 OutputAlphaFrame(Frame, VI[0].format.numPlanes, AlphaDst, vsapi);
207 vsapi->mapConsumeFrame(Props, "_Alpha", AlphaDst, maReplace);
208 }
209
210 const FFMS_VideoProperties *VP = FFMS_GetVideoProperties(V);
211 vsapi->mapSetInt(Props, "Flip", VP->Flip, maReplace);
212 vsapi->mapSetInt(Props, "Rotation", VP->Rotation, maReplace);
213
214 return Dst;
215 }
216
217 const VSFrame *VS_CC VSVideoSource4::GetFrame(int n, int activationReason, void *instanceData, void **, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) {
218 VSVideoSource4 *vs = static_cast<VSVideoSource4 *>(instanceData);
219 if (activationReason == arInitial) {
220 if (vs->LastFrame < n && vs->LastFrame > n - vs->CacheThreshold) {
221 for (int i = vs->LastFrame + 1; i < n; i++) {
222 try {
223 const VSFrame *frame = vs->GetVSFrame(i, core, vsapi);
224 vsapi->cacheFrame(frame, i, frameCtx);
225 vsapi->freeFrame(frame);
226 } catch (std::runtime_error &) {
227 // don't care if it errors out on frames we don't actually have to deliver
228 }
229 }
230 }
231
232 try {
233 const VSFrame *frame = vs->GetVSFrame(n, core, vsapi);
234 vs->LastFrame = n;
235 return frame;
236 } catch (std::runtime_error &e) {
237 vsapi->setFilterError(e.what(), frameCtx);
238 }
239
240 }
241
242 return nullptr;
243 }
244
245 void VS_CC VSVideoSource4::Free(void *instanceData, VSCore *, const VSAPI *) {
246 delete static_cast<VSVideoSource4 *>(instanceData);
247 }
248
249 VSVideoSource4::VSVideoSource4(const char *SourceFile, int Track, FFMS_Index *Index,
250 int AFPSNum, int AFPSDen, int Threads, int SeekMode,
251 int ResizeToWidth, int ResizeToHeight, const char *ResizerName,
252 int Format, bool OutputAlpha, const VSAPI *vsapi, VSCore *core)
253 : FPSNum(AFPSNum), FPSDen(AFPSDen), OutputAlpha(OutputAlpha) {
254
255 VI[0] = {};
256 VI[1] = {};
257
258 char ErrorMsg[1024];
259 FFMS_ErrorInfo E;
260 E.Buffer = ErrorMsg;
261 E.BufferSize = sizeof(ErrorMsg);
262
263 V = FFMS_CreateVideoSource(SourceFile, Track, Index, Threads, SeekMode, &E);
264 if (!V) {
265 throw std::runtime_error(std::string("Source: ") + E.Buffer);
266 }
267 try {
268 InitOutputFormat(ResizeToWidth, ResizeToHeight, ResizerName, Format, vsapi, core);
269 } catch (std::exception &) {
270 FFMS_DestroyVideoSource(V);
271 throw;
272 }
273
274 const FFMS_VideoProperties *VP = FFMS_GetVideoProperties(V);
275
276 VI[0].fpsDen = VP->FPSDenominator;
277 VI[0].fpsNum = VP->FPSNumerator;
278 VI[0].numFrames = VP->NumFrames;
279 vsh::reduceRational(&VI[0].fpsNum, &VI[0].fpsDen);
280
281 if (FPSNum > 0 && FPSDen > 0) {
282 vsh::reduceRational(&FPSNum, &FPSDen);
283 VI[0].fpsDen = FPSDen;
284 VI[0].fpsNum = FPSNum;
285 if (VP->NumFrames > 1) {
286 VI[0].numFrames = static_cast<int>((VP->LastTime - VP->FirstTime) * (1 + 1. / (VP->NumFrames - 1)) * FPSNum / FPSDen + 0.5);
287 if (VI[0].numFrames < 1)
288 VI[0].numFrames = 1;
289 } else {
290 VI[0].numFrames = 1;
291 }
292 }
293
294 if (OutputAlpha) {
295 VI[1] = VI[0];
296 vsapi->queryVideoFormat(&VI[1].format, cfGray, VI[0].format.sampleType, VI[0].format.bitsPerSample, 0, 0, core);
297 }
298
299 SARNum = VP->SARNum;
300 SARDen = VP->SARDen;
301 }
302
303 VSVideoSource4::~VSVideoSource4() {
304 FFMS_DestroyVideoSource(V);
305 }
306
307 const VSVideoInfo *VSVideoSource4::GetVideoInfo() const {
308 return &VI[0];
309 }
310
311 void VSVideoSource4::SetCacheThreshold(int threshold) {
312 CacheThreshold = threshold;
313 }
314
315 void VSVideoSource4::InitOutputFormat(int ResizeToWidth, int ResizeToHeight,
316 const char *ResizerName, int ConvertToFormat, const VSAPI *vsapi, VSCore *core) {
317
318 char ErrorMsg[1024];
319 FFMS_ErrorInfo E;
320 E.Buffer = ErrorMsg;
321 E.BufferSize = sizeof(ErrorMsg);
322
323 const FFMS_Frame *F = FFMS_GetFrame(V, 0, &E);
324 if (!F) {
325 std::string buf = "Source: ";
326 buf += E.Buffer;
327 throw std::runtime_error(buf);
328 }
329
330 std::vector<int> TargetFormats;
331 int npixfmt = GetNumPixFmts();
332 for (int i = 0; i < npixfmt; i++)
333 if (IsRealNativeEndianPlanar(*av_pix_fmt_desc_get((AVPixelFormat)i)))
334 TargetFormats.push_back(i);
335 TargetFormats.push_back(AV_PIX_FMT_NONE);
336
337 int TargetPixelFormat = AV_PIX_FMT_NONE;
338 if (ConvertToFormat != pfNone) {
339 TargetPixelFormat = FormatConversionToPixelFormat(ConvertToFormat, OutputAlpha, core, vsapi);
340 if (TargetPixelFormat == AV_PIX_FMT_NONE)
341 throw std::runtime_error(std::string("Source: Invalid output colorspace specified"));
342
343 TargetFormats.clear();
344 TargetFormats.push_back(TargetPixelFormat);
345 TargetFormats.push_back(-1);
346 }
347
348 if (ResizeToWidth <= 0)
349 ResizeToWidth = F->EncodedWidth;
350
351 if (ResizeToHeight <= 0)
352 ResizeToHeight = F->EncodedHeight;
353
354 int Resizer = ResizerNameToSWSResizer(ResizerName);
355 if (Resizer == 0)
356 throw std::runtime_error(std::string("Source: Invalid resizer name specified"));
357
358 if (FFMS_SetOutputFormatV2(V, &TargetFormats[0],
359 ResizeToWidth, ResizeToHeight, Resizer, &E))
360 throw std::runtime_error(std::string("Source: No suitable output format found"));
361
362 F = FFMS_GetFrame(V, 0, &E);
363 TargetFormats.clear();
364 TargetFormats.push_back(F->ConvertedPixelFormat);
365 TargetFormats.push_back(-1);
366
367 // This trick is required to first get the "best" default format and then set only that format as the output
368 if (FFMS_SetOutputFormatV2(V, TargetFormats.data(), ResizeToWidth, ResizeToHeight, Resizer, &E))
369 throw std::runtime_error(std::string("Source: No suitable output format found"));
370
371 F = FFMS_GetFrame(V, 0, &E);
372
373 // Don't output alpha if the clip doesn't have it
374 if (!HasAlpha(*av_pix_fmt_desc_get((AVPixelFormat)F->ConvertedPixelFormat)))
375 OutputAlpha = false;
376
377 FormatConversionToVS(VI[0].format, F->ConvertedPixelFormat, core, vsapi);
378 if (VI[0].format.colorFamily == cfUndefined)
379 throw std::runtime_error(std::string("Source: No suitable output format found"));
380
381 VI[0].width = F->ScaledWidth;
382 VI[0].height = F->ScaledHeight;
383
384 // Crop to obey subsampling width/height requirements
385 VI[0].width -= VI[0].width % (1 << VI[0].format.subSamplingW);
386 VI[0].height -= VI[0].height % (1 << VI[0].format.subSamplingH);
387 }
388
389 void VSVideoSource4::OutputFrame(const FFMS_Frame *Frame, VSFrame *Dst, const VSAPI *vsapi) {
390 const int RGBPlaneOrder[3] = { 2, 0, 1 };
391 const VSVideoFormat *fi = vsapi->getVideoFrameFormat(Dst);
392 if (fi->colorFamily == cfRGB) {
393 for (int i = 0; i < fi->numPlanes; i++)
394 vsh::bitblt(vsapi->getWritePtr(Dst, i), vsapi->getStride(Dst, i), Frame->Data[RGBPlaneOrder[i]], Frame->Linesize[RGBPlaneOrder[i]],
395 vsapi->getFrameWidth(Dst, i) * fi->bytesPerSample, vsapi->getFrameHeight(Dst, i));
396 } else {
397 for (int i = 0; i < fi->numPlanes; i++)
398 vsh::bitblt(vsapi->getWritePtr(Dst, i), vsapi->getStride(Dst, i), Frame->Data[i], Frame->Linesize[i],
399 vsapi->getFrameWidth(Dst, i) * fi->bytesPerSample, vsapi->getFrameHeight(Dst, i));
400 }
401 }
402
403 void VSVideoSource4::OutputAlphaFrame(const FFMS_Frame *Frame, int Plane, VSFrame *Dst, const VSAPI *vsapi) {
404 const VSVideoFormat *fi = vsapi->getVideoFrameFormat(Dst);
405 vsh::bitblt(vsapi->getWritePtr(Dst, 0), vsapi->getStride(Dst, 0), Frame->Data[Plane], Frame->Linesize[Plane],
406 vsapi->getFrameWidth(Dst, 0) * fi->bytesPerSample, vsapi->getFrameHeight(Dst, 0));
407 }