packets_sync.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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*) (d->decoder_tid))->join();
  371. d->decoder_tid = nullptr;
  372. packet_queue_flush(d->queue);
  373. }
  374. int decoder_decode_frame(Decoder* d, AVFrame* frame, AVSubtitle* sub)
  375. {
  376. int ret = AVERROR(EAGAIN);
  377. int decoder_reorder_pts = -1;
  378. for (;;) {
  379. if (d->queue->serial == d->pkt_serial) {
  380. do {
  381. if (d->queue->abort_request)
  382. return -1;
  383. switch (d->avctx->codec_type) {
  384. case AVMEDIA_TYPE_VIDEO:
  385. ret = avcodec_receive_frame(d->avctx, frame);
  386. if (ret >= 0) {
  387. if (decoder_reorder_pts == -1) {
  388. frame->pts = frame->best_effort_timestamp;
  389. } else if (!decoder_reorder_pts) {
  390. frame->pts = frame->pkt_dts;
  391. }
  392. }
  393. break;
  394. case AVMEDIA_TYPE_AUDIO:
  395. ret = avcodec_receive_frame(d->avctx, frame);
  396. if (ret >= 0) {
  397. AVRational tb = AVRational{1, frame->sample_rate};
  398. if (frame->pts != AV_NOPTS_VALUE)
  399. frame->pts = av_rescale_q(frame->pts, d->avctx->pkt_timebase, tb);
  400. else if (d->next_pts != AV_NOPTS_VALUE)
  401. frame->pts = av_rescale_q(d->next_pts, d->next_pts_tb, tb);
  402. if (frame->pts != AV_NOPTS_VALUE) {
  403. d->next_pts = frame->pts + frame->nb_samples;
  404. d->next_pts_tb = tb;
  405. }
  406. }
  407. break;
  408. }
  409. if (ret == AVERROR_EOF) {
  410. d->finished = d->pkt_serial;
  411. avcodec_flush_buffers(d->avctx);
  412. return 0;
  413. }
  414. if (ret >= 0)
  415. return 1;
  416. } while (ret != AVERROR(EAGAIN));
  417. }
  418. do {
  419. if (d->queue->nb_packets == 0)
  420. d->empty_queue_cond->wakeAll();
  421. if (d->packet_pending) {
  422. d->packet_pending = 0;
  423. } else {
  424. int old_serial = d->pkt_serial;
  425. if (packet_queue_get(d->queue, d->pkt, 1, &d->pkt_serial) < 0)
  426. return -1;
  427. if (old_serial != d->pkt_serial) {
  428. avcodec_flush_buffers(d->avctx);
  429. d->finished = 0;
  430. d->next_pts = d->start_pts;
  431. d->next_pts_tb = d->start_pts_tb;
  432. }
  433. }
  434. if (d->queue->serial == d->pkt_serial)
  435. break;
  436. av_packet_unref(d->pkt);
  437. } while (1);
  438. if (d->avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  439. int got_frame = 0;
  440. ret = avcodec_decode_subtitle2(d->avctx, sub, &got_frame, d->pkt);
  441. if (ret < 0) {
  442. ret = AVERROR(EAGAIN);
  443. } else {
  444. if (got_frame && !d->pkt->data) {
  445. d->packet_pending = 1;
  446. }
  447. ret = got_frame ? 0 : (d->pkt->data ? AVERROR(EAGAIN) : AVERROR_EOF);
  448. }
  449. av_packet_unref(d->pkt);
  450. } else {
  451. if (avcodec_send_packet(d->avctx, d->pkt) == AVERROR(EAGAIN)) {
  452. av_log(d->avctx,
  453. AV_LOG_ERROR,
  454. "Receive_frame and send_packet both returned EAGAIN, which is "
  455. "an API violation.\n");
  456. d->packet_pending = 1;
  457. } else {
  458. av_packet_unref(d->pkt);
  459. }
  460. }
  461. }
  462. }
  463. void get_file_info(const char* filename, int64_t& duration)
  464. {
  465. AVFormatContext* pFormatCtx = avformat_alloc_context();
  466. if (avformat_open_input(&pFormatCtx, filename, NULL, NULL) == 0) {
  467. if (pFormatCtx->duration < 0)
  468. avformat_find_stream_info(pFormatCtx, NULL);
  469. duration = pFormatCtx->duration;
  470. }
  471. // etc
  472. avformat_close_input(&pFormatCtx);
  473. avformat_free_context(pFormatCtx);
  474. }
  475. void get_duration_time(
  476. const int64_t duration_us, int64_t& hours, int64_t& mins, int64_t& secs, int64_t& us)
  477. {
  478. int64_t duration = duration_us + (duration_us <= INT64_MAX - 5000 ? 5000 : 0);
  479. duration = duration < 0 ? 0 : duration;
  480. secs = duration / AV_TIME_BASE;
  481. us = duration % AV_TIME_BASE;
  482. us = (100 * us) / AV_TIME_BASE;
  483. mins = secs / 60;
  484. secs %= 60;
  485. hours = mins / 60;
  486. mins %= 60;
  487. }
  488. double get_clock(Clock* c)
  489. {
  490. if (*c->queue_serial != c->serial)
  491. return NAN;
  492. if (c->paused) {
  493. return c->pts;
  494. } else {
  495. double time = av_gettime_relative() / 1000000.0;
  496. return c->pts_drift + time - (time - c->last_updated) * (1.0 - c->speed);
  497. }
  498. }
  499. void set_clock_at(Clock* c, double pts, int serial, double time)
  500. {
  501. c->pts = pts;
  502. c->last_updated = time;
  503. c->pts_drift = c->pts - time;
  504. c->serial = serial;
  505. }
  506. void set_clock(Clock* c, double pts, int serial)
  507. {
  508. double time = av_gettime_relative() / 1000000.0;
  509. set_clock_at(c, pts, serial, time);
  510. }
  511. void set_clock_speed(Clock* c, double speed)
  512. {
  513. set_clock(c, get_clock(c), c->serial);
  514. c->speed = speed;
  515. }
  516. void init_clock(Clock* c, int* queue_serial)
  517. {
  518. c->speed = 1.0;
  519. c->paused = 0;
  520. c->queue_serial = queue_serial;
  521. set_clock(c, NAN, -1);
  522. }
  523. void sync_clock_to_slave(Clock* c, Clock* slave)
  524. {
  525. double clock = get_clock(c);
  526. double slave_clock = get_clock(slave);
  527. if (!isnan(slave_clock) && (isnan(clock) || fabs(clock - slave_clock) > AV_NOSYNC_THRESHOLD))
  528. set_clock(c, slave_clock, slave->serial);
  529. }
  530. int stream_has_enough_packets(AVStream* st, int stream_id, PacketQueue* queue)
  531. {
  532. return stream_id < 0 || queue->abort_request || (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
  533. || queue->nb_packets > MIN_FRAMES
  534. && (!queue->duration || av_q2d(st->time_base) * queue->duration > 1.0);
  535. }
  536. int is_realtime(AVFormatContext* s)
  537. {
  538. if (!strcmp(s->iformat->name, "rtp") || !strcmp(s->iformat->name, "rtsp")
  539. || !strcmp(s->iformat->name, "sdp"))
  540. return 1;
  541. if (s->pb && (!strncmp(s->url, "rtp:", 4) || !strncmp(s->url, "udp:", 4)))
  542. return 1;
  543. return 0;
  544. }
  545. int get_master_sync_type(VideoState* is)
  546. {
  547. if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
  548. if (is->video_st)
  549. return AV_SYNC_VIDEO_MASTER;
  550. else
  551. return AV_SYNC_AUDIO_MASTER;
  552. } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
  553. if (is->audio_st)
  554. return AV_SYNC_AUDIO_MASTER;
  555. else
  556. return AV_SYNC_EXTERNAL_CLOCK;
  557. } else {
  558. return AV_SYNC_EXTERNAL_CLOCK;
  559. }
  560. }
  561. /* get the current master clock value */
  562. double get_master_clock(VideoState* is)
  563. {
  564. double val;
  565. switch (get_master_sync_type(is)) {
  566. case AV_SYNC_VIDEO_MASTER:
  567. val = get_clock(&is->vidclk);
  568. break;
  569. case AV_SYNC_AUDIO_MASTER:
  570. val = get_clock(&is->audclk);
  571. break;
  572. default:
  573. val = get_clock(&is->extclk);
  574. break;
  575. }
  576. return val;
  577. }
  578. void check_external_clock_speed(VideoState* is)
  579. {
  580. if ((is->video_stream >= 0 && is->videoq.nb_packets <= EXTERNAL_CLOCK_MIN_FRAMES)
  581. || (is->audio_stream >= 0 && is->audioq.nb_packets <= EXTERNAL_CLOCK_MIN_FRAMES)) {
  582. set_clock_speed(&is->extclk,
  583. FFMAX(EXTERNAL_CLOCK_SPEED_MIN,
  584. is->extclk.speed - EXTERNAL_CLOCK_SPEED_STEP));
  585. } else if ((is->video_stream < 0 || is->videoq.nb_packets > EXTERNAL_CLOCK_MAX_FRAMES)
  586. && (is->audio_stream < 0 || is->audioq.nb_packets > EXTERNAL_CLOCK_MAX_FRAMES)) {
  587. set_clock_speed(&is->extclk,
  588. FFMIN(EXTERNAL_CLOCK_SPEED_MAX,
  589. is->extclk.speed + EXTERNAL_CLOCK_SPEED_STEP));
  590. } else {
  591. double speed = is->extclk.speed;
  592. if (speed != 1.0)
  593. set_clock_speed(&is->extclk,
  594. speed + EXTERNAL_CLOCK_SPEED_STEP * (1.0 - speed) / fabs(1.0 - speed));
  595. }
  596. }
  597. /* seek in the stream */
  598. void stream_seek(VideoState* is, int64_t pos, int64_t rel, int seek_by_bytes)
  599. {
  600. if (!is->seek_req) {
  601. is->seek_pos = pos;
  602. is->seek_rel = rel;
  603. is->seek_flags &= ~AVSEEK_FLAG_BYTE;
  604. if (seek_by_bytes)
  605. is->seek_flags |= AVSEEK_FLAG_BYTE;
  606. is->seek_req = 1;
  607. // SDL_CondSignal(is->continue_read_thread);
  608. is->continue_read_thread->wakeAll();
  609. }
  610. }
  611. /* pause or resume the video */
  612. // void stream_toggle_pause(VideoState* is, bool pause)
  613. //{
  614. // if (is->paused) {
  615. // is->frame_timer += av_gettime_relative() / 1000000.0 -
  616. //is->vidclk.last_updated; if (is->read_pause_return != AVERROR(ENOSYS)) {
  617. // is->vidclk.paused = 0;
  618. // }
  619. // set_clock(&is->vidclk, get_clock(&is->vidclk),
  620. //is->vidclk.serial);
  621. // }
  622. // set_clock(&is->extclk, get_clock(&is->extclk), is->extclk.serial);
  623. // is->paused = is->audclk.paused = is->vidclk.paused = is->extclk.paused =
  624. //pause; // !is->paused; is->step = 0;
  625. //}
  626. void toggle_pause(VideoState* is, bool pause)
  627. {
  628. if (is->paused) {
  629. is->frame_timer += av_gettime_relative() / 1000000.0 - is->vidclk.last_updated;
  630. if (is->read_pause_return != AVERROR(ENOSYS)) {
  631. is->vidclk.paused = 0;
  632. }
  633. set_clock(&is->vidclk, get_clock(&is->vidclk), is->vidclk.serial);
  634. }
  635. set_clock(&is->extclk, get_clock(&is->extclk), is->extclk.serial);
  636. is->paused = is->audclk.paused = is->vidclk.paused = is->extclk.paused = pause; // !is->paused;
  637. is->step = 0;
  638. }
  639. void toggle_mute(VideoState* is, bool mute)
  640. {
  641. bool muted = !!is->muted;
  642. if (muted != mute) {
  643. is->muted = mute;
  644. }
  645. }
  646. void update_volume(VideoState* is, int sign, double step)
  647. {
  648. double volume_level = is->audio_volume
  649. ? (20 * log(is->audio_volume / (double) SDL_MIX_MAXVOLUME) / log(10))
  650. : -1000.0;
  651. int new_volume = lrint(SDL_MIX_MAXVOLUME * pow(10.0, (volume_level + sign * step) / 20.0));
  652. is->audio_volume = av_clip(is->audio_volume == new_volume ? (is->audio_volume + sign)
  653. : new_volume,
  654. 0,
  655. SDL_MIX_MAXVOLUME);
  656. }
  657. void step_to_next_frame(VideoState* is)
  658. {
  659. /* if the stream is paused unpause it, then step */
  660. if (is->paused)
  661. toggle_pause(is, !is->paused);
  662. is->step = 1;
  663. }
  664. double compute_target_delay(double delay, VideoState* is)
  665. {
  666. double sync_threshold, diff = 0;
  667. /* update delay to follow master synchronisation source */
  668. if (get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER) {
  669. /* if video is slave, we try to correct big delays by
  670. duplicating or deleting a frame */
  671. diff = get_clock(&is->vidclk) - get_master_clock(is);
  672. /* skip or repeat frame. We take into account the
  673. delay to compute the threshold. I still don't know
  674. if it is the best guess */
  675. sync_threshold = FFMAX(AV_SYNC_THRESHOLD_MIN, FFMIN(AV_SYNC_THRESHOLD_MAX, delay));
  676. if (!isnan(diff) && fabs(diff) < is->max_frame_duration) {
  677. if (diff <= -sync_threshold)
  678. delay = FFMAX(0, delay + diff);
  679. else if (diff >= sync_threshold && delay > AV_SYNC_FRAMEDUP_THRESHOLD)
  680. delay = delay + diff;
  681. else if (diff >= sync_threshold)
  682. delay = 2 * delay;
  683. }
  684. }
  685. av_log(nullptr, AV_LOG_TRACE, "video: delay=%0.3f A-V=%f\n", delay, -diff);
  686. return delay;
  687. }
  688. double vp_duration(VideoState* is, Frame* vp, Frame* nextvp)
  689. {
  690. if (vp->serial == nextvp->serial) {
  691. double duration = nextvp->pts - vp->pts;
  692. if (isnan(duration) || duration <= 0 || duration > is->max_frame_duration)
  693. return vp->duration;
  694. else
  695. return duration;
  696. }
  697. return 0.0;
  698. }
  699. void update_video_pts(VideoState* is, double pts, int64_t pos, int serial)
  700. {
  701. /* update current video pts */
  702. set_clock(&is->vidclk, pts, serial);
  703. sync_clock_to_slave(&is->extclk, &is->vidclk);
  704. }
  705. #if PRINT_PACKETQUEUE_INFO
  706. void print_state_info(VideoState* is)
  707. {
  708. if (is) {
  709. PacketQueue* pPacket = &is->videoq;
  710. qDebug("[VideoState] V PacketQueue[%p](nb_packets:%d,size:%d,dur:%lld, "
  711. "abort:%d, serial:%d)",
  712. pPacket,
  713. pPacket->nb_packets,
  714. pPacket->size,
  715. pPacket->duration,
  716. pPacket->abort_request,
  717. pPacket->serial);
  718. pPacket = &is->audioq;
  719. qDebug("[VideoState] A PacketQueue[%p](nb_packets:%d,size:%d,dur:%lld, "
  720. "abort:%d, serial:%d)",
  721. pPacket,
  722. pPacket->nb_packets,
  723. pPacket->size,
  724. pPacket->duration,
  725. pPacket->abort_request,
  726. pPacket->serial);
  727. pPacket = &is->subtitleq;
  728. qDebug("[VideoState] S PacketQueue[%p](nb_packets:%d,size:%d,dur:%lld, "
  729. "abort:%d, serial:%d)",
  730. pPacket,
  731. pPacket->nb_packets,
  732. pPacket->size,
  733. pPacket->duration,
  734. pPacket->abort_request,
  735. pPacket->serial);
  736. /*qDebug("[VideoState]FrameQueue(v:%p,a:%p,s:%p)",
  737. &is->pictq, &is->sampq, &is->subpq);
  738. qDebug("[VideoState]Decoder(v:%p,a:%p,s:%p)",
  739. &is->viddec, &is->auddec, &is->subdec);
  740. qDebug("[VideoState]Clock(v:%p,a:%p,s:%p)",
  741. &is->vidclk, &is->audclk, &is->extclk);*/
  742. }
  743. }
  744. #endif
  745. #if USE_AVFILTER_AUDIO
  746. void set_audio_playspeed(VideoState* is, double value)
  747. {
  748. if (value < 0 || value > 4)
  749. return;
  750. if (is->audio_speed == value)
  751. return;
  752. is->audio_speed = value;
  753. const size_t len = 32;
  754. if (!is->afilters)
  755. is->afilters = (char*) av_malloc(len);
  756. if (value <= 0.5) {
  757. snprintf(is->afilters, len, "atempo=0.5,");
  758. char tmp[128];
  759. snprintf(tmp, sizeof(tmp), "atempo=%lf", value / 0.5);
  760. // strncat(is->afilters, tmp, len - strlen(is->afilters) - 1);
  761. strncat_s(is->afilters, len, tmp, len - strlen(is->afilters) - 1);
  762. } else if (value <= 2.0) {
  763. snprintf(is->afilters, len, "atempo=%lf", value);
  764. } else {
  765. snprintf(is->afilters, len, "atempo=2.0,");
  766. char tmp[128];
  767. snprintf(tmp, sizeof(tmp), "atempo=%lf", value / 2.0);
  768. // strncat(is->afilters, tmp, len - strlen(is->afilters) - 1);
  769. strncat_s(is->afilters, len, tmp, len - strlen(is->afilters) - 1);
  770. }
  771. qDebug("changing audio filters to :%s", is->afilters);
  772. #if USE_AVFILTER_VIDEO
  773. set_video_playspeed(is);
  774. #endif
  775. is->audio_clock_old = is->audio_clock;
  776. is->req_afilter_reconfigure = 1;
  777. }
  778. void set_video_playspeed(VideoState* is)
  779. {
  780. double speed = is->audio_speed;
  781. size_t len = 32;
  782. if (!is->vfilters)
  783. is->vfilters = (char*) av_malloc(len);
  784. snprintf(is->vfilters, len, "setpts=%.4lf*PTS", 1.0 / speed);
  785. is->req_vfilter_reconfigure = 1;
  786. qDebug("changing video filters to :%s", is->vfilters);
  787. }
  788. int cmp_audio_fmts(enum AVSampleFormat fmt1,
  789. int64_t channel_count1,
  790. enum AVSampleFormat fmt2,
  791. int64_t channel_count2)
  792. {
  793. /* If channel count == 1, planar and non-planar formats are the same */
  794. if (channel_count1 == 1 && channel_count2 == 1)
  795. return av_get_packed_sample_fmt(fmt1) != av_get_packed_sample_fmt(fmt2);
  796. else
  797. return channel_count1 != channel_count2 || fmt1 != fmt2;
  798. }
  799. // int64_t get_valid_channel_layout(int64_t channel_layout, int channels)
  800. //{
  801. // if (channel_layout && av_get_channel_layout_nb_channels(channel_layout)
  802. //== channels) return channel_layout; else return 0;
  803. //}
  804. int configure_filtergraph(AVFilterGraph* graph,
  805. const char* filtergraph,
  806. AVFilterContext* source_ctx,
  807. AVFilterContext* sink_ctx)
  808. {
  809. int ret;
  810. int nb_filters = graph->nb_filters;
  811. AVFilterInOut *outputs = nullptr, *inputs = nullptr;
  812. if (filtergraph) {
  813. outputs = avfilter_inout_alloc();
  814. inputs = avfilter_inout_alloc();
  815. if (!outputs || !inputs) {
  816. ret = AVERROR(ENOMEM);
  817. goto fail;
  818. }
  819. outputs->name = av_strdup("in");
  820. outputs->filter_ctx = source_ctx;
  821. outputs->pad_idx = 0;
  822. outputs->next = nullptr;
  823. inputs->name = av_strdup("out");
  824. inputs->filter_ctx = sink_ctx;
  825. inputs->pad_idx = 0;
  826. inputs->next = nullptr;
  827. if ((ret = avfilter_graph_parse_ptr(graph, filtergraph, &inputs, &outputs, nullptr)) < 0)
  828. goto fail;
  829. } else {
  830. if ((ret = avfilter_link(source_ctx, 0, sink_ctx, 0)) < 0)
  831. goto fail;
  832. }
  833. /* Reorder the filters to ensure that inputs of the custom filters are merged
  834. * first */
  835. for (unsigned int i = 0; i < graph->nb_filters - nb_filters; i++)
  836. FFSWAP(AVFilterContext*, graph->filters[i], graph->filters[i + nb_filters]);
  837. ret = avfilter_graph_config(graph, nullptr);
  838. fail:
  839. avfilter_inout_free(&outputs);
  840. avfilter_inout_free(&inputs);
  841. return ret;
  842. }
  843. int configure_audio_filters(VideoState* is, const char* afilters, int force_output_format)
  844. {
  845. static const enum AVSampleFormat sample_fmts[] = {AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE};
  846. int sample_rates[2] = {0, -1};
  847. // int64_t channel_layouts[2] = { 0, -1 };
  848. // AVChannelLayout channel_layouts[2] = {};
  849. // int channels[2] = { 0, -1 };
  850. AVFilterContext *filt_asrc = nullptr, *filt_asink = nullptr;
  851. // char aresample_swr_opts[512] = "";
  852. // const AVDictionaryEntry* e = nullptr;
  853. char asrc_args[256];
  854. int ret;
  855. AVBPrint bp;
  856. avfilter_graph_free(&is->agraph);
  857. if (!(is->agraph = avfilter_graph_alloc()))
  858. return AVERROR(ENOMEM);
  859. is->agraph->nb_threads = 0;
  860. /*while ((e = av_dict_get(swr_opts, "", e, AV_DICT_IGNORE_SUFFIX)))
  861. av_strlcatf(aresample_swr_opts, sizeof(aresample_swr_opts), "%s=%s:",
  862. e->key, e->value); if (strlen(aresample_swr_opts))
  863. aresample_swr_opts[strlen(aresample_swr_opts) - 1] = '\0';
  864. av_opt_set(is->agraph, "aresample_swr_opts", aresample_swr_opts, 0);*/
  865. av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
  866. av_channel_layout_describe_bprint(&is->audio_filter_src.ch_layout, &bp);
  867. snprintf(asrc_args,
  868. sizeof(asrc_args),
  869. "sample_rate=%d:sample_fmt=%s:time_base=%d/%d:channel_layout=%s",
  870. is->audio_filter_src.freq,
  871. av_get_sample_fmt_name(is->audio_filter_src.fmt),
  872. 1,
  873. is->audio_filter_src.freq,
  874. bp.str);
  875. ret = avfilter_graph_create_filter(&filt_asrc,
  876. avfilter_get_by_name("abuffer"),
  877. "ffplay_abuffer",
  878. asrc_args,
  879. nullptr,
  880. is->agraph);
  881. if (ret < 0)
  882. goto end;
  883. ret = avfilter_graph_create_filter(&filt_asink,
  884. avfilter_get_by_name("abuffersink"),
  885. "ffplay_abuffersink",
  886. nullptr,
  887. nullptr,
  888. is->agraph);
  889. if (ret < 0)
  890. goto end;
  891. if ((ret = av_opt_set_int_list(filt_asink,
  892. "sample_fmts",
  893. sample_fmts,
  894. AV_SAMPLE_FMT_NONE,
  895. AV_OPT_SEARCH_CHILDREN))
  896. < 0)
  897. goto end;
  898. if ((ret = av_opt_set_int(filt_asink, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
  899. goto end;
  900. if (force_output_format) {
  901. sample_rates[0] = is->audio_filter_src.freq;
  902. // channel_layouts[0] = is->audio_filter_src.channel_layout;
  903. // channels[0] = is->audio_filter_src.channels;
  904. if ((ret = av_opt_set_int(filt_asink, "all_channel_counts", 0, AV_OPT_SEARCH_CHILDREN)) < 0)
  905. goto end;
  906. if ((ret = av_opt_set(filt_asink, "ch_layouts", bp.str, AV_OPT_SEARCH_CHILDREN)) < 0)
  907. goto end;
  908. /*if ((ret = av_opt_set_int_list(filt_asink, "channel_layouts",
  909. channel_layouts, -1, AV_OPT_SEARCH_CHILDREN)) < 0) goto end;*/
  910. /*if ((ret = av_opt_set_int_list(filt_asink, "channel_counts", channels, -1,
  911. AV_OPT_SEARCH_CHILDREN)) < 0) goto end;*/
  912. if ((ret = av_opt_set_int_list(filt_asink,
  913. "sample_rates",
  914. sample_rates,
  915. -1,
  916. AV_OPT_SEARCH_CHILDREN))
  917. < 0)
  918. goto end;
  919. }
  920. if ((ret = configure_filtergraph(is->agraph, afilters, filt_asrc, filt_asink)) < 0)
  921. goto end;
  922. is->in_audio_filter = filt_asrc;
  923. is->out_audio_filter = filt_asink;
  924. end:
  925. if (ret < 0)
  926. avfilter_graph_free(&is->agraph);
  927. av_bprint_finalize(&bp, NULL);
  928. return ret;
  929. }
  930. int configure_video_filters(AVFilterGraph* graph,
  931. VideoState* is,
  932. const char* vfilters,
  933. AVFrame* frame)
  934. {
  935. enum AVPixelFormat pix_fmts[1]; // FF_ARRAY_ELEMS(sdl_texture_format_map)
  936. // char sws_flags_str[512] = "";
  937. char buffersrc_args[256];
  938. int ret;
  939. AVFilterContext *filt_src = nullptr, *filt_out = nullptr, *last_filter = nullptr;
  940. AVCodecParameters* codecpar = is->video_st->codecpar;
  941. AVRational fr = av_guess_frame_rate(is->ic, is->video_st, nullptr);
  942. // const AVDictionaryEntry* e = nullptr;
  943. int nb_pix_fmts = 0;
  944. /*
  945. int i, j;
  946. for (i = 0; i < renderer_info.num_texture_formats; i++) {
  947. for (j = 0; j < FF_ARRAY_ELEMS(sdl_texture_format_map) - 1; j++) {
  948. if (renderer_info.texture_formats[i] ==
  949. sdl_texture_format_map[j].texture_fmt) { pix_fmts[nb_pix_fmts++] =
  950. sdl_texture_format_map[j].format; break;
  951. }
  952. }
  953. }*/
  954. pix_fmts[nb_pix_fmts] = AV_PIX_FMT_NONE;
  955. /*while ((e = av_dict_get(sws_dict, "", e, AV_DICT_IGNORE_SUFFIX))) {
  956. if (!strcmp(e->key, "sws_flags")) {
  957. av_strlcatf(sws_flags_str, sizeof(sws_flags_str), "%s=%s:",
  958. "flags", e->value);
  959. }
  960. else
  961. av_strlcatf(sws_flags_str, sizeof(sws_flags_str), "%s=%s:",
  962. e->key, e->value);
  963. }
  964. if (strlen(sws_flags_str))
  965. sws_flags_str[strlen(sws_flags_str) - 1] = '\0';
  966. graph->scale_sws_opts = av_strdup(sws_flags_str);*/
  967. snprintf(buffersrc_args,
  968. sizeof(buffersrc_args),
  969. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
  970. frame->width,
  971. frame->height,
  972. frame->format,
  973. is->video_st->time_base.num,
  974. is->video_st->time_base.den,
  975. codecpar->sample_aspect_ratio.num,
  976. FFMAX(codecpar->sample_aspect_ratio.den, 1));
  977. if (fr.num && fr.den)
  978. av_strlcatf(buffersrc_args, sizeof(buffersrc_args), ":frame_rate=%d/%d", fr.num, fr.den);
  979. if ((ret = avfilter_graph_create_filter(&filt_src,
  980. avfilter_get_by_name("buffer"),
  981. "ffplay_buffer",
  982. buffersrc_args,
  983. nullptr,
  984. graph))
  985. < 0)
  986. goto fail;
  987. ret = avfilter_graph_create_filter(&filt_out,
  988. avfilter_get_by_name("buffersink"),
  989. "ffplay_buffersink",
  990. nullptr,
  991. nullptr,
  992. graph);
  993. if (ret < 0)
  994. goto fail;
  995. if ((ret = av_opt_set_int_list(filt_out,
  996. "pix_fmts",
  997. pix_fmts,
  998. AV_PIX_FMT_NONE,
  999. AV_OPT_SEARCH_CHILDREN))
  1000. < 0)
  1001. goto fail;
  1002. last_filter = filt_out;
  1003. #if 0
  1004. /* Note: this macro adds a filter before the lastly added filter, so the
  1005. * processing order of the filters is in reverse */
  1006. #define INSERT_FILT(name, arg) \
  1007. do { \
  1008. AVFilterContext* filt_ctx; \
  1009. \
  1010. ret = avfilter_graph_create_filter(&filt_ctx, \
  1011. avfilter_get_by_name(name), \
  1012. "ffplay_" name, \
  1013. arg, \
  1014. nullptr, \
  1015. graph); \
  1016. if (ret < 0) \
  1017. goto fail; \
  1018. \
  1019. ret = avfilter_link(filt_ctx, 0, last_filter, 0); \
  1020. if (ret < 0) \
  1021. goto fail; \
  1022. \
  1023. last_filter = filt_ctx; \
  1024. } while (0)
  1025. if (autorotate) {
  1026. int32_t* displaymatrix = (int32_t*)av_stream_get_side_data(is->video_st, AV_PKT_DATA_DISPLAYMATRIX, nullptr);
  1027. double theta = get_rotation(displaymatrix);
  1028. if (fabs(theta - 90) < 1.0) {
  1029. INSERT_FILT("transpose", "clock");
  1030. }
  1031. else if (fabs(theta - 180) < 1.0) {
  1032. INSERT_FILT("hflip", nullptr);
  1033. INSERT_FILT("vflip", nullptr);
  1034. }
  1035. else if (fabs(theta - 270) < 1.0) {
  1036. INSERT_FILT("transpose", "cclock");
  1037. }
  1038. else if (fabs(theta) > 1.0) {
  1039. char rotate_buf[64];
  1040. snprintf(rotate_buf, sizeof(rotate_buf), "%f*PI/180", theta);
  1041. INSERT_FILT("rotate", rotate_buf);
  1042. }
  1043. }
  1044. #endif
  1045. if ((ret = configure_filtergraph(graph, vfilters, filt_src, last_filter)) < 0)
  1046. goto fail;
  1047. is->in_video_filter = filt_src;
  1048. is->out_video_filter = filt_out;
  1049. fail:
  1050. return ret;
  1051. }
  1052. #if 0
  1053. int audio_open(void* opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams* audio_hw_params)
  1054. {
  1055. //SDL_AudioSpec wanted_spec, spec;
  1056. //const char* env;
  1057. static const int next_nb_channels[] = { 0, 0, 1, 6, 2, 6, 4, 6 };
  1058. static const int next_sample_rates[] = { 0, 44100, 48000, 96000, 192000 };
  1059. //int next_sample_rate_idx = FF_ARRAY_ELEMS(next_sample_rates) - 1;
  1060. /*env = SDL_getenv("SDL_AUDIO_CHANNELS");
  1061. if (env) {
  1062. wanted_nb_channels = atoi(env);
  1063. wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
  1064. }*/
  1065. if (!wanted_channel_layout || wanted_nb_channels != av_get_channel_layout_nb_channels(wanted_channel_layout)) {
  1066. wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
  1067. wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
  1068. }
  1069. wanted_nb_channels = av_get_channel_layout_nb_channels(wanted_channel_layout);
  1070. /*
  1071. wanted_spec.channels = wanted_nb_channels;
  1072. wanted_spec.freq = wanted_sample_rate;
  1073. if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
  1074. av_log(nullptr, AV_LOG_ERROR, "Invalid sample rate or channel count!\n");
  1075. return -1;
  1076. }
  1077. while (next_sample_rate_idx && next_sample_rates[next_sample_rate_idx] >= wanted_spec.freq)
  1078. next_sample_rate_idx--;
  1079. wanted_spec.format = AUDIO_S16SYS;
  1080. wanted_spec.silence = 0;
  1081. wanted_spec.samples = FFMAX(SDL_AUDIO_MIN_BUFFER_SIZE, 2 << av_log2(wanted_spec.freq / SDL_AUDIO_MAX_CALLBACKS_PER_SEC));
  1082. wanted_spec.callback = sdl_audio_callback;
  1083. wanted_spec.userdata = opaque;
  1084. while (!(audio_dev = SDL_OpenAudioDevice(nullptr, 0, &wanted_spec, &spec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_CHANNELS_CHANGE))) {
  1085. av_log(nullptr, AV_LOG_WARNING, "SDL_OpenAudio (%d channels, %d Hz): %s\n",
  1086. wanted_spec.channels, wanted_spec.freq, SDL_GetError());
  1087. wanted_spec.channels = next_nb_channels[FFMIN(7, wanted_spec.channels)];
  1088. if (!wanted_spec.channels) {
  1089. wanted_spec.freq = next_sample_rates[next_sample_rate_idx--];
  1090. wanted_spec.channels = wanted_nb_channels;
  1091. if (!wanted_spec.freq) {
  1092. av_log(nullptr, AV_LOG_ERROR,
  1093. "No more combinations to try, audio open failed\n");
  1094. return -1;
  1095. }
  1096. }
  1097. wanted_channel_layout = av_get_default_channel_layout(wanted_spec.channels);
  1098. }
  1099. if (spec.format != AUDIO_S16SYS) {
  1100. av_log(nullptr, AV_LOG_ERROR,
  1101. "SDL advised audio format %d is not supported!\n", spec.format);
  1102. return -1;
  1103. }
  1104. if (spec.channels != wanted_spec.channels) {
  1105. wanted_channel_layout = av_get_default_channel_layout(spec.channels);
  1106. if (!wanted_channel_layout) {
  1107. av_log(nullptr, AV_LOG_ERROR,
  1108. "SDL advised channel count %d is not supported!\n", spec.channels);
  1109. return -1;
  1110. }
  1111. }*/
  1112. audio_hw_params->fmt = AV_SAMPLE_FMT_S16;
  1113. audio_hw_params->freq = wanted_sample_rate; // spec.freq;
  1114. audio_hw_params->channel_layout.nb_channels = wanted_channel_layout;
  1115. audio_hw_params->channels = wanted_nb_channels; // spec.channels;
  1116. audio_hw_params->frame_size = av_samples_get_buffer_size(nullptr, audio_hw_params->channels, 1, audio_hw_params->fmt, 1);
  1117. 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);
  1118. if (audio_hw_params->bytes_per_sec <= 0 || audio_hw_params->frame_size <= 0) {
  1119. av_log(nullptr, AV_LOG_ERROR, "av_samples_get_buffer_size failed\n");
  1120. return -1;
  1121. }
  1122. return 0;// spec.size;
  1123. }
  1124. #endif
  1125. #endif