audio_play_thread.cpp 11 KB

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