1
// Copyright (c) 2005-2006, Rodrigo Braz Monteiro, Fredrik Mellbin
2
// All rights reserved.
4
// Redistribution and use in source and binary forms, with or without
5
// modification, are permitted provided that the following conditions are met:
7
// * Redistributions of source code must retain the above copyright notice,
8
// this list of conditions and the following disclaimer.
9
// * Redistributions in binary form must reproduce the above copyright notice,
10
// this list of conditions and the following disclaimer in the documentation
11
// and/or other materials provided with the distribution.
12
// * Neither the name of the Aegisub Group nor the names of its contributors
13
// may be used to endorse or promote products derived from this software
14
// without specific prior written permission.
16
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
// POSSIBILITY OF SUCH DAMAGE.
28
// -----------------------------------------------------------------------------
32
// Website: http://aegisub.cellosoft.com
33
// Contact: mailto:zeratul@cellosoft.com
41
#include <wx/filename.h>
45
#include "text_file_reader.h"
46
#include "text_file_writer.h"
51
void FrameRate::Clear () {
58
void FrameRate::AddFrame(int ms) {
65
void FrameRate::CalcAverage() {
67
if (Frame.size() <= 1)
68
throw _("No timecodes to average");
70
AverageFrameRate = double(Frame.back()) / (Frame.size()-1);
74
//////////////////////// FrameRate //////////////////////
77
FrameRate::FrameRate() {
84
FrameRate::~FrameRate() {
91
void FrameRate::Load(wxString filename) {
96
// Check if file exists
97
wxFileName filetest(filename);
98
if (!filetest.FileExists()) throw _T("File not found.");
101
TextFileReader file(filename);
106
curLine = file.ReadLineFromFile();
107
wxString header = curLine;
108
bool first = (header.Left(7).Lower() == _T("assume "));
110
// V1, code converted from avcvfr9
111
if (header == _T("# timecode format v1") || first) {
112
// Locate the default fps line
115
if (!first) curLine = file.ReadLineFromFile();
118
// Skip empty lines and comments
119
if (curLine == _T("") || curLine.Left(1) == _T("#")) continue;
121
else if (curLine.Left(7).Lower() != _T("assume ")) throw _T("Encountered data before 'Assume <fps>' line");
123
if (!curLine.Mid(6).ToDouble(&AverageFrameRate) || AverageFrameRate <= 0) throw _T("Invalid 'Assume <fps>' line");
126
} while (file.HasMoreLines());
128
// Read and expand all timecodes to v2
131
double currenttime = 0;
138
while (file.HasMoreLines()) {
139
curLine = file.ReadLineFromFile();
141
// Skip empty lines and comments
142
if (curLine == _T("") || curLine.Left(1) == _T("#"))
145
wxString tmp = curLine.AfterFirst(_T(','));
146
wxString temp = curLine.BeforeFirst(_T(','));
147
if (!temp.ToLong(&lstart) || lstart < 0)
148
throw _T("Timecode parsing error, invalid start format found");
149
temp = tmp.BeforeLast(_T(','));
150
if (!temp.ToLong(&lend) || lend < 0)
151
throw _T("Timecode parsing error, invalid end format found");
152
temp = tmp.AfterLast(_T(','));
153
if (!temp.ToDouble(&lfps) || lfps <= 0)
154
throw _T("Timecode parsing error, invalid fps format found");
156
if (lstart <= lposition)
157
throw _T("Timecode parsing error, out of order or overlapping timecode range found");
160
for (int i = 0; i <= lstart - lposition - 2; i++)
161
AddFrame((int)(floor(currenttime+(i*1000) / AverageFrameRate)));
163
currenttime += ((lstart - lposition - 1)*1000) / AverageFrameRate;
165
for (int i = 0; i <= lend - lstart; i++)
166
AddFrame((int)(floor(currenttime+(i*1000) / lfps)));
168
currenttime += ((lend - lstart + 1)*1000) / lfps;
173
AddFrame(currenttime);
174
last_time = currenttime;
175
last_frame = (int)Frame.size() - 1;
179
else if (header == _T("# timecode format v2")) {
180
// Assigns new VFR file
188
while (file.HasMoreLines()) {
189
curLine = file.ReadLineFromFile();
191
//skip empty lines and comments
192
if (curLine == _T("") || curLine.Left(1) == _T("#"))
195
wxString tmp = curLine.BeforeFirst(_T('.'));
198
if (lftime >= cftime)
199
throw _T("Out of order/too close timecodes found");
206
last_frame = (int)Frame.size() - 1;
214
throw _T("Unknown time code file format.");
229
Options.AddToRecentList(filename,_T("Recent timecodes"));
235
void FrameRate::Save(wxString filename) {
236
TextFileWriter file(filename,_T("ASCII"));
237
file.WriteLineToFile(_T("# timecode format v2"));
238
for (size_t i=0;i<Frame.size();i++) {
239
file.WriteLineToFile(wxString::Format(_T("%f"),(float)Frame[i]));
246
void FrameRate::Unload () {
247
FrameRateType = NONE;
248
AverageFrameRate = 0;
259
void FrameRate::SetCFR(double fps) {
263
AverageFrameRate = fps;
269
void FrameRate::SetVFR(std::vector<int> newTimes) {
279
last_time = newTimes.back();
280
last_frame = (int)newTimes.size();
284
/////////////////////////////
285
// Gets frame number at time
286
int FrameRate::PFrameAtTime(int ms,bool useceil) {
287
// Check if it's loaded
288
if (!loaded) return -1;
290
// Normalize miliseconds
293
// Get for constant frame rate
294
if (FrameRateType == CFR || Frame.size() == 0) {
295
double value = double(ms) * AverageFrameRate / 1000.0;
296
if (useceil) return (int)ceil(value);
297
else return (int)floor(value);
300
// Get for variable frame rate
301
else if (FrameRateType == VFR) {
304
//if (useceil) trueLast = ceil(last_time);
305
//else trueLast = floor(last_time);
306
trueLast = Frame[Frame.size()-1];
309
if (ms <= trueLast) {
310
// Prepare binary search
312
size_t end = last_frame;
317
while (start <= end) {
318
// Current frame being checked
319
cur = (start+end)>>1;
321
// Is it larger or equal to searched time?
322
largerEqual = Frame[cur] >= ms;
324
// If it is, is the previous smaller?
325
// If so, this is the frame we're looking for
326
if (largerEqual && (cur == 0 || Frame[cur-1] < ms)) {
327
if (useceil) return (int)cur;
331
// Not found, continue search
332
if (largerEqual) end = cur-1;
339
if (useceil) return (int)(last_frame + ceil((ms-last_time) * AverageFrameRate / 1000));
340
else return (int)(last_frame + floor((ms-last_time) * AverageFrameRate / 1000));
347
//////////////////////
348
// Gets time at frame
349
int FrameRate::PTimeAtFrame(int frame) {
351
if (!loaded) return -1;
353
// For negative/zero times, fallback to zero
354
if (frame <= 0) return 0;
356
// Constant frame rate
357
if (FrameRateType == CFR || Frame.size() == 0) {
358
return (int)floor(double(frame) / AverageFrameRate * 1000.0);
361
// Variable frame rate
362
else if (FrameRateType == VFR) {
363
// Is it inside frame rate range? If so, just get the value from timecodes table
364
if (frame < (signed) Frame.size()) return Frame.at(frame);
366
// Otherwise, calculate it
367
else return (int)floor(Frame.back() + double(frame-Frame.size()+1) / AverageFrameRate * 1000.0);
370
// Unknown frame rate type
375
/////////////////////////////
376
// Get correct frame at time
377
// returns the adjusted time for end frames when start=false
378
// otherwise for start frames
379
int FrameRate::GetFrameAtTime(int ms,bool start) {
380
return PFrameAtTime(ms,start);
384
/////////////////////////////
385
// Get correct time at frame
386
// compensates and returns an end time when start=false
387
int FrameRate::GetTimeAtFrame(int frame,bool start,bool exact) {
390
// Exact, for display
392
finalTime = PTimeAtFrame(frame);
395
// Adjusted, for subs sync
398
finalTime = (PTimeAtFrame(frame-1) + PTimeAtFrame(frame))/2;
401
//if (FrameRateType == VFR) finalTime = PTimeAtFrame(frame);
402
//else finalTime = (PTimeAtFrame(frame) + PTimeAtFrame(frame+1))/2;
403
finalTime = (PTimeAtFrame(frame) + PTimeAtFrame(frame+1))/2;
411
////////////////////////////////////////
412
// Get the current list of frames/times
413
std::vector<int> FrameRate::GetFrameTimeList() {
418
///////////////////////////////////////////
419
// Calculate the common FPS for evil stuff
420
// e.g., in a mix of 24fps and 30fps, returns 120fps
421
double FrameRate::GetCommonFPS() {
425
int sectionStart = 0;
428
// List of likely frame rates
429
std::vector<double> frameRates;
430
frameRates.push_back(15.0 / 1.001);
431
frameRates.push_back(15);
432
frameRates.push_back(24.0 / 1.001);
433
frameRates.push_back(24);
434
frameRates.push_back(30.0 / 1.001);
435
frameRates.push_back(30);
436
frameRates.push_back(120.0 / 1.001);
437
frameRates.push_back(120);
439
// List of rates found
440
std::vector<double> found;
442
// Find the relative fps of each area
443
for (unsigned int i=1;i<Frame.size();i++) {
444
// Find the current frame distance
445
curDist = Frame[i]-Frame[i-1];
447
// See if it's close enough to the last
448
if ((abs(curDist - lastDist) < 2 || i-1 == (unsigned) sectionStart) && i != Frame.size()-1) {
453
// Calculate section fps
454
curFps = (i - sectionStart - 1) * 1000.0 / double(Frame[i-1]-Frame[sectionStart]);
458
// See if it's close enough to one of the likely rates
459
for (unsigned int j=0;j<frameRates.size();j++) {
460
if (curFps-0.01 <= frameRates[j] && curFps+0.01 >= frameRates[j]) {
461
curFps = frameRates[j];
466
// See if it's on list
468
for (unsigned int j=0;j<found.size();j++) {
469
if (found[j] == curFps) {
476
if (!onList) found.push_back(curFps);
479
// Find common between them
480
double v1,v2,minInt,tempd;
482
while (found.size() > 1) {
483
// Extract last two values
492
// Find what it takes to make it an integer
493
for (minInt = 1;minInt<20;minInt++) {
495
tempi1 = (int)(tempd-0.001);
496
tempi2 = (int)(tempd+0.001);
497
if (tempi1 != tempi2) break;
499
if (minInt != 20) v1 = v1*minInt;
501
// See if it's close enough to one of the likely rates
502
for (unsigned int j=0;j<frameRates.size();j++) {
503
if (v1-0.01 <= frameRates[j] && v1+0.01 >= frameRates[j]) {
509
// Re-insert obtained result
519
FrameRate VFR_Output;