forked from wang-bin/QtAV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AudioThread.cpp
310 lines (297 loc) · 12.3 KB
/
AudioThread.cpp
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/******************************************************************************
QtAV: Media play library based on Qt and FFmpeg
Copyright (C) 2012-2016 Wang Bin <[email protected]>
* This file is part of QtAV
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
#include "AudioThread.h"
#include "AVThread_p.h"
#include "QtAV/AudioDecoder.h"
#include "QtAV/Packet.h"
#include "QtAV/AudioFormat.h"
#include "QtAV/AudioOutput.h"
#include "QtAV/AudioResampler.h"
#include "QtAV/AVClock.h"
#include "QtAV/Filter.h"
#include "output/OutputSet.h"
#include "QtAV/private/AVCompat.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDateTime>
#include "utils/Logger.h"
namespace QtAV {
class AudioThreadPrivate : public AVThreadPrivate
{
public:
void init() {
resample = false;
last_pts = 0;
}
bool resample;
qreal last_pts; //used when audio output is not available, to calculate the aproximate sleeping time
};
AudioThread::AudioThread(QObject *parent)
:AVThread(*new AudioThreadPrivate(), parent)
{
}
void AudioThread::applyFilters(AudioFrame &frame)
{
DPTR_D(AudioThread);
//QMutexLocker locker(&d.mutex);
//Q_UNUSED(locker);
if (!d.filters.isEmpty()) {
//sort filters by format. vo->defaultFormat() is the last
foreach (Filter *filter, d.filters) {
AudioFilter *af = static_cast<AudioFilter*>(filter);
if (!af->isEnabled())
continue;
af->apply(d.statistics, &frame);
}
}
}
/*
*TODO:
* if output is null or dummy, the use duration to wait
*/
void AudioThread::run()
{
DPTR_D(AudioThread);
//No decoder or output. No audio output is ok, just display picture
if (!d.dec || !d.dec->isAvailable() || !d.outputSet)
return;
resetState();
Q_ASSERT(d.clock != 0);
d.init();
//TODO: bool need_sync in private class
Packet pkt;
while (true) {
processNextTask();
//TODO: why put it at the end of loop then playNextFrame() not work?
if (tryPause()) { //DO NOT continue, or playNextFrame() will fail
if (d.stop)
break; //the queue is empty and may block. should setBlocking(false) wake up cond empty?
} else {
if (isPaused())
continue;
}
if (!pkt.isValid() && !pkt.isEOF()) { // can't seek back if eof packet is read
pkt = d.packets.take(); //wait to dequeue
}
if (pkt.isEOF()) {
qDebug("audio thread gets an eof packet.");
} else {
if (d.stop) // user stop
break;
if (!pkt.isValid()) {
qDebug("Invalid packet! flush audio codec context!!!!!!!! audio queue size=%d", d.packets.size());
QMutexLocker locker(&d.mutex);
Q_UNUSED(locker);
if (d.dec) //maybe set to null in setDecoder()
d.dec->flush();
d.render_pts0 = pkt.pts;
pkt = Packet(); //mark invalid to take next
continue;
}
}
qreal dts = pkt.dts; //FIXME: pts and dts
// no key frame for audio. so if pts reaches, try decode and skip render if got frame pts does not reach
bool skip_render = pkt.pts < d.render_pts0;
// audio has no key frame, skip rendering equals to skip decoding
if (skip_render) {
d.clock->updateValue(pkt.pts);
/*
* audio may be too fast than video if skip without sleep
* a frame is about 20ms. sleep time must be << frame time
*/
qreal a_v = dts - d.clock->videoTime();
//qDebug("skip audio decode at %f/%f v=%f a-v=%fms", dts, d.render_pts0, d.clock->videoTime(), a_v*1000.0);
if (a_v > 0) {
msleep(qMin((ulong)20, ulong(a_v*1000.0)));
} else {
// audio maybe too late compared with video packet before seeking backword. so just ignore
msleep(0); //wait video seek done if audio done early
}
pkt = Packet(); //mark invalid to take next
continue;
}
const bool is_external_clock = d.clock->clockType() == AVClock::ExternalClock;
if (is_external_clock) {
d.delay = dts - d.clock->value();
/*
*after seeking forward, a packet may be the old, v packet may be
*the new packet, then the d.delay is very large, omit it.
*TODO: 1. how to choose the value
* 2. use last delay when seeking
*/
if (qAbs(d.delay) < 2.0) {
if (d.delay < -kSyncThreshold) { //Speed up. drop frame? resample?
qDebug("audio is late compared with external clock. skip decoding. %.3f-%.3f=%.3f", dts, d.clock->value(), d.delay);
pkt = Packet(); //mark invalid to take next
continue;
}
if (d.delay > 0)
waitAndCheck(d.delay, dts);
} else { //when to drop off?
if (d.delay > 0) {
msleep(64);
} else {
//audio packet not cleaned up?
qDebug("audio is too late compared with external clock. skip decoding. %.3f-%.3f=%.3f", dts, d.clock->value(), d.delay);
pkt = Packet(); //mark invalid to take next
continue;
}
}
}
/* lock here to ensure decoder and ao can complete current work before they are changed
* current packet maybe not supported by new decoder
*/
// TODO: smaller scope
QMutexLocker locker(&d.mutex);
Q_UNUSED(locker);
AudioDecoder *dec = static_cast<AudioDecoder*>(d.dec);
if (!dec) {
pkt = Packet(); //mark invalid to take next
continue;
}
AudioOutput *ao = 0;
// first() is not null even if list empty
if (!d.outputSet->outputs().isEmpty())
ao = static_cast<AudioOutput*>(d.outputSet->outputs().first());
//DO NOT decode and convert if ao is not available or mute!
bool has_ao = ao && ao->isAvailable();
//if (!has_ao) {//do not decode?
// TODO: move resampler to AudioFrame, like VideoFrame does
if (has_ao && dec->resampler()) {
if (dec->resampler()->speed() != ao->speed()
|| dec->resampler()->outAudioFormat() != ao->audioFormat()) {
//resample later to ensure thread safe. TODO: test
if (d.resample) {
qDebug() << "ao.format " << ao->audioFormat();
qDebug() << "swr.format " << dec->resampler()->outAudioFormat();
qDebug("decoder set speed: %.2f", ao->speed());
dec->resampler()->setOutAudioFormat(ao->audioFormat());
dec->resampler()->setSpeed(ao->speed());
dec->resampler()->prepare();
d.resample = false;
} else {
d.resample = true;
}
}
} else {
if (dec->resampler() && dec->resampler()->speed() != d.clock->speed()) {
if (d.resample) {
qDebug("decoder set speed: %.2f", d.clock->speed());
dec->resampler()->setSpeed(d.clock->speed());
dec->resampler()->prepare();
d.resample = false;
} else {
d.resample = true;
}
}
}
if (d.stop) {
qDebug("audio thread stop before decode()");
break;
}
if (!dec->decode(pkt)) {
qWarning("Decode audio failed. undecoded: %d", dec->undecodedSize());
if (pkt.isEOF()) {
qDebug("audio decode eof done");
if (!pkt.position)
break;
}
qreal dt = dts - d.last_pts;
if (dt > 0.5 || dt < 0) {
dt = 0;
}
if (!qFuzzyIsNull(dt)) {
msleep((unsigned long)(dt*1000.0));
}
pkt = Packet();
d.last_pts = d.clock->value(); //not pkt.pts! the delay is updated!
continue;
}
// reduce here to ensure to decode the rest data in the next loop
if (!pkt.isEOF())
pkt.data = QByteArray::fromRawData(pkt.data.constData() pkt.data.size() - dec->undecodedSize(), dec->undecodedSize());
#if USE_AUDIO_FRAME
AudioFrame frame(dec->frame());
if (!frame)
continue; //pkt data is updated after decode, no reset here
if (frame.timestamp() <= 0)
frame.setTimestamp(pkt.pts); // pkt.pts is wrong. >= real timestamp
if (d.render_pts0 >= 0.0) { // seeking
if (frame.timestamp() < d.render_pts0) {
qDebug("skip audio rendering: %f-%f", frame.timestamp(), d.render_pts0);
d.clock->updateValue(frame.timestamp());
continue; //pkt data is updated after decode, no reset here
}
qDebug("seek audio done @%.3f", frame.timestamp());
d.render_pts0 = -1.0;
Q_EMIT seekFinished(qint64(frame.timestamp()*1000.0));
}
if (has_ao) {
applyFilters(frame);
frame.setAudioResampler(dec->resampler()); //!!!
// FIXME: resample ONCE is required for audio frames from ffmpeg
//if (ao->audioFormat() != frame.format()) {
frame = frame.to(ao->audioFormat());
//}
}
QByteArray decoded(frame.data());
#else
QByteArray decoded(dec->data());
#endif
int decodedSize = decoded.size();
int decodedPos = 0;
qreal delay = 0;
//AudioFormat.durationForBytes() calculates int type internally. not accurate
const AudioFormat &af = dec->resampler()->outAudioFormat();
const qreal byte_rate = af.bytesPerSecond();
while (decodedSize > 0) {
if (d.stop) {
qDebug("audio thread stop after decode()");
break;
}
// TODO: set to format.bytesPerFrame()*1024?
const int chunk = qMin(decodedSize, has_ao ? ao->bufferSize() : 1024*4);//int(max_len*byte_rate));
//AudioFormat.bytesForDuration
const qreal chunk_delay = (qreal)chunk/(qreal)byte_rate;
pkt.pts = chunk_delay;
pkt.dts = chunk_delay;
if (has_ao && ao->isOpen()) {
QByteArray decodedChunk = QByteArray::fromRawData(decoded.constData() decodedPos, chunk);
ao->play(decodedChunk, pkt.pts);
//qDebug("ao.timestamp: %.3f", ao->timestamp());
if (!is_external_clock)
d.clock->updateValue(ao->timestamp());
} else {
d.clock->updateDelay(delay = chunk_delay);
/*
* why need this even if we add delay? and usleep sounds weird
* the advantage is if no audio device, the play speed is ok too
* So is portaudio blocking the thread when playing?
*/
//TODO: avoid acummulative error. External clock?
msleep((unsigned long)(chunk_delay * 1000.0));
}
decodedPos = chunk;
decodedSize -= chunk;
}
if (has_ao)
emit frameDelivered();
d.last_pts = d.clock->value(); //not pkt.pts! the delay is updated!
}
d.packets.clear();
qDebug("Audio thread stops running...");
}
} //namespace QtAV