packets_sync.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  1. // ***********************************************************/
  2. // packets_sync.cpp
  3. //
  4. // Copy Right @ Steven Huang. All rights reserved.
  5. //
  6. // packets A/V synchronization struct and operations definition.
  7. // This code is referenced from ffplay.c in Ffmpeg library.
  8. // ***********************************************************/
  9. #include "packets_sync.h"
  10. int framedrop = -1;
  11. // static int decoder_reorder_pts = -1;
  12. // static int display_disable = 1;
  13. // static int64_t audio_callback_time;
  14. int packet_queue_init(PacketQueue* q)
  15. {
  16. memset(q, 0, sizeof(PacketQueue));
  17. q->pkt_list = av_fifo_alloc2(1, sizeof(MyAVPacketList), AV_FIFO_FLAG_AUTO_GROW);
  18. if (!q->pkt_list)
  19. return AVERROR(ENOMEM);
  20. q->mutex = new QMutex();
  21. if (!q->mutex) {
  22. av_log(nullptr, AV_LOG_FATAL, "new QMutex() error.\n");
  23. return AVERROR(ENOMEM);
  24. }
  25. q->cond = new QWaitCondition();
  26. if (!q->cond) {
  27. av_log(nullptr, AV_LOG_FATAL, "new QWaitCondition() error.\n");
  28. return AVERROR(ENOMEM);
  29. }
  30. q->abort_request = 1;
  31. return 0;
  32. }
  33. void packet_queue_destroy(PacketQueue* q)
  34. {
  35. packet_queue_flush(q);
  36. av_fifo_freep2(&q->pkt_list);
  37. delete q->mutex;
  38. delete q->cond;
  39. }
  40. void packet_queue_flush(PacketQueue* q)
  41. {
  42. MyAVPacketList pkt1;
  43. q->mutex->lock();
  44. while (av_fifo_read(q->pkt_list, &pkt1, 1) >= 0)
  45. av_packet_free(&pkt1.pkt);
  46. q->nb_packets = 0;
  47. q->size = 0;
  48. q->duration = 0;
  49. q->serial++;
  50. q->mutex->unlock();
  51. }
  52. void packet_queue_start(PacketQueue* q)
  53. {
  54. q->mutex->lock();
  55. q->abort_request = 0;
  56. q->serial++;
  57. q->mutex->unlock();
  58. }
  59. void packet_queue_abort(PacketQueue* q)
  60. {
  61. q->mutex->lock();
  62. q->abort_request = 1;
  63. q->cond->wakeAll();
  64. q->mutex->unlock();
  65. }
  66. int packet_queue_get(PacketQueue* q, AVPacket* pkt, int block, int* serial)
  67. {
  68. #if PRINT_PACKETQUEUE_INFO
  69. // packet_queue_print(q, pkt, "packet_queue_get");
  70. #endif
  71. MyAVPacketList pkt1;
  72. int ret = 0;
  73. q->mutex->lock();
  74. for (;;) {
  75. if (q->abort_request) {
  76. ret = -1;
  77. break;
  78. }
  79. if (av_fifo_read(q->pkt_list, &pkt1, 1) >= 0) {
  80. q->nb_packets--;
  81. q->size -= pkt1.pkt->size + sizeof(pkt1);
  82. q->duration -= pkt1.pkt->duration;
  83. av_packet_move_ref(pkt, pkt1.pkt);
  84. if (serial)
  85. *serial = pkt1.serial;
  86. av_packet_free(&pkt1.pkt);
  87. ret = 1;
  88. break;
  89. } else if (!block) {
  90. ret = 0;
  91. break;
  92. } else {
  93. q->cond->wait(q->mutex);
  94. }
  95. }
  96. q->mutex->unlock();
  97. return ret;
  98. }
  99. void packet_queue_print(const PacketQueue* q, const AVPacket* pkt, const QString& prefix)
  100. {
  101. qDebug("[%s]Queue:[%p](nb_packets:%d, size:%d, dur:%d, serial:%d), "
  102. "pkt(pts:%lld,dts:%lld,size:%d,s_index:%d,dur:%lld,pos:%lld).",
  103. qUtf8Printable(prefix),
  104. q,
  105. q->nb_packets,
  106. q->size,
  107. q->duration,
  108. q->serial,
  109. pkt->pts,
  110. pkt->dts,
  111. pkt->size,
  112. pkt->stream_index,
  113. pkt->duration,
  114. pkt->pos);
  115. }
  116. int packet_queue_put(PacketQueue* q, AVPacket* pkt)
  117. {
  118. AVPacket* pkt1;
  119. int ret = -1;
  120. pkt1 = av_packet_alloc();
  121. if (!pkt1) {
  122. av_packet_unref(pkt);
  123. return ret;
  124. }
  125. av_packet_move_ref(pkt1, pkt);
  126. q->mutex->lock();
  127. ret = packet_queue_put_private(q, pkt1);
  128. q->mutex->unlock();
  129. if (ret < 0)
  130. av_packet_free(&pkt1);
  131. #if PRINT_PACKETQUEUE_INFO
  132. // packet_queue_print(q, pkt, "packet_queue_put");
  133. #endif
  134. return ret;
  135. }
  136. int packet_queue_put_nullpacket(PacketQueue* q, AVPacket* pkt, int stream_index)
  137. {
  138. pkt->stream_index = stream_index;
  139. return packet_queue_put(q, pkt);
  140. }
  141. int packet_queue_put_private(PacketQueue* q, AVPacket* pkt)
  142. {
  143. MyAVPacketList pkt1;
  144. int ret;
  145. if (q->abort_request)
  146. return -1;
  147. pkt1.pkt = pkt;
  148. pkt1.serial = q->serial;
  149. ret = av_fifo_write(q->pkt_list, &pkt1, 1);
  150. if (ret < 0)
  151. return ret;
  152. q->nb_packets++;
  153. q->size += pkt1.pkt->size + sizeof(pkt1);
  154. q->duration += pkt1.pkt->duration;
  155. /* XXX: should duplicate packet data in DV case */
  156. q->cond->wakeAll();
  157. return 0;
  158. }
  159. int frame_queue_init(FrameQueue* f, PacketQueue* pktq, int max_size, int keep_last)
  160. {
  161. int i;
  162. memset(f, 0, sizeof(FrameQueue));
  163. if (!(f->mutex = new QMutex())) {
  164. av_log(nullptr, AV_LOG_FATAL, "new QMutex() error!\n");
  165. return AVERROR(ENOMEM);
  166. }
  167. if (!(f->cond = new QWaitCondition())) {
  168. av_log(nullptr, AV_LOG_FATAL, "new QWaitCondition() error\n");
  169. return AVERROR(ENOMEM);
  170. }
  171. f->pktq = pktq;
  172. f->max_size = FFMIN(max_size, FRAME_QUEUE_SIZE);
  173. f->keep_last = !!keep_last;
  174. for (i = 0; i < f->max_size; i++)
  175. if (!(f->queue[i].frame = av_frame_alloc()))
  176. return AVERROR(ENOMEM);
  177. return 0;
  178. }
  179. void frame_queue_destory(FrameQueue* f)
  180. {
  181. int i;
  182. for (i = 0; i < f->max_size; i++) {
  183. Frame* vp = &f->queue[i];
  184. frame_queue_unref_item(vp);
  185. av_frame_free(&vp->frame);
  186. }
  187. delete f->mutex;
  188. delete f->cond;
  189. }
  190. void frame_queue_unref_item(Frame* vp)
  191. {
  192. av_frame_unref(vp->frame); // frame reference number reduce 1
  193. avsubtitle_free(&vp->sub); // sub
  194. }
  195. void frame_queue_signal(FrameQueue* f)
  196. {
  197. f->mutex->lock();
  198. f->cond->wakeAll();
  199. f->mutex->unlock();
  200. }
  201. Frame* frame_queue_peek(FrameQueue* f)
  202. {
  203. return &f->queue[(f->rindex + f->rindex_shown) % f->max_size];
  204. }
  205. Frame* frame_queue_peek_next(FrameQueue* f)
  206. {
  207. return &f->queue[(f->rindex + f->rindex_shown + 1) % f->max_size];
  208. }
  209. Frame* frame_queue_peek_last(FrameQueue* f)
  210. {
  211. return &f->queue[f->rindex];
  212. }
  213. Frame* frame_queue_peek_writable(FrameQueue* f)
  214. {
  215. /* wait until we have space to put a new frame */
  216. f->mutex->lock();
  217. while (f->size >= f->max_size && !f->pktq->abort_request) {
  218. f->cond->wait(f->mutex);
  219. }
  220. f->mutex->unlock();
  221. if (f->pktq->abort_request)
  222. return nullptr;
  223. return &f->queue[f->windex];
  224. }
  225. Frame* frame_queue_peek_readable(FrameQueue* f)
  226. {
  227. /* wait until we have a readable a new frame */
  228. f->mutex->lock();
  229. while (f->size - f->rindex_shown <= 0 && !f->pktq->abort_request) {
  230. f->cond->wait(f->mutex);
  231. }
  232. f->mutex->unlock();
  233. if (f->pktq->abort_request)
  234. return nullptr;
  235. return &f->queue[(f->rindex + f->rindex_shown) % f->max_size];
  236. }
  237. void frame_queue_push(FrameQueue* f)
  238. {
  239. if (++f->windex == f->max_size)
  240. f->windex = 0;
  241. f->mutex->lock();
  242. f->size++;
  243. f->cond->wakeAll();
  244. f->mutex->unlock();
  245. }
  246. void frame_queue_next(FrameQueue* f)
  247. {
  248. if (f->keep_last && !f->rindex_shown) {
  249. f->rindex_shown = 1;
  250. return;
  251. }
  252. frame_queue_unref_item(&f->queue[f->rindex]);
  253. if (++f->rindex == f->max_size)
  254. f->rindex = 0;
  255. f->mutex->lock();
  256. f->size--;
  257. f->cond->wakeAll();
  258. f->mutex->unlock();
  259. }
  260. /* return the number of undisplayed frames in the queue */
  261. int frame_queue_nb_remaining(FrameQueue* f)
  262. {
  263. return f->size - f->rindex_shown;
  264. }
  265. /* return last shown position */
  266. int64_t frame_queue_last_pos(FrameQueue* f)
  267. {
  268. Frame* fp = &f->queue[f->rindex];
  269. if (f->rindex_shown && fp->serial == f->pktq->serial)
  270. return fp->pos;
  271. else
  272. return -1;
  273. }
  274. int queue_picture(
  275. VideoState* is, AVFrame* src_frame, double pts, double duration, int64_t pos, int serial)
  276. {
  277. #if PRINT_PACKETQUEUE_INFO
  278. // int64 lld, double lf
  279. qDebug("queue picture, w:%d, h:%d, nb:%d, ft:%d(%s), kf:%d, pic_t:%d(%c), "
  280. "pts:%lf, duration:%lf, pos:%lld, serial:%d",
  281. src_frame->width,
  282. src_frame->height,
  283. src_frame->nb_samples,
  284. src_frame->format,
  285. av_get_sample_fmt_name(AVSampleFormat(src_frame->format)),
  286. src_frame->key_frame,
  287. src_frame->pict_type,
  288. av_get_picture_type_char(src_frame->pict_type),
  289. pts,
  290. duration,
  291. pos,
  292. serial);
  293. #endif
  294. Frame* vp;
  295. if (!(vp = frame_queue_peek_writable(&is->pictq)))
  296. return -1;
  297. vp->sar = src_frame->sample_aspect_ratio;
  298. vp->uploaded = 0;
  299. vp->width = src_frame->width;
  300. vp->height = src_frame->height;
  301. vp->format = src_frame->format;
  302. vp->pts = pts;
  303. vp->duration = duration;
  304. vp->pos = pos;
  305. vp->serial = serial;
  306. av_frame_move_ref(vp->frame, src_frame);
  307. frame_queue_push(&is->pictq);
  308. return 0;
  309. }
  310. int get_video_frame(VideoState* is, AVFrame* frame)
  311. {
  312. int got_picture = -1;
  313. if ((got_picture = decoder_decode_frame(&is->viddec, frame, nullptr)) < 0)
  314. return -1;
  315. if (got_picture) {
  316. double dpts = NAN;
  317. if (frame->pts != AV_NOPTS_VALUE)
  318. dpts = av_q2d(is->video_st->time_base) * frame->pts;
  319. frame->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, frame);
  320. if (framedrop > 0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {
  321. if (frame->pts != AV_NOPTS_VALUE) {
  322. double diff = dpts - get_master_clock(is);
  323. if (!isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD
  324. && diff - is->frame_last_filter_delay < 0
  325. && is->viddec.pkt_serial == is->vidclk.serial && is->videoq.nb_packets) {
  326. is->frame_drops_early++;
  327. av_frame_unref(frame);
  328. got_picture = 0;
  329. }
  330. }
  331. }
  332. }
  333. return got_picture;
  334. }
  335. int decoder_init(Decoder* d,
  336. AVCodecContext* avctx,
  337. PacketQueue* queue,
  338. QWaitCondition* empty_queue_cond)
  339. {
  340. memset(d, 0, sizeof(Decoder));
  341. d->pkt = av_packet_alloc();
  342. if (!d->pkt)
  343. return AVERROR(ENOMEM);
  344. d->avctx = avctx;
  345. d->queue = queue;
  346. d->empty_queue_cond = empty_queue_cond;
  347. d->start_pts = AV_NOPTS_VALUE;
  348. d->pkt_serial = -1;
  349. return 0;
  350. }
  351. int decoder_start(Decoder* d, void* thread, const char* thread_name)
  352. {
  353. packet_queue_start(d->queue);
  354. d->decoder_tid = thread;
  355. d->decoder_name = av_strdup(thread_name);
  356. return 0;
  357. }
  358. void decoder_destroy(Decoder* d)
  359. {
  360. av_packet_free(&d->pkt);
  361. avcodec_free_context(&d->avctx);
  362. av_free(d->decoder_name);
  363. }
  364. void decoder_abort(Decoder* d, FrameQueue* fq)
  365. {
  366. packet_queue_abort(d->queue);
  367. frame_queue_signal(fq);
  368. // SDL_WaitThread(d->decoder_tid, nullptr);
  369. // TODO: //
  370. ThreadBase* thread = (ThreadBase*) (d->decoder_tid);
  371. if (thread && thread->isRunning()) {
  372. thread->join();
  373. }
  374. d->decoder_tid = nullptr;
  375. packet_queue_flush(d->queue);
  376. }
  377. int decoder_decode_frame(Decoder* d, AVFrame* frame, AVSubtitle* sub)
  378. {
  379. int ret = AVERROR(EAGAIN);
  380. int decoder_reorder_pts = -1;
  381. for (;;) {
  382. if (d->queue->serial == d->pkt_serial) {
  383. do {
  384. if (d->queue->abort_request)
  385. return -1;
  386. switch (d->avctx->codec_type) {
  387. case AVMEDIA_TYPE_VIDEO:
  388. ret = avcodec_receive_frame(d->avctx, frame);
  389. if (ret >= 0) {
  390. if (decoder_reorder_pts == -1) {
  391. frame->pts = frame->best_effort_timestamp;
  392. } else if (!decoder_reorder_pts) {
  393. frame->pts = frame->pkt_dts;
  394. }
  395. }
  396. break;
  397. case AVMEDIA_TYPE_AUDIO:
  398. ret = avcodec_receive_frame(d->avctx, frame);
  399. if (ret >= 0) {
  400. AVRational tb = AVRational{1, frame->sample_rate};
  401. if (frame->pts != AV_NOPTS_VALUE)
  402. frame->pts = av_rescale_q(frame->pts, d->avctx->pkt_timebase, tb);
  403. else if (d->next_pts != AV_NOPTS_VALUE)
  404. frame->pts = av_rescale_q(d->next_pts, d->next_pts_tb, tb);
  405. if (frame->pts != AV_NOPTS_VALUE) {
  406. d->next_pts = frame->pts + frame->nb_samples;
  407. d->next_pts_tb = tb;
  408. }
  409. }
  410. break;
  411. }
  412. if (ret == AVERROR_EOF) {
  413. d->finished = d->pkt_serial;
  414. avcodec_flush_buffers(d->avctx);
  415. return 0;
  416. }
  417. if (ret >= 0)
  418. return 1;
  419. } while (ret != AVERROR(EAGAIN));
  420. }
  421. do {
  422. if (d->queue->nb_packets == 0)
  423. d->empty_queue_cond->wakeAll();
  424. if (d->packet_pending) {
  425. d->packet_pending = 0;
  426. } else {
  427. int old_serial = d->pkt_serial;
  428. if (packet_queue_get(d->queue, d->pkt, 1, &d->pkt_serial) < 0)
  429. return -1;
  430. if (old_serial != d->pkt_serial) {
  431. avcodec_flush_buffers(d->avctx);
  432. d->finished = 0;
  433. d->next_pts = d->start_pts;
  434. d->next_pts_tb = d->start_pts_tb;
  435. }
  436. }
  437. if (d->queue->serial == d->pkt_serial)
  438. break;
  439. av_packet_unref(d->pkt);
  440. } while (1);
  441. if (d->avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  442. int got_frame = 0;
  443. ret = avcodec_decode_subtitle2(d->avctx, sub, &got_frame, d->pkt);
  444. if (ret < 0) {
  445. ret = AVERROR(EAGAIN);
  446. } else {
  447. if (got_frame && !d->pkt->data) {
  448. d->packet_pending = 1;
  449. }
  450. ret = got_frame ? 0 : (d->pkt->data ? AVERROR(EAGAIN) : AVERROR_EOF);
  451. }
  452. av_packet_unref(d->pkt);
  453. } else {
  454. if (avcodec_send_packet(d->avctx, d->pkt) == AVERROR(EAGAIN)) {
  455. av_log(d->avctx,
  456. AV_LOG_ERROR,
  457. "Receive_frame and send_packet both returned EAGAIN, which is "
  458. "an API violation.\n");
  459. d->packet_pending = 1;
  460. } else {
  461. av_packet_unref(d->pkt);
  462. }
  463. }
  464. }
  465. }
  466. void get_file_info(const char* filename, int64_t& duration)
  467. {
  468. AVFormatContext* pFormatCtx = avformat_alloc_context();
  469. if (avformat_open_input(&pFormatCtx, filename, NULL, NULL) == 0) {
  470. if (pFormatCtx->duration < 0)
  471. avformat_find_stream_info(pFormatCtx, NULL);
  472. duration = pFormatCtx->duration;
  473. }
  474. // etc
  475. avformat_close_input(&pFormatCtx);
  476. avformat_free_context(pFormatCtx);
  477. }
  478. void get_duration_time(
  479. const int64_t duration_us, int64_t& hours, int64_t& mins, int64_t& secs, int64_t& us)
  480. {
  481. int64_t duration = duration_us + (duration_us <= INT64_MAX - 5000 ? 5000 : 0);
  482. duration = duration < 0 ? 0 : duration;
  483. secs = duration / AV_TIME_BASE;
  484. us = duration % AV_TIME_BASE;
  485. us = (100 * us) / AV_TIME_BASE;
  486. mins = secs / 60;
  487. secs %= 60;
  488. hours = mins / 60;
  489. mins %= 60;
  490. }
  491. double get_clock(Clock* c)
  492. {
  493. if (*c->queue_serial != c->serial)
  494. return NAN;
  495. if (c->paused) {
  496. return c->pts;
  497. } else {
  498. double time = av_gettime_relative() / 1000000.0;
  499. return c->pts_drift + time - (time - c->last_updated) * (1.0 - c->speed);
  500. }
  501. }
  502. void set_clock_at(Clock* c, double pts, int serial, double time)
  503. {
  504. c->pts = pts;
  505. c->last_updated = time;
  506. c->pts_drift = c->pts - time;
  507. c->serial = serial;
  508. }
  509. void set_clock(Clock* c, double pts, int serial)
  510. {
  511. double time = av_gettime_relative() / 1000000.0;
  512. set_clock_at(c, pts, serial, time);
  513. }
  514. void set_clock_speed(Clock* c, double speed)
  515. {
  516. set_clock(c, get_clock(c), c->serial);
  517. c->speed = speed;
  518. }
  519. void init_clock(Clock* c, int* queue_serial)
  520. {
  521. c->speed = 1.0;
  522. c->paused = 0;
  523. c->queue_serial = queue_serial;
  524. set_clock(c, NAN, -1);
  525. }
  526. void sync_clock_to_slave(Clock* c, Clock* slave)
  527. {
  528. double clock = get_clock(c);
  529. double slave_clock = get_clock(slave);
  530. if (!isnan(slave_clock) && (isnan(clock) || fabs(clock - slave_clock) > AV_NOSYNC_THRESHOLD))
  531. set_clock(c, slave_clock, slave->serial);
  532. }
  533. int stream_has_enough_packets(AVStream* st, int stream_id, PacketQueue* queue)
  534. {
  535. return stream_id < 0 || queue->abort_request || (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
  536. || queue->nb_packets > MIN_FRAMES
  537. && (!queue->duration || av_q2d(st->time_base) * queue->duration > 1.0);
  538. }
  539. int is_realtime(AVFormatContext* s)
  540. {
  541. if (!strcmp(s->iformat->name, "rtp") || !strcmp(s->iformat->name, "rtsp")
  542. || !strcmp(s->iformat->name, "sdp"))
  543. return 1;
  544. if (s->pb && (!strncmp(s->url, "rtp:", 4) || !strncmp(s->url, "udp:", 4)))
  545. return 1;
  546. return 0;
  547. }
  548. int get_master_sync_type(VideoState* is)
  549. {
  550. if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
  551. if (is->video_st)
  552. return AV_SYNC_VIDEO_MASTER;
  553. else
  554. return AV_SYNC_AUDIO_MASTER;
  555. } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
  556. if (is->audio_st)
  557. return AV_SYNC_AUDIO_MASTER;
  558. else
  559. return AV_SYNC_EXTERNAL_CLOCK;
  560. } else {
  561. return AV_SYNC_EXTERNAL_CLOCK;
  562. }
  563. }
  564. /* get the current master clock value */
  565. double get_master_clock(VideoState* is)
  566. {
  567. double val;
  568. switch (get_master_sync_type(is)) {
  569. case AV_SYNC_VIDEO_MASTER:
  570. val = get_clock(&is->vidclk);
  571. break;
  572. case AV_SYNC_AUDIO_MASTER:
  573. val = get_clock(&is->audclk);
  574. break;
  575. default:
  576. val = get_clock(&is->extclk);
  577. break;
  578. }
  579. return val;
  580. }
  581. void check_external_clock_speed(VideoState* is)
  582. {
  583. if ((is->video_stream >= 0 && is->videoq.nb_packets <= EXTERNAL_CLOCK_MIN_FRAMES)
  584. || (is->audio_stream >= 0 && is->audioq.nb_packets <= EXTERNAL_CLOCK_MIN_FRAMES)) {
  585. set_clock_speed(&is->extclk,
  586. FFMAX(EXTERNAL_CLOCK_SPEED_MIN,
  587. is->extclk.speed - EXTERNAL_CLOCK_SPEED_STEP));
  588. } else if ((is->video_stream < 0 || is->videoq.nb_packets > EXTERNAL_CLOCK_MAX_FRAMES)
  589. && (is->audio_stream < 0 || is->audioq.nb_packets > EXTERNAL_CLOCK_MAX_FRAMES)) {
  590. set_clock_speed(&is->extclk,
  591. FFMIN(EXTERNAL_CLOCK_SPEED_MAX,
  592. is->extclk.speed + EXTERNAL_CLOCK_SPEED_STEP));
  593. } else {
  594. double speed = is->extclk.speed;
  595. if (speed != 1.0)
  596. set_clock_speed(&is->extclk,
  597. speed + EXTERNAL_CLOCK_SPEED_STEP * (1.0 - speed) / fabs(1.0 - speed));
  598. }
  599. }
  600. /* seek in the stream */
  601. void stream_seek(VideoState* is, int64_t pos, int64_t rel, int seek_by_bytes)
  602. {
  603. if (!is->seek_req) {
  604. is->seek_pos = pos;
  605. is->seek_rel = rel;
  606. is->seek_flags &= ~AVSEEK_FLAG_BYTE;
  607. if (seek_by_bytes)
  608. is->seek_flags |= AVSEEK_FLAG_BYTE;
  609. is->seek_req = 1;
  610. // SDL_CondSignal(is->continue_read_thread);
  611. is->continue_read_thread->wakeAll();
  612. }
  613. }
  614. /* pause or resume the video */
  615. // void stream_toggle_pause(VideoState* is, bool pause)
  616. //{
  617. // if (is->paused) {
  618. // is->frame_timer += av_gettime_relative() / 1000000.0 -
  619. //is->vidclk.last_updated; if (is->read_pause_return != AVERROR(ENOSYS)) {
  620. // is->vidclk.paused = 0;
  621. // }
  622. // set_clock(&is->vidclk, get_clock(&is->vidclk),
  623. //is->vidclk.serial);
  624. // }
  625. // set_clock(&is->extclk, get_clock(&is->extclk), is->extclk.serial);
  626. // is->paused = is->audclk.paused = is->vidclk.paused = is->extclk.paused =
  627. //pause; // !is->paused; is->step = 0;
  628. //}
  629. void toggle_pause(VideoState* is, bool pause)
  630. {
  631. if (is->paused) {
  632. is->frame_timer += av_gettime_relative() / 1000000.0 - is->vidclk.last_updated;
  633. if (is->read_pause_return != AVERROR(ENOSYS)) {
  634. is->vidclk.paused = 0;
  635. }
  636. set_clock(&is->vidclk, get_clock(&is->vidclk), is->vidclk.serial);
  637. }
  638. set_clock(&is->extclk, get_clock(&is->extclk), is->extclk.serial);
  639. is->paused = is->audclk.paused = is->vidclk.paused = is->extclk.paused = pause; // !is->paused;
  640. is->step = 0;
  641. }
  642. void toggle_mute(VideoState* is, bool mute)
  643. {
  644. bool muted = !!is->muted;
  645. if (muted != mute) {
  646. is->muted = mute;
  647. }
  648. }
  649. void update_volume(VideoState* is, int sign, double step)
  650. {
  651. double volume_level = is->audio_volume
  652. ? (20 * log(is->audio_volume / (double) SDL_MIX_MAXVOLUME) / log(10))
  653. : -1000.0;
  654. int new_volume = lrint(SDL_MIX_MAXVOLUME * pow(10.0, (volume_level + sign * step) / 20.0));
  655. is->audio_volume = av_clip(is->audio_volume == new_volume ? (is->audio_volume + sign)
  656. : new_volume,
  657. 0,
  658. SDL_MIX_MAXVOLUME);
  659. }
  660. void step_to_next_frame(VideoState* is)
  661. {
  662. /* if the stream is paused unpause it, then step */
  663. if (is->paused)
  664. toggle_pause(is, !is->paused);
  665. is->step = 1;
  666. }
  667. double compute_target_delay(double delay, VideoState* is)
  668. {
  669. double sync_threshold, diff = 0;
  670. /* update delay to follow master synchronisation source */
  671. if (get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER) {
  672. /* if video is slave, we try to correct big delays by
  673. duplicating or deleting a frame */
  674. diff = get_clock(&is->vidclk) - get_master_clock(is);
  675. /* skip or repeat frame. We take into account the
  676. delay to compute the threshold. I still don't know
  677. if it is the best guess */
  678. sync_threshold = FFMAX(AV_SYNC_THRESHOLD_MIN, FFMIN(AV_SYNC_THRESHOLD_MAX, delay));
  679. if (!isnan(diff) && fabs(diff) < is->max_frame_duration) {
  680. if (diff <= -sync_threshold)
  681. delay = FFMAX(0, delay + diff);
  682. else if (diff >= sync_threshold && delay > AV_SYNC_FRAMEDUP_THRESHOLD)
  683. delay = delay + diff;
  684. else if (diff >= sync_threshold)
  685. delay = 2 * delay;
  686. }
  687. }
  688. av_log(nullptr, AV_LOG_TRACE, "video: delay=%0.3f A-V=%f\n", delay, -diff);
  689. return delay;
  690. }
  691. double vp_duration(VideoState* is, Frame* vp, Frame* nextvp)
  692. {
  693. if (vp->serial == nextvp->serial) {
  694. double duration = nextvp->pts - vp->pts;
  695. if (isnan(duration) || duration <= 0 || duration > is->max_frame_duration)
  696. return vp->duration;
  697. else
  698. return duration;
  699. }
  700. return 0.0;
  701. }
  702. void update_video_pts(VideoState* is, double pts, int64_t pos, int serial)
  703. {
  704. /* update current video pts */
  705. set_clock(&is->vidclk, pts, serial);
  706. sync_clock_to_slave(&is->extclk, &is->vidclk);
  707. }
  708. #if PRINT_PACKETQUEUE_INFO
  709. void print_state_info(VideoState* is)
  710. {
  711. if (is) {
  712. PacketQueue* pPacket = &is->videoq;
  713. qDebug("[VideoState] V PacketQueue[%p](nb_packets:%d,size:%d,dur:%lld, "
  714. "abort:%d, serial:%d)",
  715. pPacket,
  716. pPacket->nb_packets,
  717. pPacket->size,
  718. pPacket->duration,
  719. pPacket->abort_request,
  720. pPacket->serial);
  721. pPacket = &is->audioq;
  722. qDebug("[VideoState] A PacketQueue[%p](nb_packets:%d,size:%d,dur:%lld, "
  723. "abort:%d, serial:%d)",
  724. pPacket,
  725. pPacket->nb_packets,
  726. pPacket->size,
  727. pPacket->duration,
  728. pPacket->abort_request,
  729. pPacket->serial);
  730. pPacket = &is->subtitleq;
  731. qDebug("[VideoState] S PacketQueue[%p](nb_packets:%d,size:%d,dur:%lld, "
  732. "abort:%d, serial:%d)",
  733. pPacket,
  734. pPacket->nb_packets,
  735. pPacket->size,
  736. pPacket->duration,
  737. pPacket->abort_request,
  738. pPacket->serial);
  739. /*qDebug("[VideoState]FrameQueue(v:%p,a:%p,s:%p)",
  740. &is->pictq, &is->sampq, &is->subpq);
  741. qDebug("[VideoState]Decoder(v:%p,a:%p,s:%p)",
  742. &is->viddec, &is->auddec, &is->subdec);
  743. qDebug("[VideoState]Clock(v:%p,a:%p,s:%p)",
  744. &is->vidclk, &is->audclk, &is->extclk);*/
  745. }
  746. }
  747. #endif
  748. #if USE_AVFILTER_AUDIO
  749. void set_audio_playspeed(VideoState* is, double value)
  750. {
  751. if (value < 0 || value > 4)
  752. return;
  753. if (is->audio_speed == value)
  754. return;
  755. is->audio_speed = value;
  756. const size_t len = 32;
  757. if (!is->afilters)
  758. is->afilters = (char*) av_malloc(len);
  759. if (value <= 0.5) {
  760. snprintf(is->afilters, len, "atempo=0.5,");
  761. char tmp[128];
  762. snprintf(tmp, sizeof(tmp), "atempo=%lf", value / 0.5);
  763. // strncat(is->afilters, tmp, len - strlen(is->afilters) - 1);
  764. strncat_s(is->afilters, len, tmp, len - strlen(is->afilters) - 1);
  765. } else if (value <= 2.0) {
  766. snprintf(is->afilters, len, "atempo=%lf", value);
  767. } else {
  768. snprintf(is->afilters, len, "atempo=2.0,");
  769. char tmp[128];
  770. snprintf(tmp, sizeof(tmp), "atempo=%lf", value / 2.0);
  771. // strncat(is->afilters, tmp, len - strlen(is->afilters) - 1);
  772. strncat_s(is->afilters, len, tmp, len - strlen(is->afilters) - 1);
  773. }
  774. qDebug("changing audio filters to :%s", is->afilters);
  775. #if USE_AVFILTER_VIDEO
  776. set_video_playspeed(is);
  777. #endif
  778. is->audio_clock_old = is->audio_clock;
  779. is->req_afilter_reconfigure = 1;
  780. }
  781. void set_video_playspeed(VideoState* is)
  782. {
  783. double speed = is->audio_speed;
  784. size_t len = 32;
  785. if (!is->vfilters)
  786. is->vfilters = (char*) av_malloc(len);
  787. snprintf(is->vfilters, len, "setpts=%.4lf*PTS", 1.0 / speed);
  788. is->req_vfilter_reconfigure = 1;
  789. qDebug("changing video filters to :%s", is->vfilters);
  790. }
  791. int cmp_audio_fmts(enum AVSampleFormat fmt1,
  792. int64_t channel_count1,
  793. enum AVSampleFormat fmt2,
  794. int64_t channel_count2)
  795. {
  796. /* If channel count == 1, planar and non-planar formats are the same */
  797. if (channel_count1 == 1 && channel_count2 == 1)
  798. return av_get_packed_sample_fmt(fmt1) != av_get_packed_sample_fmt(fmt2);
  799. else
  800. return channel_count1 != channel_count2 || fmt1 != fmt2;
  801. }
  802. // int64_t get_valid_channel_layout(int64_t channel_layout, int channels)
  803. //{
  804. // if (channel_layout && av_get_channel_layout_nb_channels(channel_layout)
  805. //== channels) return channel_layout; else return 0;
  806. //}
  807. int configure_filtergraph(AVFilterGraph* graph,
  808. const char* filtergraph,
  809. AVFilterContext* source_ctx,
  810. AVFilterContext* sink_ctx)
  811. {
  812. int ret;
  813. int nb_filters = graph->nb_filters;
  814. AVFilterInOut *outputs = nullptr, *inputs = nullptr;
  815. if (filtergraph) {
  816. outputs = avfilter_inout_alloc();
  817. inputs = avfilter_inout_alloc();
  818. if (!outputs || !inputs) {
  819. ret = AVERROR(ENOMEM);
  820. goto fail;
  821. }
  822. outputs->name = av_strdup("in");
  823. outputs->filter_ctx = source_ctx;
  824. outputs->pad_idx = 0;
  825. outputs->next = nullptr;
  826. inputs->name = av_strdup("out");
  827. inputs->filter_ctx = sink_ctx;
  828. inputs->pad_idx = 0;
  829. inputs->next = nullptr;
  830. if ((ret = avfilter_graph_parse_ptr(graph, filtergraph, &inputs, &outputs, nullptr)) < 0)
  831. goto fail;
  832. } else {
  833. if ((ret = avfilter_link(source_ctx, 0, sink_ctx, 0)) < 0)
  834. goto fail;
  835. }
  836. /* Reorder the filters to ensure that inputs of the custom filters are merged
  837. * first */
  838. for (unsigned int i = 0; i < graph->nb_filters - nb_filters; i++)
  839. FFSWAP(AVFilterContext*, graph->filters[i], graph->filters[i + nb_filters]);
  840. ret = avfilter_graph_config(graph, nullptr);
  841. fail:
  842. avfilter_inout_free(&outputs);
  843. avfilter_inout_free(&inputs);
  844. return ret;
  845. }
  846. int configure_audio_filters(VideoState* is, const char* afilters, int force_output_format)
  847. {
  848. static const enum AVSampleFormat sample_fmts[] = {AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE};
  849. int sample_rates[2] = {0, -1};
  850. // int64_t channel_layouts[2] = { 0, -1 };
  851. // AVChannelLayout channel_layouts[2] = {};
  852. // int channels[2] = { 0, -1 };
  853. AVFilterContext *filt_asrc = nullptr, *filt_asink = nullptr;
  854. // char aresample_swr_opts[512] = "";
  855. // const AVDictionaryEntry* e = nullptr;
  856. char asrc_args[256];
  857. int ret;
  858. AVBPrint bp;
  859. avfilter_graph_free(&is->agraph);
  860. if (!(is->agraph = avfilter_graph_alloc()))
  861. return AVERROR(ENOMEM);
  862. is->agraph->nb_threads = 0;
  863. /*while ((e = av_dict_get(swr_opts, "", e, AV_DICT_IGNORE_SUFFIX)))
  864. av_strlcatf(aresample_swr_opts, sizeof(aresample_swr_opts), "%s=%s:",
  865. e->key, e->value); if (strlen(aresample_swr_opts))
  866. aresample_swr_opts[strlen(aresample_swr_opts) - 1] = '\0';
  867. av_opt_set(is->agraph, "aresample_swr_opts", aresample_swr_opts, 0);*/
  868. av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
  869. av_channel_layout_describe_bprint(&is->audio_filter_src.ch_layout, &bp);
  870. snprintf(asrc_args,
  871. sizeof(asrc_args),
  872. "sample_rate=%d:sample_fmt=%s:time_base=%d/%d:channel_layout=%s",
  873. is->audio_filter_src.freq,
  874. av_get_sample_fmt_name(is->audio_filter_src.fmt),
  875. 1,
  876. is->audio_filter_src.freq,
  877. bp.str);
  878. ret = avfilter_graph_create_filter(&filt_asrc,
  879. avfilter_get_by_name("abuffer"),
  880. "ffplay_abuffer",
  881. asrc_args,
  882. nullptr,
  883. is->agraph);
  884. if (ret < 0)
  885. goto end;
  886. ret = avfilter_graph_create_filter(&filt_asink,
  887. avfilter_get_by_name("abuffersink"),
  888. "ffplay_abuffersink",
  889. nullptr,
  890. nullptr,
  891. is->agraph);
  892. if (ret < 0)
  893. goto end;
  894. if ((ret = av_opt_set_int_list(filt_asink,
  895. "sample_fmts",
  896. sample_fmts,
  897. AV_SAMPLE_FMT_NONE,
  898. AV_OPT_SEARCH_CHILDREN))
  899. < 0)
  900. goto end;
  901. if ((ret = av_opt_set_int(filt_asink, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
  902. goto end;
  903. if (force_output_format) {
  904. sample_rates[0] = is->audio_filter_src.freq;
  905. // channel_layouts[0] = is->audio_filter_src.channel_layout;
  906. // channels[0] = is->audio_filter_src.channels;
  907. if ((ret = av_opt_set_int(filt_asink, "all_channel_counts", 0, AV_OPT_SEARCH_CHILDREN)) < 0)
  908. goto end;
  909. if ((ret = av_opt_set(filt_asink, "ch_layouts", bp.str, AV_OPT_SEARCH_CHILDREN)) < 0)
  910. goto end;
  911. /*if ((ret = av_opt_set_int_list(filt_asink, "channel_layouts",
  912. channel_layouts, -1, AV_OPT_SEARCH_CHILDREN)) < 0) goto end;*/
  913. /*if ((ret = av_opt_set_int_list(filt_asink, "channel_counts", channels, -1,
  914. AV_OPT_SEARCH_CHILDREN)) < 0) goto end;*/
  915. if ((ret = av_opt_set_int_list(filt_asink,
  916. "sample_rates",
  917. sample_rates,
  918. -1,
  919. AV_OPT_SEARCH_CHILDREN))
  920. < 0)
  921. goto end;
  922. }
  923. if ((ret = configure_filtergraph(is->agraph, afilters, filt_asrc, filt_asink)) < 0)
  924. goto end;
  925. is->in_audio_filter = filt_asrc;
  926. is->out_audio_filter = filt_asink;
  927. end:
  928. if (ret < 0)
  929. avfilter_graph_free(&is->agraph);
  930. av_bprint_finalize(&bp, NULL);
  931. return ret;
  932. }
  933. int configure_video_filters(AVFilterGraph* graph,
  934. VideoState* is,
  935. const char* vfilters,
  936. AVFrame* frame)
  937. {
  938. enum AVPixelFormat pix_fmts[1]; // FF_ARRAY_ELEMS(sdl_texture_format_map)
  939. // char sws_flags_str[512] = "";
  940. char buffersrc_args[256];
  941. int ret;
  942. AVFilterContext *filt_src = nullptr, *filt_out = nullptr, *last_filter = nullptr;
  943. AVCodecParameters* codecpar = is->video_st->codecpar;
  944. AVRational fr = av_guess_frame_rate(is->ic, is->video_st, nullptr);
  945. // const AVDictionaryEntry* e = nullptr;
  946. int nb_pix_fmts = 0;
  947. /*
  948. int i, j;
  949. for (i = 0; i < renderer_info.num_texture_formats; i++) {
  950. for (j = 0; j < FF_ARRAY_ELEMS(sdl_texture_format_map) - 1; j++) {
  951. if (renderer_info.texture_formats[i] ==
  952. sdl_texture_format_map[j].texture_fmt) { pix_fmts[nb_pix_fmts++] =
  953. sdl_texture_format_map[j].format; break;
  954. }
  955. }
  956. }*/
  957. pix_fmts[nb_pix_fmts] = AV_PIX_FMT_NONE;
  958. /*while ((e = av_dict_get(sws_dict, "", e, AV_DICT_IGNORE_SUFFIX))) {
  959. if (!strcmp(e->key, "sws_flags")) {
  960. av_strlcatf(sws_flags_str, sizeof(sws_flags_str), "%s=%s:",
  961. "flags", e->value);
  962. }
  963. else
  964. av_strlcatf(sws_flags_str, sizeof(sws_flags_str), "%s=%s:",
  965. e->key, e->value);
  966. }
  967. if (strlen(sws_flags_str))
  968. sws_flags_str[strlen(sws_flags_str) - 1] = '\0';
  969. graph->scale_sws_opts = av_strdup(sws_flags_str);*/
  970. snprintf(buffersrc_args,
  971. sizeof(buffersrc_args),
  972. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
  973. frame->width,
  974. frame->height,
  975. frame->format,
  976. is->video_st->time_base.num,
  977. is->video_st->time_base.den,
  978. codecpar->sample_aspect_ratio.num,
  979. FFMAX(codecpar->sample_aspect_ratio.den, 1));
  980. if (fr.num && fr.den)
  981. av_strlcatf(buffersrc_args, sizeof(buffersrc_args), ":frame_rate=%d/%d", fr.num, fr.den);
  982. if ((ret = avfilter_graph_create_filter(&filt_src,
  983. avfilter_get_by_name("buffer"),
  984. "ffplay_buffer",
  985. buffersrc_args,
  986. nullptr,
  987. graph))
  988. < 0)
  989. goto fail;
  990. ret = avfilter_graph_create_filter(&filt_out,
  991. avfilter_get_by_name("buffersink"),
  992. "ffplay_buffersink",
  993. nullptr,
  994. nullptr,
  995. graph);
  996. if (ret < 0)
  997. goto fail;
  998. if ((ret = av_opt_set_int_list(filt_out,
  999. "pix_fmts",
  1000. pix_fmts,
  1001. AV_PIX_FMT_NONE,
  1002. AV_OPT_SEARCH_CHILDREN))
  1003. < 0)
  1004. goto fail;
  1005. last_filter = filt_out;
  1006. #if 0
  1007. /* Note: this macro adds a filter before the lastly added filter, so the
  1008. * processing order of the filters is in reverse */
  1009. #define INSERT_FILT(name, arg) \
  1010. do { \
  1011. AVFilterContext* filt_ctx; \
  1012. \
  1013. ret = avfilter_graph_create_filter(&filt_ctx, \
  1014. avfilter_get_by_name(name), \
  1015. "ffplay_" name, \
  1016. arg, \
  1017. nullptr, \
  1018. graph); \
  1019. if (ret < 0) \
  1020. goto fail; \
  1021. \
  1022. ret = avfilter_link(filt_ctx, 0, last_filter, 0); \
  1023. if (ret < 0) \
  1024. goto fail; \
  1025. \
  1026. last_filter = filt_ctx; \
  1027. } while (0)
  1028. if (autorotate) {
  1029. int32_t* displaymatrix = (int32_t*)av_stream_get_side_data(is->video_st, AV_PKT_DATA_DISPLAYMATRIX, nullptr);
  1030. double theta = get_rotation(displaymatrix);
  1031. if (fabs(theta - 90) < 1.0) {
  1032. INSERT_FILT("transpose", "clock");
  1033. }
  1034. else if (fabs(theta - 180) < 1.0) {
  1035. INSERT_FILT("hflip", nullptr);
  1036. INSERT_FILT("vflip", nullptr);
  1037. }
  1038. else if (fabs(theta - 270) < 1.0) {
  1039. INSERT_FILT("transpose", "cclock");
  1040. }
  1041. else if (fabs(theta) > 1.0) {
  1042. char rotate_buf[64];
  1043. snprintf(rotate_buf, sizeof(rotate_buf), "%f*PI/180", theta);
  1044. INSERT_FILT("rotate", rotate_buf);
  1045. }
  1046. }
  1047. #endif
  1048. if ((ret = configure_filtergraph(graph, vfilters, filt_src, last_filter)) < 0)
  1049. goto fail;
  1050. is->in_video_filter = filt_src;
  1051. is->out_video_filter = filt_out;
  1052. fail:
  1053. return ret;
  1054. }
  1055. #if 0
  1056. int audio_open(void* opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams* audio_hw_params)
  1057. {
  1058. //SDL_AudioSpec wanted_spec, spec;
  1059. //const char* env;
  1060. static const int next_nb_channels[] = { 0, 0, 1, 6, 2, 6, 4, 6 };
  1061. static const int next_sample_rates[] = { 0, 44100, 48000, 96000, 192000 };
  1062. //int next_sample_rate_idx = FF_ARRAY_ELEMS(next_sample_rates) - 1;
  1063. /*env = SDL_getenv("SDL_AUDIO_CHANNELS");
  1064. if (env) {
  1065. wanted_nb_channels = atoi(env);
  1066. wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
  1067. }*/
  1068. if (!wanted_channel_layout || wanted_nb_channels != av_get_channel_layout_nb_channels(wanted_channel_layout)) {
  1069. wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
  1070. wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
  1071. }
  1072. wanted_nb_channels = av_get_channel_layout_nb_channels(wanted_channel_layout);
  1073. /*
  1074. wanted_spec.channels = wanted_nb_channels;
  1075. wanted_spec.freq = wanted_sample_rate;
  1076. if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
  1077. av_log(nullptr, AV_LOG_ERROR, "Invalid sample rate or channel count!\n");
  1078. return -1;
  1079. }
  1080. while (next_sample_rate_idx && next_sample_rates[next_sample_rate_idx] >= wanted_spec.freq)
  1081. next_sample_rate_idx--;
  1082. wanted_spec.format = AUDIO_S16SYS;
  1083. wanted_spec.silence = 0;
  1084. wanted_spec.samples = FFMAX(SDL_AUDIO_MIN_BUFFER_SIZE, 2 << av_log2(wanted_spec.freq / SDL_AUDIO_MAX_CALLBACKS_PER_SEC));
  1085. wanted_spec.callback = sdl_audio_callback;
  1086. wanted_spec.userdata = opaque;
  1087. while (!(audio_dev = SDL_OpenAudioDevice(nullptr, 0, &wanted_spec, &spec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_CHANNELS_CHANGE))) {
  1088. av_log(nullptr, AV_LOG_WARNING, "SDL_OpenAudio (%d channels, %d Hz): %s\n",
  1089. wanted_spec.channels, wanted_spec.freq, SDL_GetError());
  1090. wanted_spec.channels = next_nb_channels[FFMIN(7, wanted_spec.channels)];
  1091. if (!wanted_spec.channels) {
  1092. wanted_spec.freq = next_sample_rates[next_sample_rate_idx--];
  1093. wanted_spec.channels = wanted_nb_channels;
  1094. if (!wanted_spec.freq) {
  1095. av_log(nullptr, AV_LOG_ERROR,
  1096. "No more combinations to try, audio open failed\n");
  1097. return -1;
  1098. }
  1099. }
  1100. wanted_channel_layout = av_get_default_channel_layout(wanted_spec.channels);
  1101. }
  1102. if (spec.format != AUDIO_S16SYS) {
  1103. av_log(nullptr, AV_LOG_ERROR,
  1104. "SDL advised audio format %d is not supported!\n", spec.format);
  1105. return -1;
  1106. }
  1107. if (spec.channels != wanted_spec.channels) {
  1108. wanted_channel_layout = av_get_default_channel_layout(spec.channels);
  1109. if (!wanted_channel_layout) {
  1110. av_log(nullptr, AV_LOG_ERROR,
  1111. "SDL advised channel count %d is not supported!\n", spec.channels);
  1112. return -1;
  1113. }
  1114. }*/
  1115. audio_hw_params->fmt = AV_SAMPLE_FMT_S16;
  1116. audio_hw_params->freq = wanted_sample_rate; // spec.freq;
  1117. audio_hw_params->channel_layout.nb_channels = wanted_channel_layout;
  1118. audio_hw_params->channels = wanted_nb_channels; // spec.channels;
  1119. audio_hw_params->frame_size = av_samples_get_buffer_size(nullptr, audio_hw_params->channels, 1, audio_hw_params->fmt, 1);
  1120. audio_hw_params->bytes_per_sec = av_samples_get_buffer_size(nullptr, audio_hw_params->channels, audio_hw_params->freq, audio_hw_params->fmt, 1);
  1121. if (audio_hw_params->bytes_per_sec <= 0 || audio_hw_params->frame_size <= 0) {
  1122. av_log(nullptr, AV_LOG_ERROR, "av_samples_get_buffer_size failed\n");
  1123. return -1;
  1124. }
  1125. return 0;// spec.size;
  1126. }
  1127. #endif
  1128. #endif