video_play_thread.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. // ***********************************************************/
  2. // video_play_thread.cpp
  3. //
  4. // Copy Right @ Steven Huang. All rights reserved.
  5. //
  6. // Video play thread. This section includes key code for
  7. // synchronizing video frames and audio using pts/dts,
  8. // as well as subtitle processing.
  9. // ***********************************************************/
  10. #include "video_play_thread.h"
  11. #include "AVPlayer2/playercontroller.h"
  12. extern int framedrop;
  13. const QRegularExpression VideoPlayThread::m_assFilter = QRegularExpression("{\\\\.*?}");
  14. const QRegularExpression VideoPlayThread::m_assNewLineReplacer = QRegularExpression("\\\\n|\\\\N");
  15. Q_DECLARE_METATYPE(AVFrame*)
  16. VideoPlayThread::VideoPlayThread(VideoState* pState)
  17. : m_pState(pState)
  18. {
  19. qRegisterMetaType<AVFrame*>();
  20. }
  21. VideoPlayThread::~VideoPlayThread()
  22. {
  23. final_resample_param();
  24. }
  25. void VideoPlayThread::stop()
  26. {
  27. *m_exit = true;
  28. m_cv.notify_all();
  29. }
  30. void VideoPlayThread::run()
  31. {
  32. qCDebug(playerControllerLog) << "[VideoPlayThread] run start, m_pState:" << (void*)m_pState;
  33. assert(m_pState);
  34. VideoState* is = m_pState;
  35. qCDebug(playerControllerLog) << "[VideoPlayThread] VideoState* is:" << (void*)is << ", abort_request:" << is->abort_request;
  36. double remaining_time = 0.0;
  37. int loop_count = 0;
  38. for (;;) {
  39. if (m_exit) {
  40. qCDebug(playerControllerLog) << "[VideoPlayThread] m_exit set, exit.";
  41. break;
  42. }
  43. if (is->abort_request) {
  44. qCDebug(playerControllerLog) << "[VideoPlayThread] abort_request set, exit.";
  45. break;
  46. }
  47. if (is->paused) {
  48. qCDebug(playerControllerLog) << "[VideoPlayThread] paused, wait.";
  49. std::unique_lock<std::mutex> lock(m_mutex);
  50. m_cv.wait_for(lock, std::chrono::milliseconds(10), [this] { return m_exit && *m_exit; });
  51. continue;
  52. }
  53. qCDebug(playerControllerLog) << "[VideoPlayThread] call video_refresh, loop:" << loop_count << ", pictq size:" << (is ? is->pictq.size : -1) << ", remaining_time:" << remaining_time;
  54. if (remaining_time > 0.0)
  55. av_usleep((int64_t) (remaining_time * 1000000.0));
  56. remaining_time = REFRESH_RATE;
  57. if ((!is->paused || is->force_refresh)) {
  58. qCDebug(playerControllerLog) << "[VideoPlayThread] call video_refresh, loop:" << loop_count++;
  59. video_refresh(is, &remaining_time);
  60. }
  61. }
  62. qCDebug(playerControllerLog) << "[VideoPlayThread] run end, abort_request:" << is->abort_request << ", m_exit:" << m_exit;
  63. }
  64. void VideoPlayThread::video_refresh(VideoState* is, double* remaining_time)
  65. {
  66. double time;
  67. Frame *sp, *sp2;
  68. if (!is->paused && get_master_sync_type(is) == AV_SYNC_EXTERNAL_CLOCK && is->realtime)
  69. check_external_clock_speed(is);
  70. if (is->video_st) {
  71. retry:
  72. if (frame_queue_nb_remaining(&is->pictq) == 0) {
  73. // nothing to do, no picture to display in the queue
  74. *remaining_time = REFRESH_RATE;
  75. } else {
  76. double last_duration, duration, delay;
  77. Frame *vp, *lastvp;
  78. /* dequeue the picture */
  79. lastvp = frame_queue_peek_last(&is->pictq);
  80. vp = frame_queue_peek(&is->pictq);
  81. if (vp->serial != is->videoq.serial) {
  82. frame_queue_next(&is->pictq);
  83. goto retry;
  84. }
  85. if (lastvp->serial != vp->serial)
  86. is->frame_timer = av_gettime_relative() / 1000000.0;
  87. if (is->paused)
  88. goto display;
  89. /* compute nominal last_duration */
  90. last_duration = vp_duration(is, lastvp, vp);
  91. delay = compute_target_delay(last_duration, is);
  92. time = av_gettime_relative() / 1000000.0;
  93. if (time < is->frame_timer + delay) {
  94. *remaining_time = FFMIN(is->frame_timer + delay - time, *remaining_time);
  95. goto display;
  96. }
  97. is->frame_timer += delay;
  98. if (delay > 0 && time - is->frame_timer > AV_SYNC_THRESHOLD_MAX)
  99. is->frame_timer = time;
  100. is->pictq.mutex->lock();
  101. if (!isnan(vp->pts))
  102. update_video_pts(is, vp->pts, vp->pos, vp->serial);
  103. is->pictq.mutex->unlock();
  104. if (frame_queue_nb_remaining(&is->pictq) > 1) {
  105. Frame* nextvp = frame_queue_peek_next(&is->pictq);
  106. duration = vp_duration(is, vp, nextvp);
  107. if (!is->step
  108. && (framedrop > 0
  109. || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER))
  110. && time > is->frame_timer + duration) {
  111. is->frame_drops_late++;
  112. frame_queue_next(&is->pictq);
  113. goto retry;
  114. }
  115. }
  116. if (is->subtitle_st) {
  117. while (frame_queue_nb_remaining(&is->subpq) > 0) {
  118. sp = frame_queue_peek(&is->subpq);
  119. if (frame_queue_nb_remaining(&is->subpq) > 1)
  120. sp2 = frame_queue_peek_next(&is->subpq);
  121. else
  122. sp2 = nullptr;
  123. if (sp->serial != is->subtitleq.serial
  124. || (is->vidclk.pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))
  125. || (sp2
  126. && is->vidclk.pts
  127. > (sp2->pts + ((float) sp2->sub.start_display_time / 1000)))) {
  128. #if 0
  129. if (sp->uploaded) {
  130. int i;
  131. for (i = 0; i < sp->sub.num_rects; i++) {
  132. AVSubtitleRect* sub_rect = sp->sub.rects[i];
  133. /*uint8_t* pixels;
  134. int pitch, j;
  135. if (!SDL_LockTexture(is->sub_texture, (SDL_Rect*)sub_rect, (void**)&pixels, &pitch)) {
  136. for (j = 0; j < sub_rect->h; j++, pixels += pitch)
  137. memset(pixels, 0, sub_rect->w << 2);
  138. SDL_UnlockTexture(is->sub_texture);
  139. }*/
  140. }
  141. }
  142. #endif
  143. frame_queue_next(&is->subpq);
  144. } else {
  145. break;
  146. }
  147. }
  148. }
  149. frame_queue_next(&is->pictq);
  150. is->force_refresh = 1;
  151. if (is->step && !is->paused)
  152. toggle_pause(is, !is->step);
  153. }
  154. display:
  155. /* display picture */
  156. if (is->force_refresh && is->pictq.rindex_shown)
  157. video_display(is);
  158. }
  159. is->force_refresh = 0;
  160. }
  161. void VideoPlayThread::video_display(VideoState* is)
  162. {
  163. if (is->audio_st && false) {
  164. // video_audio_display(is);
  165. } else if (is->video_st) {
  166. video_image_display(is);
  167. }
  168. }
  169. #if 0
  170. void VideoPlayThread::video_audio_display(VideoState* s)
  171. {
  172. int64_t audio_callback_time = 0;
  173. int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
  174. int ch, channels, h, h2;
  175. int64_t time_diff;
  176. int rdft_bits, nb_freq;
  177. for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)
  178. ;
  179. nb_freq = 1 << (rdft_bits - 1);
  180. /* compute display index : center on currently output samples */
  181. channels = s->audio_tgt.channels;
  182. nb_display_channels = channels;
  183. if (!s->paused) {
  184. int data_used = (2 * nb_freq);
  185. n = 2 * channels;
  186. delay = s->audio_write_buf_size;
  187. delay /= n;
  188. /* to be more precise, we take into account the time spent since
  189. the last buffer computation */
  190. if (audio_callback_time) {
  191. time_diff = av_gettime_relative() - audio_callback_time;
  192. delay -= (time_diff * s->audio_tgt.freq) / 1000000;
  193. }
  194. delay += 2 * data_used;
  195. if (delay < data_used)
  196. delay = data_used;
  197. i_start = x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
  198. /*if (s->show_mode == SHOW_MODE_WAVES) {
  199. h = INT_MIN;
  200. for (i = 0; i < 1000; i += channels) {
  201. int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;
  202. int a = s->sample_array[idx];
  203. int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];
  204. int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];
  205. int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];
  206. int score = a - d;
  207. if (h < score && (b ^ c) < 0) {
  208. h = score;
  209. i_start = idx;
  210. }
  211. }
  212. }*/
  213. s->last_i_start = i_start;
  214. }
  215. else {
  216. i_start = s->last_i_start;
  217. }
  218. #if 0
  219. if (s->show_mode == SHOW_MODE_WAVES) {
  220. SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
  221. /* total height for one channel */
  222. h = s->height / nb_display_channels;
  223. /* graph height / 2 */
  224. h2 = (h * 9) / 20;
  225. for (ch = 0; ch < nb_display_channels; ch++) {
  226. i = i_start + ch;
  227. y1 = s->ytop + ch * h + (h / 2); /* position of center line */
  228. for (x = 0; x < s->width; x++) {
  229. y = (s->sample_array[i] * h2) >> 15;
  230. if (y < 0) {
  231. y = -y;
  232. ys = y1 - y;
  233. }
  234. else {
  235. ys = y1;
  236. }
  237. fill_rectangle(s->xleft + x, ys, 1, y);
  238. i += channels;
  239. if (i >= SAMPLE_ARRAY_SIZE)
  240. i -= SAMPLE_ARRAY_SIZE;
  241. }
  242. }
  243. SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
  244. for (ch = 1; ch < nb_display_channels; ch++) {
  245. y = s->ytop + ch * h;
  246. fill_rectangle(s->xleft, y, s->width, 1);
  247. }
  248. }
  249. else {
  250. if (realloc_texture(&s->vis_texture, SDL_PIXELFORMAT_ARGB8888, s->width, s->height, SDL_BLENDMODE_NONE, 1) < 0)
  251. return;
  252. if (s->xpos >= s->width)
  253. s->xpos = 0;
  254. nb_display_channels = FFMIN(nb_display_channels, 2);
  255. if (rdft_bits != s->rdft_bits) {
  256. av_rdft_end(s->rdft);
  257. av_free(s->rdft_data);
  258. s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
  259. s->rdft_bits = rdft_bits;
  260. s->rdft_data = av_malloc_array(nb_freq, 4 * sizeof(*s->rdft_data));
  261. }
  262. if (!s->rdft || !s->rdft_data) {
  263. av_log(nullptr, AV_LOG_ERROR, "Failed to allocate buffers for RDFT, switching to waves display\n");
  264. s->show_mode = SHOW_MODE_WAVES;
  265. }
  266. else {
  267. FFTSample* data[2];
  268. SDL_Rect rect = { .x = s->xpos, .y = 0, .w = 1, .h = s->height };
  269. uint32_t* pixels;
  270. int pitch;
  271. for (ch = 0; ch < nb_display_channels; ch++) {
  272. data[ch] = s->rdft_data + 2 * nb_freq * ch;
  273. i = i_start + ch;
  274. for (x = 0; x < 2 * nb_freq; x++) {
  275. double w = (x - nb_freq) * (1.0 / nb_freq);
  276. data[ch][x] = s->sample_array[i] * (1.0 - w * w);
  277. i += channels;
  278. if (i >= SAMPLE_ARRAY_SIZE)
  279. i -= SAMPLE_ARRAY_SIZE;
  280. }
  281. av_rdft_calc(s->rdft, data[ch]);
  282. }
  283. /* Least efficient way to do this, we should of course
  284. * directly access it but it is more than fast enough. */
  285. if (!SDL_LockTexture(s->vis_texture, &rect, (void**)&pixels, &pitch)) {
  286. pitch >>= 2;
  287. pixels += pitch * s->height;
  288. for (y = 0; y < s->height; y++) {
  289. double w = 1 / sqrt(nb_freq);
  290. int a = sqrt(w * sqrt(data[0][2 * y + 0] * data[0][2 * y + 0] + data[0][2 * y + 1] * data[0][2 * y + 1]));
  291. int b = (nb_display_channels == 2) ? sqrt(w * hypot(data[1][2 * y + 0], data[1][2 * y + 1]))
  292. : a;
  293. a = FFMIN(a, 255);
  294. b = FFMIN(b, 255);
  295. pixels -= pitch;
  296. *pixels = (a << 16) + (b << 8) + ((a + b) >> 1);
  297. }
  298. SDL_UnlockTexture(s->vis_texture);
  299. }
  300. SDL_RenderCopy(renderer, s->vis_texture, nullptr, nullptr);
  301. }
  302. if (!s->paused)
  303. s->xpos++;
  304. }
  305. #endif
  306. }
  307. #endif
  308. void VideoPlayThread::video_image_display(VideoState* is)
  309. {
  310. Frame* sp = nullptr;
  311. Frame* vp = frame_queue_peek_last(&is->pictq);
  312. Video_Resample* pResample = &m_Resample;
  313. if (frame_queue_nb_remaining(&is->subpq) > 0) {
  314. sp = frame_queue_peek(&is->subpq);
  315. if (vp->pts >= sp->pts + ((float) sp->sub.start_display_time / 1000)) {
  316. if (!sp->uploaded) {
  317. // uint8_t* pixels[4];
  318. // int pitch[4];
  319. if (!sp->width || !sp->height) {
  320. sp->width = vp->width;
  321. sp->height = vp->height;
  322. }
  323. // if (realloc_texture(&is->sub_texture, SDL_PIXELFORMAT_ARGB8888,
  324. // sp->width, sp->height, SDL_BLENDMODE_BLEND, 1) < 0) return;
  325. #if 1
  326. for (unsigned int i = 0; i < sp->sub.num_rects; i++) {
  327. AVSubtitleRect* sub_rect = sp->sub.rects[i];
  328. if (sub_rect->type == SUBTITLE_ASS) {
  329. qDebug("subtitle[%d], format:%d, type:%d, text:%s, flags:%d",
  330. i,
  331. sp->sub.format,
  332. sub_rect->type,
  333. sub_rect->text,
  334. sub_rect->flags);
  335. // QString ass = QString::fromUtf8(sub_rect->ass);
  336. QString ass = QString::fromLocal8Bit(
  337. QString::fromStdString(sub_rect->ass).toUtf8());
  338. QStringList assList = ass.split(",");
  339. if (assList.size() > 8) {
  340. ass = assList[8];
  341. qDebug("ass: %s", qUtf8Printable(ass));
  342. parse_subtitle_ass(ass);
  343. }
  344. } else {
  345. qWarning("not handled yet, type:%d", sub_rect->type);
  346. }
  347. }
  348. #else
  349. for (i = 0; i < sp->sub.num_rects; i++) {
  350. AVSubtitleRect* sub_rect = sp->sub.rects[i];
  351. sub_rect->x = av_clip(sub_rect->x, 0, sp->width);
  352. sub_rect->y = av_clip(sub_rect->y, 0, sp->height);
  353. sub_rect->w = av_clip(sub_rect->w, 0, sp->width - sub_rect->x);
  354. sub_rect->h = av_clip(sub_rect->h, 0, sp->height - sub_rect->y);
  355. is->sub_convert_ctx = sws_getCachedContext(is->sub_convert_ctx,
  356. sub_rect->w,
  357. sub_rect->h,
  358. AV_PIX_FMT_PAL8,
  359. sub_rect->w,
  360. sub_rect->h,
  361. AV_PIX_FMT_BGRA,
  362. 0,
  363. nullptr,
  364. nullptr,
  365. nullptr);
  366. if (!is->sub_convert_ctx) {
  367. av_log(nullptr, AV_LOG_FATAL, "Cannot initialize the conversion context\n");
  368. return;
  369. }
  370. #if 1
  371. sws_scale(is->sub_convert_ctx,
  372. (const uint8_t* const*) sub_rect->data,
  373. sub_rect->linesize,
  374. 0,
  375. sub_rect->h,
  376. pixels,
  377. pitch);
  378. #else
  379. if (!SDL_LockTexture(is->sub_texture,
  380. (SDL_Rect*) sub_rect,
  381. (void**) pixels,
  382. pitch)) {
  383. sws_scale(is->sub_convert_ctx,
  384. (const uint8_t* const*) sub_rect->data,
  385. sub_rect->linesize,
  386. 0,
  387. sub_rect->h,
  388. pixels,
  389. pitch);
  390. SDL_UnlockTexture(is->sub_texture);
  391. }
  392. #endif
  393. }
  394. #endif
  395. sp->uploaded = 1;
  396. }
  397. } else {
  398. sp = nullptr;
  399. }
  400. }
  401. AVFrame* pFrameRGB = pResample->pFrameRGB; // dst
  402. AVCodecContext* pVideoCtx = is->viddec.avctx;
  403. AVFrame* pFrame = vp->frame;
  404. // AVPixelFormat fmt = (AVPixelFormat)pFrame->format; // 0
  405. // const char* fmt_name = av_get_pix_fmt_name(fmt);
  406. // AVHWFramesContext* ctx =
  407. // (AVHWFramesContext*)pVideoCtx->hw_frames_ctx->data; AVPixelFormat sw_fmt =
  408. // ctx->sw_format;
  409. // qDebug("frame w:%d,h:%d, pts:%lld, dts:%lld", pVideoCtx->width,
  410. // pVideoCtx->height, pFrame->pts, pFrame->pkt_dts);
  411. // TODO: 不转换
  412. sws_scale(pResample->sws_ctx,
  413. (uint8_t const* const*) pFrame->data,
  414. pFrame->linesize,
  415. 0,
  416. pVideoCtx->height,
  417. pFrameRGB->data,
  418. pFrameRGB->linesize);
  419. // QImage img(pVideoCtx->width, pVideoCtx->height, QImage::Format_RGB888);
  420. // for (int y = 0; y < pVideoCtx->height; ++y) {
  421. // memcpy(img.scanLine(y),
  422. // pFrameRGB->data[0] + y * pFrameRGB->linesize[0],
  423. // pVideoCtx->width * 3);
  424. // }
  425. // emit frame_ready(img);
  426. if (m_onFrameReady) m_onFrameReady(pFrameRGB);
  427. }
  428. bool VideoPlayThread::init_resample_param(AVCodecContext* pVideo, bool bHardware)
  429. {
  430. Video_Resample* pResample = &m_Resample;
  431. if (pVideo) {
  432. enum AVPixelFormat pix_fmt = pVideo->pix_fmt; // frame format after decode
  433. if (bHardware)
  434. pix_fmt = AV_PIX_FMT_NV12;
  435. struct SwsContext* sws_ctx
  436. = sws_getContext(pVideo->width,
  437. pVideo->height,
  438. pix_fmt, // AV_PIX_FMT_YUV420P
  439. pVideo->width,
  440. pVideo->height,
  441. AV_PIX_FMT_RGB24, // sws_scale destination color scheme
  442. SWS_BILINEAR,
  443. nullptr,
  444. nullptr,
  445. nullptr);
  446. AVFrame* pFrameRGB = av_frame_alloc();
  447. if (!pFrameRGB) {
  448. printf("Could not allocate rgb frame.\n");
  449. return false;
  450. }
  451. pFrameRGB->width = pVideo->width;
  452. pFrameRGB->height = pVideo->height;
  453. pFrameRGB->format = AV_PIX_FMT_RGB24;
  454. int numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGB24, pVideo->width, pVideo->height, 32);
  455. uint8_t* const buffer_RGB = (uint8_t*) av_malloc(numBytes * sizeof(uint8_t));
  456. if (!buffer_RGB) {
  457. printf("Could not allocate buffer.\n");
  458. return false;
  459. }
  460. av_image_fill_arrays(pFrameRGB->data,
  461. pFrameRGB->linesize,
  462. buffer_RGB,
  463. AV_PIX_FMT_RGB24,
  464. pVideo->width,
  465. pVideo->height,
  466. 32);
  467. pResample->sws_ctx = sws_ctx;
  468. pResample->pFrameRGB = pFrameRGB;
  469. pResample->buffer_RGB = buffer_RGB;
  470. return true;
  471. }
  472. return false;
  473. }
  474. void VideoPlayThread::final_resample_param()
  475. {
  476. Video_Resample* pResample = &m_Resample;
  477. // Free video resample context
  478. sws_freeContext(pResample->sws_ctx);
  479. // Free the RGB image
  480. av_free(pResample->buffer_RGB);
  481. av_frame_free(&pResample->pFrameRGB);
  482. av_free(pResample->pFrameRGB);
  483. }
  484. void VideoPlayThread::parse_subtitle_ass(const QString& text)
  485. {
  486. QString str = text;
  487. str.remove(m_assFilter);
  488. str.replace(m_assNewLineReplacer, "\n");
  489. str = str.trimmed();
  490. // emit subtitle_ready(str);
  491. if (m_onSubtitleReady) m_onSubtitleReady(str);
  492. }