File indexing completed on 2024-06-16 04:38:28

0001 /*
0002     SPDX-FileCopyrightText: 2003 Fabrice Bellard
0003     SPDX-FileCopyrightText: 2020-2022 Mladen Milinkovic <max@smoothware.net>
0004 
0005     SPDX-License-Identifier: GPL-2.0-or-later
0006 */
0007 
0008 #include "clock.h"
0009 
0010 #include <cmath>
0011 
0012 extern "C" {
0013 #include "libavutil/time.h"
0014 #include "libavutil/avutil.h"
0015 }
0016 
0017 #include "videoplayer/backend/packetqueue.h"
0018 
0019 using namespace SubtitleComposer;
0020 
0021 Clock::Clock()
0022     : m_pts(0.),
0023       m_ptsDrift(0.),
0024       m_lastUpdated(0.),
0025       m_speed(0.),
0026       m_serial(0),
0027       m_paused(false),
0028       m_queueSerial(nullptr)
0029 {
0030 
0031 }
0032 
0033 double
0034 Clock::get() const
0035 {
0036     if(*m_queueSerial != m_serial)
0037         return NAN;
0038     if(m_paused) {
0039         return m_pts;
0040     } else {
0041         double time = av_gettime_relative() / double(AV_TIME_BASE);
0042         return m_ptsDrift + time - (time - m_lastUpdated) * (1.0 - m_speed);
0043     }
0044 }
0045 
0046 void
0047 Clock::setAt(double pts, int serial, double time)
0048 {
0049     m_pts = pts;
0050     m_lastUpdated = time;
0051     m_ptsDrift = m_pts - time;
0052     m_serial = serial;
0053 }
0054 
0055 void
0056 Clock::set(double pts, int serial)
0057 {
0058     double time = av_gettime_relative() / double(AV_TIME_BASE);
0059     setAt(pts, serial, time);
0060 }
0061 
0062 void
0063 Clock::setSpeed(double speed)
0064 {
0065     set(get(), m_serial);
0066     m_speed = speed;
0067 }
0068 
0069 void
0070 Clock::init(const PacketQueue *queue)
0071 {
0072     m_speed = 1.0;
0073     m_paused = 0;
0074     m_queueSerial = queue == nullptr ? &m_serial : &queue->m_serial;
0075     set(NAN, -1);
0076 }
0077 
0078 void
0079 Clock::syncTo(Clock *other)
0080 {
0081     double clock = get();
0082     double otherClock = other->get();
0083     if(!std::isnan(otherClock) && (std::isnan(clock) || fabs(clock - otherClock) > AV_NOSYNC_THRESHOLD))
0084         set(otherClock, other->m_serial);
0085 }