da9973cc0904e80e26fec463da6dd8a28aad23dd
[libsub.git] / src / frame_time.cc
1 /*
2     Copyright (C) 2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "frame_time.h"
21 #include "compose.hpp"
22 #include <iostream>
23
24 using std::ostream;
25 using std::string;
26 using namespace sub;
27
28 bool
29 sub::operator== (FrameTime const & a, FrameTime const & b)
30 {
31         return a.hours() == b.hours() && a.minutes() == b.minutes() && a.seconds() == b.seconds() && a.frames() == b.frames();
32 }
33
34 bool
35 sub::operator< (FrameTime const & a, FrameTime const & b)
36 {
37         if (a.hours() != b.hours()) {
38                 return a.hours() < b.hours();
39         }
40
41         if (a.minutes() != b.minutes()) {
42                 return a.minutes() < b.minutes();
43         }
44
45         if (a.seconds() != b.seconds()) {
46                 return a.seconds() < b.seconds();
47         }
48
49         return a.frames() < b.frames();
50 }
51
52 ostream&
53 sub::operator<< (ostream& s, FrameTime const & t)
54 {
55         s << t.hours() << ":" << t.minutes() << ":" << t.seconds() << ":" << t.frames();
56         return s;
57 }
58
59 string
60 FrameTime::timecode () const
61 {
62         return String::compose ("%1:%2:%3:%4", _hours, _minutes, _seconds, _frames);
63 }
64
65 FrameTime::FrameTime (int64_t f, float fps)
66 {
67         _hours = f / (60 * 60 * fps);
68         f -= _hours * 60 * 60 * fps;
69         _minutes = f / (60 * fps);
70         f -= _minutes * 60 * fps;
71         _seconds = f / fps;
72         f -= _seconds * fps;
73         _frames = int (f);
74 }
75
76 void
77 FrameTime::add (FrameTime t, float fps)
78 {
79         _frames += t.frames ();
80         if (_frames > fps) {
81                 _frames -= fps;
82                 _seconds++;
83         }
84
85         _seconds += t.seconds ();
86         if (_seconds >= 60) {
87                 _seconds -= 60;
88                 ++_minutes;
89         }
90
91         _minutes += t.minutes ();
92         if (_minutes >= 60) {
93                 _minutes -= 60;
94                 ++_hours;
95         }
96
97         _hours += t.hours ();
98 }