audio_play_thread.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. // ***********************************************************/
  2. // audio_play_thread.cpp
  3. //
  4. // Copy Right @ Steven Huang. All rights reserved.
  5. //
  6. // audio play thread
  7. // ***********************************************************/
  8. #include "audio_play_thread.h"
  9. #include <utility>
  10. #if !NDEBUG
  11. #define DEBUG_PLAYFILTER 0
  12. #define WRITE_AUDIO_FILE 0
  13. #else
  14. #define DEBUG_PLAYFILTER 0
  15. #define WRITE_AUDIO_FILE 0
  16. #endif
  17. #if WRITE_AUDIO_FILE
  18. #include <fstream>
  19. #endif
  20. AudioPlayThread::AudioPlayThread(QObject* parent, VideoState* pState)
  21. : QThread(parent)
  22. , m_pOutput(nullptr)
  23. , m_pState(pState)
  24. {
  25. // print_device();
  26. qRegisterMetaType<AudioData>("AudioData");
  27. }
  28. AudioPlayThread::~AudioPlayThread()
  29. {
  30. stop_device();
  31. final_resample_param();
  32. }
  33. void AudioPlayThread::print_device() const
  34. {
  35. QAudioDeviceInfo deviceInfo = QAudioDeviceInfo::defaultOutputDevice();
  36. auto deviceInfos = QAudioDeviceInfo::availableDevices(QAudio::AudioInput);
  37. for (const QAudioDeviceInfo& deviceInfo : std::as_const(deviceInfos))
  38. qDebug() << "Input device name: " << deviceInfo.deviceName();
  39. deviceInfos = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput);
  40. for (const QAudioDeviceInfo& deviceInfo : std::as_const(deviceInfos))
  41. qDebug() << "Output device name: " << deviceInfo.deviceName();
  42. const auto edians = deviceInfo.supportedByteOrders();
  43. for (const QAudioFormat::Endian& endian : edians)
  44. qDebug() << "Endian: " << endian;
  45. const auto sampleTypes = deviceInfo.supportedSampleTypes();
  46. for (const QAudioFormat::SampleType& sampleType : sampleTypes)
  47. qDebug() << "sampleType: " << sampleType;
  48. const auto codecs = deviceInfo.supportedCodecs();
  49. for (const QString& codec : codecs)
  50. qDebug() << "codec: " << codec;
  51. const auto sampleRates = deviceInfo.supportedSampleRates();
  52. for (const int& sampleRate : sampleRates)
  53. qDebug() << "sampleRate: " << sampleRate;
  54. const auto ChannelCounts = deviceInfo.supportedChannelCounts();
  55. for (const int& channelCount : ChannelCounts)
  56. qDebug() << "channelCount: " << channelCount;
  57. const auto sampleSizes = deviceInfo.supportedSampleSizes();
  58. for (const int& sampleSize : sampleSizes)
  59. qDebug() << "sampleSize: " << sampleSize;
  60. }
  61. bool AudioPlayThread::init_device(int sample_rate,
  62. int channel,
  63. AVSampleFormat sample_fmt,
  64. float default_vol)
  65. {
  66. QAudioDeviceInfo deviceInfo = QAudioDeviceInfo::defaultOutputDevice();
  67. QAudioFormat format;
  68. format.setSampleRate(sample_rate);
  69. format.setChannelCount(channel);
  70. format.setSampleSize(8 * av_get_bytes_per_sample(sample_fmt));
  71. format.setCodec("audio/pcm");
  72. format.setByteOrder(QAudioFormat::LittleEndian);
  73. format.setSampleType(QAudioFormat::SignedInt);
  74. // qDebug("sample size=%d\n", 8 * av_get_bytes_per_sample(sample_fmt));
  75. if (!deviceInfo.isFormatSupported(format)) {
  76. qWarning() << "Raw audio format not supported!";
  77. return false;
  78. }
  79. // m_pOutput = std::make_unique<QAudioOutput>(deviceInfo, format);
  80. m_pOutput = new QAudioOutput(deviceInfo, format, this); // this 为 parent
  81. // 析构时 Qt 自动 delete
  82. set_device_volume(default_vol);
  83. m_audioDevice = m_pOutput->start();
  84. return true;
  85. }
  86. float AudioPlayThread::get_device_volume() const
  87. {
  88. if (m_pOutput)
  89. return m_pOutput->volume();
  90. return 0;
  91. }
  92. void AudioPlayThread::set_device_volume(float volume)
  93. {
  94. if (m_pOutput)
  95. m_pOutput->setVolume(volume);
  96. }
  97. void AudioPlayThread::stop_device()
  98. {
  99. if (m_pOutput) {
  100. m_pOutput->stop();
  101. m_pOutput->reset();
  102. }
  103. }
  104. void AudioPlayThread::play_file(const QString& file)
  105. {
  106. /*play pcm file directly*/
  107. QFile audioFile;
  108. audioFile.setFileName(file);
  109. audioFile.open(QIODevice::ReadOnly);
  110. m_pOutput->start(&audioFile);
  111. }
  112. void AudioPlayThread::play_buf(const uint8_t* buf, int datasize)
  113. {
  114. if (!m_audioDevice)
  115. return;
  116. uint8_t* data = (uint8_t*) buf;
  117. while (datasize > 0) {
  118. qint64 len = m_audioDevice->write((const char*) data, datasize);
  119. if (len < 0)
  120. break;
  121. if (len > 0) {
  122. data = data + len;
  123. datasize -= len;
  124. }
  125. // qDebug("play buf:reslen:%d, write len:%d", len, datasize);
  126. }
  127. }
  128. void AudioPlayThread::run()
  129. {
  130. assert(m_pState);
  131. VideoState* is = m_pState;
  132. int audio_size;
  133. for (;;) {
  134. if (m_bExitThread)
  135. break;
  136. if (is->abort_request)
  137. break;
  138. if (is->paused) {
  139. msleep(10);
  140. continue;
  141. }
  142. audio_size = audio_decode_frame(is);
  143. if (audio_size < 0)
  144. break;
  145. if (!isnan(is->audio_clock)) {
  146. AVCodecContext* pAudioCodex = is->auddec.avctx;
  147. if (pAudioCodex) {
  148. int bytes_per_sec = av_samples_get_buffer_size(nullptr,
  149. pAudioCodex->ch_layout.nb_channels,
  150. pAudioCodex->sample_rate,
  151. AV_SAMPLE_FMT_S16,
  152. 1);
  153. int64_t audio_callback_time = av_gettime_relative();
  154. set_clock_at(&is->audclk,
  155. is->audio_clock - (double) (audio_size) / bytes_per_sec,
  156. is->audio_clock_serial,
  157. audio_callback_time / 1000000.0);
  158. sync_clock_to_slave(&is->extclk, &is->audclk);
  159. }
  160. }
  161. }
  162. qDebug("-------- Audio play thread exit.");
  163. }
  164. int AudioPlayThread::audio_decode_frame(VideoState* is)
  165. {
  166. int data_size;
  167. Frame* af;
  168. do {
  169. while (frame_queue_nb_remaining(&is->sampq) == 0) {
  170. if (is->eof) {
  171. // break;
  172. return -1;
  173. } else {
  174. av_usleep(1000);
  175. // return -1;
  176. }
  177. if (is->abort_request)
  178. break;
  179. }
  180. if (!(af = frame_queue_peek_readable(&is->sampq)))
  181. return -1;
  182. frame_queue_next(&is->sampq);
  183. } while (af->serial != is->audioq.serial);
  184. /*data_size = av_samples_get_buffer_size(nullptr, af->frame->channels,
  185. af->frame->nb_samples,
  186. AVSampleFormat(af->frame->format), 1);*/
  187. #if USE_AVFILTER_AUDIO
  188. data_size = av_samples_get_buffer_size(nullptr,
  189. af->frame->ch_layout.nb_channels,
  190. af->frame->nb_samples,
  191. AV_SAMPLE_FMT_S16,
  192. 1);
  193. uint8_t* const buffer_audio = (uint8_t*) av_malloc(data_size * sizeof(uint8_t));
  194. memcpy(buffer_audio, af->frame->data[0], data_size);
  195. #else
  196. struct SwrContext* swrCtx = m_audioResample.swrCtx;
  197. data_size = av_samples_get_buffer_size(nullptr,
  198. af->frame->channels,
  199. af->frame->nb_samples,
  200. AV_SAMPLE_FMT_S16,
  201. 0); // AVSampleFormat(af->frame->format)
  202. uint8_t* buffer_audio = (uint8_t*) av_malloc(data_size * sizeof(uint8_t));
  203. int ret = swr_convert(swrCtx,
  204. &buffer_audio,
  205. af->frame->nb_samples,
  206. (const uint8_t**) (af->frame->data),
  207. af->frame->nb_samples);
  208. if (ret < 0) {
  209. return 0;
  210. }
  211. #endif
  212. if (is->muted && data_size > 0)
  213. memset(buffer_audio, 0, data_size); // mute
  214. #if WRITE_AUDIO_FILE
  215. std::ofstream myfile;
  216. myfile.open("audio.pcm", std::ios::out | std::ios::app | std::ios::binary);
  217. if (myfile.is_open()) {
  218. myfile.write((char*) buffer_audio, data_size);
  219. }
  220. #endif
  221. if (m_bSendToVisual) {
  222. AudioData data;
  223. if (data_size > BUFFER_LEN) {
  224. qDebug() << "audio frame is too long,data_size:" << data_size
  225. << ", buffer_len:" << BUFFER_LEN << "\n";
  226. }
  227. int len = std::min(data_size, BUFFER_LEN);
  228. memcpy(data.buffer, buffer_audio, len);
  229. data.len = len;
  230. emit data_visual_ready(data);
  231. }
  232. play_buf(buffer_audio, data_size);
  233. av_free((void*) buffer_audio);
  234. /* update the audio clock with the pts */
  235. if (!isnan(af->pts)) {
  236. // is->audio_clock = af->pts + (double)af->frame->nb_samples /
  237. // af->frame->sample_rate;
  238. double frame = (double) af->frame->nb_samples / af->frame->sample_rate;
  239. // frame = frame * is->audio_speed;
  240. is->audio_clock = af->pts + frame;
  241. #if USE_AVFILTER_AUDIO
  242. is->audio_clock = is->audio_clock_old
  243. + (is->audio_clock - is->audio_clock_old) * is->audio_speed;
  244. // is->audio_clock = is->audio_clock * is->audio_speed;
  245. #endif
  246. #if DEBUG_PLAYFILTER
  247. static int pks_num = 0;
  248. pks_num++;
  249. qDebug("[%d]audio: clock=%0.3f pts=%0.3f, (nb:%d, sr:%d)frame:%0.3f\n",
  250. pks_num,
  251. is->audio_clock,
  252. af->pts,
  253. af->frame->nb_samples,
  254. af->frame->sample_rate,
  255. frame);
  256. // qDebug("audio: clock=%0.3f pts=%0.3f, (nb:%d, sr:%d)frame:%0.3f\n",
  257. // is->audio_clock, af->pts, af->frame->nb_samples, af->frame->sample_rate,
  258. // frame);
  259. #endif
  260. } else {
  261. is->audio_clock = NAN;
  262. }
  263. is->audio_clock_serial = af->serial;
  264. emit update_play_time();
  265. #if (!NDEBUG && PRINT_PACKETQUEUE_AUDIO_INFO)
  266. {
  267. static double last_clock;
  268. qDebug("audio: delay=%0.3f clock=%0.3f\n", is->audio_clock - last_clock, is->audio_clock);
  269. last_clock = is->audio_clock;
  270. }
  271. #endif
  272. return data_size;
  273. }
  274. bool AudioPlayThread::init_resample_param(AVCodecContext* pAudio,
  275. AVSampleFormat sample_fmt,
  276. VideoState* is)
  277. {
  278. if (pAudio) {
  279. int ret = -1;
  280. struct SwrContext* swrCtx = nullptr;
  281. #if USE_AVFILTER_AUDIO
  282. if (is) {
  283. AVFilterContext* sink = is->out_audio_filter;
  284. // int sample_rate = av_buffersink_get_sample_rate(sink);
  285. // int nb_channels = av_buffersink_get_channels(sink);
  286. AVChannelLayout channel_layout;
  287. av_buffersink_get_ch_layout(sink, &channel_layout);
  288. // int64_t channel_layout = av_buffersink_get_channel_layout(sink);
  289. int format = av_buffersink_get_format(sink);
  290. ret = swr_alloc_set_opts2(&swrCtx,
  291. &pAudio->ch_layout,
  292. sample_fmt,
  293. pAudio->sample_rate,
  294. &channel_layout,
  295. (AVSampleFormat) format,
  296. pAudio->sample_rate,
  297. 0,
  298. nullptr);
  299. /*m_audioResample.channel_layout = channel_layout;
  300. m_audioResample.sample_fmt = sample_fmt;
  301. m_audioResample.sample_rate = pAudio->sample_rate;*/
  302. }
  303. #else
  304. ret = swr_alloc_set_opts2(&swrCtx,
  305. &pAudio->ch_layout,
  306. sample_fmt,
  307. pAudio->sample_rate,
  308. &pAudio->ch_layout,
  309. pAudio->sample_fmt,
  310. pAudio->sample_rate,
  311. 0,
  312. nullptr);
  313. #endif
  314. if (!(ret < 0)) {
  315. swr_init(swrCtx);
  316. m_audioResample.swrCtx = swrCtx;
  317. return true;
  318. }
  319. }
  320. return false;
  321. }
  322. void AudioPlayThread::final_resample_param()
  323. {
  324. swr_free(&m_audioResample.swrCtx);
  325. }
  326. void AudioPlayThread::stop_thread()
  327. {
  328. m_bExitThread = true;
  329. // 如有条件变量/阻塞等待,这里唤醒
  330. }