summaryrefslogtreecommitdiffstats
path: root/src/plugins/multimedia/ffmpeg/playbackengine/qffmpegdemuxer.cpp
blob: fba48f3dafa0958a519c0cbb5a2330e31ad77efa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "playbackengine/qffmpegdemuxer_p.h"
#include <qloggingcategory.h>

QT_BEGIN_NAMESPACE

// 4 sec for buffering. TODO: maybe move to env var customization
static constexpr qint64 MaxBufferingTimeUs = 4'000'000;

// around 4 sec of hdr video
static constexpr qint64 MaxBufferingSize = 32 * 1024 * 1024;

namespace QFFmpeg {

static Q_LOGGING_CATEGORY(qLcDemuxer, "qt.multimedia.ffmpeg.demuxer");

static qint64 streamTimeToUs(const AVStream *stream, qint64 time)
{
    Q_ASSERT(stream);

    const auto res = mul(time * 1000000, stream->time_base);
    return res ? *res : time;
}

static auto isStreamLimitReached = [](const auto &streamIndexToData) {
    return streamIndexToData.second.bufferingTime >= MaxBufferingTimeUs
            || streamIndexToData.second.bufferingSize >= MaxBufferingSize;
};

Demuxer::Demuxer(AVFormatContext *context, const PositionWithOffset &posWithOffset,
                 const StreamIndexes &streamIndexes, int loops)
    : m_context(context), m_posWithOffset(posWithOffset), m_loops(loops)
{
    qCDebug(qLcDemuxer) << "Create demuxer."
                        << "pos:" << posWithOffset.pos << "loop offset:" << posWithOffset.offset.pos
                        << "loop index:" << posWithOffset.offset.index << "loops:" << loops;

    Q_ASSERT(m_context);
    Q_ASSERT(loops < 0 || m_posWithOffset.offset.index < loops);

    for (auto i = 0; i < QPlatformMediaPlayer::NTrackTypes; ++i) {
        if (streamIndexes[i] >= 0) {
            const auto trackType = static_cast<QPlatformMediaPlayer::TrackType>(i);
            qCDebug(qLcDemuxer) << "Activate demuxing stream" << i << ", trackType:" << trackType;
            m_streams[streamIndexes[i]] = { trackType };
        }
    }
}

void Demuxer::doNextStep()
{
    ensureSeeked();

    Packet packet(m_posWithOffset.offset, AVPacketUPtr{ av_packet_alloc() }, id());
    if (av_read_frame(m_context, packet.avPacket()) < 0) {
        ++m_posWithOffset.offset.index;

        const auto loops = m_loops.loadAcquire();
        if (loops >= 0 && m_posWithOffset.offset.index >= loops) {
            qCDebug(qLcDemuxer) << "finish demuxing";

            if (!std::exchange(m_buffered, true))
                emit packetsBuffered();

            setAtEnd(true);
        } else {
            m_seeked = false;
            m_posWithOffset.pos = 0;
            m_posWithOffset.offset.pos = m_endPts;
            m_endPts = 0;

            ensureSeeked();

            qCDebug(qLcDemuxer) << "Demuxer loops changed. Index:" << m_posWithOffset.offset.index
                                << "Offset:" << m_posWithOffset.offset.pos;

            scheduleNextStep(false);
        }

        return;
    }

    auto &avPacket = *packet.avPacket();

    const auto streamIndex = avPacket.stream_index;
    const auto stream = m_context->streams[streamIndex];

    auto it = m_streams.find(streamIndex);

    if (it != m_streams.end()) {
        const auto packetEndPos = streamTimeToUs(stream, avPacket.pts + avPacket.duration);
        m_endPts = std::max(m_endPts, m_posWithOffset.offset.pos + packetEndPos);

        it->second.bufferingTime += streamTimeToUs(stream, avPacket.duration);
        it->second.bufferingSize += avPacket.size;

        if (!m_buffered && isStreamLimitReached(*it)) {
            m_buffered = true;
            emit packetsBuffered();
        }

        if (!m_firstPacketFound) {
            m_firstPacketFound = true;
            const auto pos = streamTimeToUs(stream, avPacket.pts);
            emit firstPacketFound(std::chrono::steady_clock::now(), pos);
        }

        auto signal = signalByTrackType(it->second.trackType);
        emit (this->*signal)(packet);
    }

    scheduleNextStep(false);
}

void Demuxer::onPacketProcessed(Packet packet)
{
    Q_ASSERT(packet.isValid());

    if (packet.sourceId() != id())
        return;

    auto &avPacket = *packet.avPacket();

    const auto streamIndex = avPacket.stream_index;
    auto it = m_streams.find(streamIndex);

    if (it != m_streams.end()) {
        it->second.bufferingTime -= streamTimeToUs(m_context->streams[streamIndex], avPacket.duration);
        it->second.bufferingSize -= avPacket.size;

        Q_ASSERT(it->second.bufferingTime >= 0);
        Q_ASSERT(it->second.bufferingSize >= 0);
    }

    scheduleNextStep();
}

bool Demuxer::canDoNextStep() const
{
    return PlaybackEngineObject::canDoNextStep() && !isAtEnd() && !m_streams.empty()
            && std::none_of(m_streams.begin(), m_streams.end(), isStreamLimitReached);
}

void Demuxer::ensureSeeked()
{
    if (std::exchange(m_seeked, true))
        return;

    if ((m_context->ctx_flags & AVFMTCTX_UNSEEKABLE) == 0) {
        const qint64 seekPos = m_posWithOffset.pos * AV_TIME_BASE / 1000000;
        auto err = av_seek_frame(m_context, -1, seekPos, AVSEEK_FLAG_BACKWARD);

        if (err < 0) {
            qCWarning(qLcDemuxer) << "Failed to seek, pos" << seekPos;

            // Drop an error of seeking to initial position of streams with undefined duration.
            // This needs improvements.
            if (seekPos != 0 || m_context->duration > 0)
                emit error(QMediaPlayer::ResourceError,
                           QLatin1StringView("Failed to seek: ") + err2str(err));
        }
    }

    setAtEnd(false);
}

Demuxer::RequestingSignal Demuxer::signalByTrackType(QPlatformMediaPlayer::TrackType trackType)
{
    switch (trackType) {
    case QPlatformMediaPlayer::TrackType::VideoStream:
        return &Demuxer::requestProcessVideoPacket;
    case QPlatformMediaPlayer::TrackType::AudioStream:
        return &Demuxer::requestProcessAudioPacket;
    case QPlatformMediaPlayer::TrackType::SubtitleStream:
        return &Demuxer::requestProcessSubtitlePacket;
    default:
        Q_ASSERT(!"Unknown track type");
    }

    return nullptr;
}

void Demuxer::setLoops(int loopsCount)
{
    qCDebug(qLcDemuxer) << "setLoops to demuxer" << loopsCount;
    m_loops.storeRelease(loopsCount);
}

} // namespace QFFmpeg

QT_END_NAMESPACE

#include "moc_qffmpegdemuxer_p.cpp"