Debian Codegraph @

src/core/track.cpp

raw symbols SCIP
1 // Copyright (c) 2014 Thomas Goyne <[email protected]>
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 "track.h"
22
23 #include "utils.h"
24 #include "zipfile.h"
25 #include "indexing.h"
26
27 #include <algorithm>
28 #include <cmath>
29 #include <cstdlib>
30
31 extern "C" {
32 #include <libavutil/avutil.h>
33 #include <libavutil/common.h>
34 #include <libavutil/mathematics.h>
35 }
36
37 namespace {
38 FrameInfo ReadFrame(ZipFile &stream, FrameInfo const& prev, const FFMS_TrackType TT) {
39 FrameInfo f{};
40 f.PTS = stream.Read<int64_t>() + prev.PTS;
41 f.OriginalPTS = stream.Read<int64_t>() + prev.OriginalPTS;
42 f.KeyFrame = !!stream.Read<int8_t>();
43 f.FilePos = stream.Read<int64_t>() + prev.FilePos;
44 f.MarkedHidden = !!stream.Read<int8_t>();
45
46 if (TT == FFMS_TYPE_AUDIO) {
47 f.SampleStart = prev.SampleStart + prev.SampleCount;
48 f.SampleCount = stream.Read<uint32_t>() + prev.SampleCount;
49 } else if (TT == FFMS_TYPE_VIDEO) {
50 f.OriginalPos = static_cast<size_t>(stream.Read<uint64_t>() + prev.OriginalPos + 1);
51 f.PosInDecodingOrder = static_cast<size_t>(stream.Read<uint64_t>() + prev.PosInDecodingOrder + 1);
52 f.RepeatPict = stream.Read<int32_t>();
53 f.SecondField = !!stream.Read<int8_t>();
54 }
55 return f;
56 }
57
58 static void WriteFrame(ZipFile &stream, FrameInfo const& f, FrameInfo const& prev, const FFMS_TrackType TT) {
59 stream.Write(f.PTS - prev.PTS);
60 stream.Write(f.OriginalPTS - prev.OriginalPTS);
61 stream.Write<int8_t>(f.KeyFrame);
62 stream.Write(f.FilePos - prev.FilePos);
63 stream.Write<uint8_t>(f.MarkedHidden);
64
65 if (TT == FFMS_TYPE_AUDIO)
66 stream.Write(f.SampleCount - prev.SampleCount);
67 else if (TT == FFMS_TYPE_VIDEO) {
68 stream.Write(static_cast<uint64_t>(f.OriginalPos) - prev.OriginalPos - 1);
69 stream.Write(static_cast<uint64_t>(f.PosInDecodingOrder) - prev.PosInDecodingOrder - 1);
70 stream.Write<int32_t>(f.RepeatPict);
71 stream.Write<uint8_t>(f.SecondField);
72 }
73 }
74 }
75
76 FFMS_Track::FFMS_Track()
77 : Data(std::make_shared<TrackData>())
78 {
79 }
80
81 FFMS_Track::FFMS_Track(int64_t Num, int64_t Den, FFMS_TrackType TT, bool HasDiscontTS, bool UseDTS, bool HasTS)
82 : Data(std::make_shared<TrackData>())
83 , TT(TT)
84 , UseDTS(UseDTS)
85 , HasTS(HasTS)
86 , HasDiscontTS(HasDiscontTS) {
87 TB.Num = Num;
88 TB.Den = Den;
89 }
90
91 FFMS_Track::FFMS_Track(ZipFile &stream)
92 : Data(std::make_shared<TrackData>()) {
93 frame_vec &Frames = Data->Frames;
94 TT = static_cast<FFMS_TrackType>(stream.Read<uint8_t>());
95 TB.Num = stream.Read<int64_t>();
96 TB.Den = stream.Read<int64_t>();
97 LastDuration = stream.Read<int64_t>();
98 MaxBFrames = stream.Read<int32_t>();
99 UseDTS = !!stream.Read<uint8_t>();
100 HasTS = !!stream.Read<uint8_t>();
101 HasDiscontTS = !!stream.Read<uint8_t>();
102 size_t FrameCount = static_cast<size_t>(stream.Read<uint64_t>());
103
104 if (!FrameCount) return;
105
106 FrameInfo temp{};
107 Frames.reserve(FrameCount);
108 for (size_t i = 0; i < FrameCount; ++i)
109 Frames.push_back(ReadFrame(stream, i == 0 ? temp : Frames.back(), TT));
110
111 if (TT == FFMS_TYPE_VIDEO)
112 GeneratePublicInfo();
113 }
114
115 void FFMS_Track::Write(ZipFile &stream) const {
116 frame_vec &Frames = Data->Frames;
117 stream.Write<uint8_t>(TT);
118 stream.Write(TB.Num);
119 stream.Write(TB.Den);
120 stream.Write<int64_t>(LastDuration);
121 stream.Write<int32_t>(MaxBFrames);
122 stream.Write<uint8_t>(UseDTS);
123 stream.Write<uint8_t>(HasTS);
124 stream.Write<uint8_t>(HasDiscontTS);
125 stream.Write<uint64_t>(size());
126
127 if (empty()) return;
128
129 FrameInfo temp{};
130 for (size_t i = 0; i < size(); ++i)
131 WriteFrame(stream, Frames[i], i == 0 ? temp : Frames[i - 1], TT);
132 }
133
134 void FFMS_Track::AddVideoFrame(int64_t PTS, int64_t DTS, int RepeatPict, bool KeyFrame, int FrameType, int64_t FilePos, bool MarkedHidden, bool SecondField) {
135 Data->Frames.push_back({ PTS, 0, FilePos, 0, 0, 0, 0, FrameType, RepeatPict, KeyFrame, MarkedHidden, SecondField, DTS });
136 }
137
138 void FFMS_Track::AddAudioFrame(int64_t PTS, int64_t DTS, int64_t SampleStart, uint32_t SampleCount, bool KeyFrame, int64_t FilePos, bool MarkedHidden) {
139 if (SampleCount > 0) {
140 Data->Frames.push_back({ PTS, 0, FilePos, SampleStart, SampleCount,
141 0, 0, 0, 0, KeyFrame, MarkedHidden, false, DTS });
142 }
143 }
144
145 void FFMS_Track::WriteTimecodes(const char *TimecodeFile) const {
146 frame_vec &Frames = Data->Frames;
147 FileHandle file(TimecodeFile, "w", FFMS_ERROR_TRACK, FFMS_ERROR_FILE_WRITE);
148
149 file.Printf("# timecode format v2\n");
150 for (size_t i = 0; i < size(); ++i) {
151 if (!Frames[i].Skipped())
152 file.Printf("%.02f\n", (Frames[i].PTS * TB.Num) / (double)TB.Den);
153 }
154 }
155
156 static bool PTSComparison(FrameInfo FI1, FrameInfo FI2) {
157 return FI1.PTS < FI2.PTS;
158 }
159
160 int FFMS_Track::FrameFromPTS(int64_t PTS, bool AllowHidden) const {
161 FrameInfo F;
162 F.PTS = PTS;
163
164 auto Pos = std::lower_bound(begin(), end(), F, PTSComparison);
165 while (Pos != end() && (!AllowHidden && Pos->Skipped()) && Pos->PTS == PTS)
166 Pos++;
167
168 if (Pos == end() || Pos->PTS != PTS)
169 return -1;
170 return std::distance(begin(), Pos);
171 }
172
173 int FFMS_Track::FrameFromPos(int64_t Pos, bool AllowHidden) const {
174 for (size_t i = 0; i < size(); i++)
175 if (Data->Frames[i].FilePos == Pos && (AllowHidden || !Data->Frames[i].Skipped()))
176 return static_cast<int>(i);
177 return -1;
178 }
179
180 int FFMS_Track::ClosestFrameFromPTS(int64_t PTS) const {
181 FrameInfo F;
182 F.PTS = PTS;
183
184 auto Pos = std::lower_bound(begin(), end(), F, PTSComparison);
185 while (Pos != end() && Pos->Skipped() && Pos->PTS == PTS)
186 Pos++;
187
188 if (Pos == end())
189 return static_cast<int>(size() - 1);
190 size_t Frame = std::distance(begin(), Pos);
191 if (Pos == begin() || FFABS(Pos->PTS - PTS) <= FFABS((Pos - 1)->PTS - PTS))
192 return static_cast<int>(Frame);
193 return static_cast<int>(Frame - 1);
194 }
195
196 int FFMS_Track::FindClosestVideoKeyFrame(int Frame) const {
197 frame_vec &Frames = Data->Frames;
198 Frame = std::min(std::max(Frame, 0), static_cast<int>(size()) - 1);
199 size_t PosInDecodingOrder = Frames[Frame].PosInDecodingOrder;
200 for (; PosInDecodingOrder > 0 && !(Frames[Frames[PosInDecodingOrder].OriginalPos].KeyFrame && Frames[Frames[PosInDecodingOrder].OriginalPos].PTS <= Frames[Frame].PTS); PosInDecodingOrder--);
201
202 return Frames[PosInDecodingOrder].OriginalPos;
203 }
204
205 int FFMS_Track::RealFrameNumber(int Frame) const {
206 return Data->RealFrameNumbers[Frame];
207 }
208
209 int FFMS_Track::VisibleFrameCount() const {
210 return TT == FFMS_TYPE_AUDIO ? static_cast<int>(Data->Frames.size()) : static_cast<int>(Data->RealFrameNumbers.size());
211 }
212
213 void FFMS_Track::MaybeReorderFrames() {
214 frame_vec &Frames = Data->Frames;
215 // First check if we need to do anything
216 bool has_b_frames = false;
217 for (size_t i = 1; i < size(); ++i) {
218 // If the timestamps are already out of order, then they actually are
219 // presentation timestamps and we don't need to do anything
220 if (Frames[i].PTS < Frames[i - 1].PTS)
221 return;
222
223 if (Frames[i].FrameType == AV_PICTURE_TYPE_B) {
224 has_b_frames = true;
225
226 // Reordering files with multiple b-frames is currently not
227 // supported
228 if (Frames[i - 1].FrameType == AV_PICTURE_TYPE_B)
229 return;
230 }
231 }
232
233 // Don't need to do anything if there are no b-frames as presentation order
234 // equals decoding order
235 if (!has_b_frames)
236 return;
237
238 // We have b-frames, but the timestamps are monotonically increasing. This
239 // means that the timestamps we have are decoding timestamps, and we want
240 // presentation time stamps. Convert DTS to PTS by swapping the timestamp
241 // of each b-frame with the frame before it. This only works for the
242 // specific case of b-frames which reference the frame immediately after
243 // them temporally, but that happens to cover the only files I've seen
244 // with b-frames and no presentation timestamps.
245 for (size_t i = 1; i < size(); ++i) {
246 if (Frames[i].FrameType == AV_PICTURE_TYPE_B)
247 std::swap(Frames[i].PTS, Frames[i - 1].PTS);
248 }
249 }
250
251 void FFMS_Track::RevertToDTS() {
252 frame_vec &Frames = Data->Frames;
253 for (size_t i = 0; i < size(); ++i)
254 Frames[i].PTS = Frames[i].DTS;
255
256 UseDTS = true;
257 }
258
259 void FFMS_Track::MaybeHideFrames() {
260 frame_vec &Frames = Data->Frames;
261 // Awful handling for interlaced H.264: each frame is output twice, so hide
262 // frames with an invalid file position. The PTS will not match sometimes,
263 // since libavformat makes up timestamps... but only sometimes.
264 for (size_t i = 1; i < size(); ++i) {
265 FrameInfo const& prev = Frames[i - 1];
266 FrameInfo& cur = Frames[i];
267
268 if (prev.FilePos >= 0 && (cur.FilePos == -1 || cur.FilePos == prev.FilePos) && !prev.Skipped())
269 cur.MarkedHidden = true;
270 }
271 }
272
273 void FFMS_Track::FillAudioGaps() {
274 frame_vec &Frames = Data->Frames;
275 // There may not be audio data for the entire duration of the audio track,
276 // as some formats support gaps between the end time of one packet and the
277 // PTS of the next audio packet, and we should zero-fill those gaps.
278 // However, garbage or missing timestamps for audio tracks are very common,
279 // so we only want to trust them if they're all present, monotonically
280 // increasing, and result in a total duration meaningfully longer than the
281 // samples we have would cover.
282 if (size() < 2 || !HasTS || front().PTS == AV_NOPTS_VALUE || back().PTS == AV_NOPTS_VALUE)
283 return;
284
285 const auto DurationToSamples = [this](int64_t Dur) {
286 auto Num = TB.Num * SampleRate;
287 auto Den = TB.Den * 1000;
288 return av_rescale(Dur, Num, Den);
289 };
290
291 const auto SamplesToDuration = [this](int64_t Samples) {
292 auto Num = TB.Den * 1000;
293 auto Den = TB.Num * SampleRate;
294 return av_rescale(Samples, Num, Den);
295 };
296
297 if (HasDiscontTS) {
298 int64_t shift = 0;
299 Frames[0].OriginalPTS = Frames[0].PTS;
300 for (size_t i = 1; i < size(); i++) {
301 Frames[i].OriginalPTS = Frames[i].PTS;
302 if (Frames[i].PTS != AV_NOPTS_VALUE && Frames[i].OriginalPTS <= Frames[i-1].OriginalPTS)
303 shift = -(Frames[i].PTS) + Frames[i-1].PTS + SamplesToDuration(Frames[i-1].SampleCount);
304 Frames[i].PTS += shift;
305 }
306 }
307
308 const auto ActualSamples = back().SampleStart + back().SampleCount;
309 const auto ExpectedSamples = DurationToSamples(back().PTS - front().PTS) + back().SampleCount;
310 if (ActualSamples + 5 > ExpectedSamples) // arbitrary threshold to cover rounding/not worth adjusting
311 return;
312
313 // Verify that every frame has a timestamp and that they monotonically
314 // increase, as otherwise we can't trust them
315 auto PrevPTS = front().PTS - 1;
316 for (auto const& frame : *this) {
317 if (frame.PTS == AV_NOPTS_VALUE || frame.PTS <= PrevPTS)
318 return;
319 PrevPTS = frame.PTS;
320 }
321
322 // There are some missing samples and the timestamps appear to all be valid,
323 // so go ahead and extend the frames to cover the gaps
324 const auto FirstPTS = front().PTS;
325 auto PrevFrame = &Frames.front();
326 int32_t Shift = 0;
327 for (auto& Frame : Frames) {
328 if (Shift > 0)
329 Frame.SampleStart += Shift;
330
331 const auto ExpectedStartSample = DurationToSamples(Frame.PTS - FirstPTS);
332 const auto Gap = static_cast<int32_t>(ExpectedStartSample - Frame.SampleStart);
333 if (Gap > 0) {
334 PrevFrame->SampleCount += Gap;
335 Frame.SampleStart = ExpectedStartSample;
336 }
337 Shift += Gap;
338 PrevFrame = &Frame;
339 }
340 }
341
342 void FFMS_Track::FinalizeTrack() {
343 frame_vec &Frames = Data->Frames;
344 // With some formats (such as Vorbis) a bad final packet results in a
345 // frame with PTS 0, which we don't want to sort to the beginning
346 if (size() > 2 && front().PTS >= back().PTS)
347 Frames.pop_back();
348
349 if (TT != FFMS_TYPE_VIDEO)
350 return;
351
352 for (size_t i = 0; i < size(); i++) {
353 Frames[i].PosInDecodingOrder = i;
354 Frames[i].OriginalPTS = Frames[i].PTS;
355 }
356
357 MaybeReorderFrames();
358
359 if (size() > 2 && HasDiscontTS) {
360 std::vector<size_t> secs = { 0 };
361
362 auto lastPTS = Frames[0].PTS;
363 const auto thresh = std::abs(Frames[1].PTS - Frames[0].PTS) * 16; // A bad approximation of 16 frames, the max reorder buffer size.
364 for (size_t i = 0; i < size(); i++) {
365 if (Frames[i].PTS < lastPTS && (lastPTS - Frames[i].PTS) > thresh && i + 1 < size()) {
366 secs.push_back(i);
367 i++; // Sections must be at least 2 frames long.
368 }
369 lastPTS = Frames[i].PTS;
370 }
371
372 // We need to sort each distinct sections by PTS to account for any reordering.
373 for (size_t i = 0; i < secs.size() - 1; i++)
374 sort(Frames.begin() + secs[i], Frames.begin() + secs[i + 1], PTSComparison);
375 sort(Frames.begin() + secs.back(), Frames.end(), PTSComparison);
376
377 // Try and make up some sane timestamps based on previous sections, while
378 // keeping the same frame durations.
379 for (size_t i = 1; i < secs.size(); i++) {
380 const auto shift = -(Frames[secs[i]].PTS) + (Frames[secs[i] + 1].PTS - Frames[secs[i]].PTS) + Frames[secs[i] - 1].PTS;
381 size_t end;
382 if (i == secs.size() - 1)
383 end = Frames.size();
384 else
385 end = secs[i + 1];
386 for (size_t j = secs[i]; j < end; j++)
387 Frames[j].PTS += shift;
388 }
389 } else {
390 sort(Frames.begin(), Frames.end(), PTSComparison);
391 }
392
393 std::vector<size_t> ReorderTemp;
394 ReorderTemp.reserve(size());
395
396 for (size_t i = 0; i < size(); i++)
397 ReorderTemp.push_back(Frames[i].PosInDecodingOrder);
398
399 for (size_t i = 0; i < size(); i++)
400 Frames[ReorderTemp[i]].OriginalPos = i;
401
402 for (size_t i = 0; i < size(); i++) {
403 if (Frames[Frames[i].OriginalPos].PosInDecodingOrder != i ||
404 Frames[Frames[i].PosInDecodingOrder].OriginalPos != i)
405 throw FFMS_Exception(FFMS_ERROR_INDEXING, FFMS_ERROR_CODEC, "Insanity detected when tracking frame reordering");
406 }
407
408 GeneratePublicInfo();
409
410 // If the last packet in the file did not have a duration set,
411 // fudge one based on the previous frame's duration.
412 if (LastDuration == 0) {
413 size_t InfoSize = Data->PublicFrameInfo.size();
414 if (InfoSize >= 2)
415 LastDuration = Data->PublicFrameInfo[InfoSize - 1].PTS - Data->PublicFrameInfo[InfoSize - 2].PTS;
416 }
417 }
418
419 void FFMS_Track::GeneratePublicInfo() {
420 frame_vec &Frames = Data->Frames;
421 std::vector<int> &RealFrameNumbers = Data->RealFrameNumbers;
422 std::vector<FFMS_FrameInfo> &PublicFrameInfo = Data->PublicFrameInfo;
423 RealFrameNumbers.reserve(size());
424 PublicFrameInfo.reserve(size());
425 for (size_t i = 0; i < size(); ++i) {
426 if (Frames[i].Skipped())
427 continue;
428 RealFrameNumbers.push_back(static_cast<int>(i));
429
430 FFMS_FrameInfo info = { Frames[i].PTS, Frames[i].RepeatPict, Frames[i].KeyFrame, Frames[i].OriginalPTS };
431 PublicFrameInfo.push_back(info);
432 }
433 }
434
435 const FFMS_FrameInfo *FFMS_Track::GetFrameInfo(size_t N) const {
436 std::vector<FFMS_FrameInfo> &PublicFrameInfo = Data->PublicFrameInfo;
437 if (N >= PublicFrameInfo.size()) return nullptr;
438 return &PublicFrameInfo[N];
439 }