You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1893 lines
55KB

  1. /*
  2. * FFplay : Simple Media Player based on the ffmpeg libraries
  3. * Copyright (c) 2003 Fabrice Bellard
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. */
  19. #define HAVE_AV_CONFIG_H
  20. #include "avformat.h"
  21. #include "cmdutils.h"
  22. #include <SDL.h>
  23. #include <SDL_thread.h>
  24. #ifdef CONFIG_WIN32
  25. #undef main /* We don't want SDL to override our main() */
  26. #endif
  27. #if defined(__linux__)
  28. #define HAVE_X11
  29. #endif
  30. #ifdef HAVE_X11
  31. #include <X11/Xlib.h>
  32. #endif
  33. //#define DEBUG_SYNC
  34. #define MAX_VIDEOQ_SIZE (5 * 256 * 1024)
  35. #define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
  36. /* SDL audio buffer size, in samples. Should be small to have precise
  37. A/V sync as SDL does not have hardware buffer fullness info. */
  38. #define SDL_AUDIO_BUFFER_SIZE 1024
  39. /* no AV sync correction is done if below the AV sync threshold */
  40. #define AV_SYNC_THRESHOLD 0.08
  41. /* no AV correction is done if too big error */
  42. #define AV_NOSYNC_THRESHOLD 10.0
  43. /* maximum audio speed change to get correct sync */
  44. #define SAMPLE_CORRECTION_PERCENT_MAX 10
  45. /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
  46. #define AUDIO_DIFF_AVG_NB 20
  47. /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
  48. #define SAMPLE_ARRAY_SIZE (2*65536)
  49. typedef struct PacketQueue {
  50. AVPacketList *first_pkt, *last_pkt;
  51. int nb_packets;
  52. int size;
  53. int abort_request;
  54. SDL_mutex *mutex;
  55. SDL_cond *cond;
  56. } PacketQueue;
  57. #define VIDEO_PICTURE_QUEUE_SIZE 1
  58. typedef struct VideoPicture {
  59. double pts; /* presentation time stamp for this picture */
  60. SDL_Overlay *bmp;
  61. int width, height; /* source height & width */
  62. int allocated;
  63. } VideoPicture;
  64. enum {
  65. AV_SYNC_AUDIO_MASTER, /* default choice */
  66. AV_SYNC_VIDEO_MASTER,
  67. AV_SYNC_EXTERNAL_CLOCK, /* synchronize to an external clock */
  68. };
  69. typedef struct VideoState {
  70. SDL_Thread *parse_tid;
  71. SDL_Thread *video_tid;
  72. AVInputFormat *iformat;
  73. int no_background;
  74. int abort_request;
  75. int paused;
  76. int last_paused;
  77. int seek_req;
  78. int64_t seek_pos;
  79. AVFormatContext *ic;
  80. int dtg_active_format;
  81. int audio_stream;
  82. int av_sync_type;
  83. double external_clock; /* external clock base */
  84. int64_t external_clock_time;
  85. double audio_clock;
  86. double audio_diff_cum; /* used for AV difference average computation */
  87. double audio_diff_avg_coef;
  88. double audio_diff_threshold;
  89. int audio_diff_avg_count;
  90. AVStream *audio_st;
  91. PacketQueue audioq;
  92. int audio_hw_buf_size;
  93. /* samples output by the codec. we reserve more space for avsync
  94. compensation */
  95. uint8_t audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2];
  96. int audio_buf_size; /* in bytes */
  97. int audio_buf_index; /* in bytes */
  98. AVPacket audio_pkt;
  99. uint8_t *audio_pkt_data;
  100. int audio_pkt_size;
  101. int show_audio; /* if true, display audio samples */
  102. int16_t sample_array[SAMPLE_ARRAY_SIZE];
  103. int sample_array_index;
  104. int last_i_start;
  105. double frame_timer;
  106. double frame_last_pts;
  107. double frame_last_delay;
  108. double video_clock;
  109. int video_stream;
  110. AVStream *video_st;
  111. PacketQueue videoq;
  112. double video_last_P_pts; /* pts of the last P picture (needed if B
  113. frames are present) */
  114. double video_current_pts; /* current displayed pts (different from
  115. video_clock if frame fifos are used) */
  116. int64_t video_current_pts_time; /* time at which we updated
  117. video_current_pts - used to
  118. have running video pts */
  119. VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
  120. int pictq_size, pictq_rindex, pictq_windex;
  121. SDL_mutex *pictq_mutex;
  122. SDL_cond *pictq_cond;
  123. // QETimer *video_timer;
  124. char filename[1024];
  125. int width, height, xleft, ytop;
  126. } VideoState;
  127. void show_help(void);
  128. static int audio_write_get_buf_size(VideoState *is);
  129. /* options specified by the user */
  130. static AVInputFormat *file_iformat;
  131. static AVImageFormat *image_format;
  132. static const char *input_filename;
  133. static int fs_screen_width;
  134. static int fs_screen_height;
  135. static int screen_width = 640;
  136. static int screen_height = 480;
  137. static int audio_disable;
  138. static int video_disable;
  139. static int display_disable;
  140. static int show_status;
  141. static int av_sync_type = AV_SYNC_AUDIO_MASTER;
  142. static int64_t start_time = AV_NOPTS_VALUE;
  143. static int debug = 0;
  144. /* current context */
  145. static int is_full_screen;
  146. static VideoState *cur_stream;
  147. static int64_t audio_callback_time;
  148. #define FF_ALLOC_EVENT (SDL_USEREVENT)
  149. #define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
  150. #define FF_QUIT_EVENT (SDL_USEREVENT + 2)
  151. SDL_Surface *screen;
  152. /* packet queue handling */
  153. static void packet_queue_init(PacketQueue *q)
  154. {
  155. memset(q, 0, sizeof(PacketQueue));
  156. q->mutex = SDL_CreateMutex();
  157. q->cond = SDL_CreateCond();
  158. }
  159. static void packet_queue_flush(PacketQueue *q)
  160. {
  161. AVPacketList *pkt, *pkt1;
  162. for(pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
  163. pkt1 = pkt->next;
  164. av_free_packet(&pkt->pkt);
  165. }
  166. q->last_pkt = NULL;
  167. q->first_pkt = NULL;
  168. q->nb_packets = 0;
  169. q->size = 0;
  170. }
  171. static void packet_queue_end(PacketQueue *q)
  172. {
  173. packet_queue_flush(q);
  174. SDL_DestroyMutex(q->mutex);
  175. SDL_DestroyCond(q->cond);
  176. }
  177. static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
  178. {
  179. AVPacketList *pkt1;
  180. /* duplicate the packet */
  181. if (av_dup_packet(pkt) < 0)
  182. return -1;
  183. pkt1 = av_malloc(sizeof(AVPacketList));
  184. if (!pkt1)
  185. return -1;
  186. pkt1->pkt = *pkt;
  187. pkt1->next = NULL;
  188. SDL_LockMutex(q->mutex);
  189. if (!q->last_pkt)
  190. q->first_pkt = pkt1;
  191. else
  192. q->last_pkt->next = pkt1;
  193. q->last_pkt = pkt1;
  194. q->nb_packets++;
  195. q->size += pkt1->pkt.size;
  196. /* XXX: should duplicate packet data in DV case */
  197. SDL_CondSignal(q->cond);
  198. SDL_UnlockMutex(q->mutex);
  199. return 0;
  200. }
  201. static void packet_queue_abort(PacketQueue *q)
  202. {
  203. SDL_LockMutex(q->mutex);
  204. q->abort_request = 1;
  205. SDL_CondSignal(q->cond);
  206. SDL_UnlockMutex(q->mutex);
  207. }
  208. /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
  209. static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
  210. {
  211. AVPacketList *pkt1;
  212. int ret;
  213. SDL_LockMutex(q->mutex);
  214. for(;;) {
  215. if (q->abort_request) {
  216. ret = -1;
  217. break;
  218. }
  219. pkt1 = q->first_pkt;
  220. if (pkt1) {
  221. q->first_pkt = pkt1->next;
  222. if (!q->first_pkt)
  223. q->last_pkt = NULL;
  224. q->nb_packets--;
  225. q->size -= pkt1->pkt.size;
  226. *pkt = pkt1->pkt;
  227. av_free(pkt1);
  228. ret = 1;
  229. break;
  230. } else if (!block) {
  231. ret = 0;
  232. break;
  233. } else {
  234. SDL_CondWait(q->cond, q->mutex);
  235. }
  236. }
  237. SDL_UnlockMutex(q->mutex);
  238. return ret;
  239. }
  240. static inline void fill_rectangle(SDL_Surface *screen,
  241. int x, int y, int w, int h, int color)
  242. {
  243. SDL_Rect rect;
  244. rect.x = x;
  245. rect.y = y;
  246. rect.w = w;
  247. rect.h = h;
  248. SDL_FillRect(screen, &rect, color);
  249. }
  250. #if 0
  251. /* draw only the border of a rectangle */
  252. void fill_border(VideoState *s, int x, int y, int w, int h, int color)
  253. {
  254. int w1, w2, h1, h2;
  255. /* fill the background */
  256. w1 = x;
  257. if (w1 < 0)
  258. w1 = 0;
  259. w2 = s->width - (x + w);
  260. if (w2 < 0)
  261. w2 = 0;
  262. h1 = y;
  263. if (h1 < 0)
  264. h1 = 0;
  265. h2 = s->height - (y + h);
  266. if (h2 < 0)
  267. h2 = 0;
  268. fill_rectangle(screen,
  269. s->xleft, s->ytop,
  270. w1, s->height,
  271. color);
  272. fill_rectangle(screen,
  273. s->xleft + s->width - w2, s->ytop,
  274. w2, s->height,
  275. color);
  276. fill_rectangle(screen,
  277. s->xleft + w1, s->ytop,
  278. s->width - w1 - w2, h1,
  279. color);
  280. fill_rectangle(screen,
  281. s->xleft + w1, s->ytop + s->height - h2,
  282. s->width - w1 - w2, h2,
  283. color);
  284. }
  285. #endif
  286. static void video_image_display(VideoState *is)
  287. {
  288. VideoPicture *vp;
  289. float aspect_ratio;
  290. int width, height, x, y;
  291. SDL_Rect rect;
  292. vp = &is->pictq[is->pictq_rindex];
  293. if (vp->bmp) {
  294. /* XXX: use variable in the frame */
  295. if (is->video_st->codec.sample_aspect_ratio.num == 0)
  296. aspect_ratio = 0;
  297. else
  298. aspect_ratio = av_q2d(is->video_st->codec.sample_aspect_ratio)
  299. * is->video_st->codec.width / is->video_st->codec.height;;
  300. if (aspect_ratio <= 0.0)
  301. aspect_ratio = (float)is->video_st->codec.width /
  302. (float)is->video_st->codec.height;
  303. /* if an active format is indicated, then it overrides the
  304. mpeg format */
  305. #if 0
  306. if (is->video_st->codec.dtg_active_format != is->dtg_active_format) {
  307. is->dtg_active_format = is->video_st->codec.dtg_active_format;
  308. printf("dtg_active_format=%d\n", is->dtg_active_format);
  309. }
  310. #endif
  311. #if 0
  312. switch(is->video_st->codec.dtg_active_format) {
  313. case FF_DTG_AFD_SAME:
  314. default:
  315. /* nothing to do */
  316. break;
  317. case FF_DTG_AFD_4_3:
  318. aspect_ratio = 4.0 / 3.0;
  319. break;
  320. case FF_DTG_AFD_16_9:
  321. aspect_ratio = 16.0 / 9.0;
  322. break;
  323. case FF_DTG_AFD_14_9:
  324. aspect_ratio = 14.0 / 9.0;
  325. break;
  326. case FF_DTG_AFD_4_3_SP_14_9:
  327. aspect_ratio = 14.0 / 9.0;
  328. break;
  329. case FF_DTG_AFD_16_9_SP_14_9:
  330. aspect_ratio = 14.0 / 9.0;
  331. break;
  332. case FF_DTG_AFD_SP_4_3:
  333. aspect_ratio = 4.0 / 3.0;
  334. break;
  335. }
  336. #endif
  337. /* XXX: we suppose the screen has a 1.0 pixel ratio */
  338. height = is->height;
  339. width = ((int)rint(height * aspect_ratio)) & -3;
  340. if (width > is->width) {
  341. width = is->width;
  342. height = ((int)rint(width / aspect_ratio)) & -3;
  343. }
  344. x = (is->width - width) / 2;
  345. y = (is->height - height) / 2;
  346. if (!is->no_background) {
  347. /* fill the background */
  348. // fill_border(is, x, y, width, height, QERGB(0x00, 0x00, 0x00));
  349. } else {
  350. is->no_background = 0;
  351. }
  352. rect.x = is->xleft + x;
  353. rect.y = is->xleft + y;
  354. rect.w = width;
  355. rect.h = height;
  356. SDL_DisplayYUVOverlay(vp->bmp, &rect);
  357. } else {
  358. #if 0
  359. fill_rectangle(screen,
  360. is->xleft, is->ytop, is->width, is->height,
  361. QERGB(0x00, 0x00, 0x00));
  362. #endif
  363. }
  364. }
  365. static inline int compute_mod(int a, int b)
  366. {
  367. a = a % b;
  368. if (a >= 0)
  369. return a;
  370. else
  371. return a + b;
  372. }
  373. static void video_audio_display(VideoState *s)
  374. {
  375. int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
  376. int ch, channels, h, h2, bgcolor, fgcolor;
  377. int16_t time_diff;
  378. /* compute display index : center on currently output samples */
  379. channels = s->audio_st->codec.channels;
  380. nb_display_channels = channels;
  381. if (!s->paused) {
  382. n = 2 * channels;
  383. delay = audio_write_get_buf_size(s);
  384. delay /= n;
  385. /* to be more precise, we take into account the time spent since
  386. the last buffer computation */
  387. if (audio_callback_time) {
  388. time_diff = av_gettime() - audio_callback_time;
  389. delay += (time_diff * s->audio_st->codec.sample_rate) / 1000000;
  390. }
  391. delay -= s->width / 2;
  392. if (delay < s->width)
  393. delay = s->width;
  394. i_start = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
  395. s->last_i_start = i_start;
  396. } else {
  397. i_start = s->last_i_start;
  398. }
  399. bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
  400. fill_rectangle(screen,
  401. s->xleft, s->ytop, s->width, s->height,
  402. bgcolor);
  403. fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
  404. /* total height for one channel */
  405. h = s->height / nb_display_channels;
  406. /* graph height / 2 */
  407. h2 = (h * 9) / 20;
  408. for(ch = 0;ch < nb_display_channels; ch++) {
  409. i = i_start + ch;
  410. y1 = s->ytop + ch * h + (h / 2); /* position of center line */
  411. for(x = 0; x < s->width; x++) {
  412. y = (s->sample_array[i] * h2) >> 15;
  413. if (y < 0) {
  414. y = -y;
  415. ys = y1 - y;
  416. } else {
  417. ys = y1;
  418. }
  419. fill_rectangle(screen,
  420. s->xleft + x, ys, 1, y,
  421. fgcolor);
  422. i += channels;
  423. if (i >= SAMPLE_ARRAY_SIZE)
  424. i -= SAMPLE_ARRAY_SIZE;
  425. }
  426. }
  427. fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
  428. for(ch = 1;ch < nb_display_channels; ch++) {
  429. y = s->ytop + ch * h;
  430. fill_rectangle(screen,
  431. s->xleft, y, s->width, 1,
  432. fgcolor);
  433. }
  434. SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
  435. }
  436. /* display the current picture, if any */
  437. static void video_display(VideoState *is)
  438. {
  439. if (is->audio_st && is->show_audio)
  440. video_audio_display(is);
  441. else if (is->video_st)
  442. video_image_display(is);
  443. }
  444. static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque)
  445. {
  446. SDL_Event event;
  447. event.type = FF_REFRESH_EVENT;
  448. event.user.data1 = opaque;
  449. SDL_PushEvent(&event);
  450. return 0; /* 0 means stop timer */
  451. }
  452. /* schedule a video refresh in 'delay' ms */
  453. static void schedule_refresh(VideoState *is, int delay)
  454. {
  455. SDL_AddTimer(delay, sdl_refresh_timer_cb, is);
  456. }
  457. /* get the current audio clock value */
  458. static double get_audio_clock(VideoState *is)
  459. {
  460. double pts;
  461. int hw_buf_size, bytes_per_sec;
  462. pts = is->audio_clock;
  463. hw_buf_size = audio_write_get_buf_size(is);
  464. bytes_per_sec = 0;
  465. if (is->audio_st) {
  466. bytes_per_sec = is->audio_st->codec.sample_rate *
  467. 2 * is->audio_st->codec.channels;
  468. }
  469. if (bytes_per_sec)
  470. pts -= (double)hw_buf_size / bytes_per_sec;
  471. return pts;
  472. }
  473. /* get the current video clock value */
  474. static double get_video_clock(VideoState *is)
  475. {
  476. double delta;
  477. if (is->paused) {
  478. delta = 0;
  479. } else {
  480. delta = (av_gettime() - is->video_current_pts_time) / 1000000.0;
  481. }
  482. return is->video_current_pts + delta;
  483. }
  484. /* get the current external clock value */
  485. static double get_external_clock(VideoState *is)
  486. {
  487. int64_t ti;
  488. ti = av_gettime();
  489. return is->external_clock + ((ti - is->external_clock_time) * 1e-6);
  490. }
  491. /* get the current master clock value */
  492. static double get_master_clock(VideoState *is)
  493. {
  494. double val;
  495. if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
  496. if (is->video_st)
  497. val = get_video_clock(is);
  498. else
  499. val = get_audio_clock(is);
  500. } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
  501. if (is->audio_st)
  502. val = get_audio_clock(is);
  503. else
  504. val = get_video_clock(is);
  505. } else {
  506. val = get_external_clock(is);
  507. }
  508. return val;
  509. }
  510. /* seek in the stream */
  511. static void stream_seek(VideoState *is, int64_t pos)
  512. {
  513. is->seek_pos = pos;
  514. is->seek_req = 1;
  515. }
  516. /* pause or resume the video */
  517. static void stream_pause(VideoState *is)
  518. {
  519. is->paused = !is->paused;
  520. if (is->paused) {
  521. is->video_current_pts = get_video_clock(is);
  522. }
  523. }
  524. /* called to display each frame */
  525. static void video_refresh_timer(void *opaque)
  526. {
  527. VideoState *is = opaque;
  528. VideoPicture *vp;
  529. double actual_delay, delay, sync_threshold, ref_clock, diff;
  530. if (is->video_st) {
  531. if (is->pictq_size == 0) {
  532. /* if no picture, need to wait */
  533. schedule_refresh(is, 40);
  534. } else {
  535. /* dequeue the picture */
  536. vp = &is->pictq[is->pictq_rindex];
  537. /* update current video pts */
  538. is->video_current_pts = vp->pts;
  539. is->video_current_pts_time = av_gettime();
  540. /* compute nominal delay */
  541. delay = vp->pts - is->frame_last_pts;
  542. if (delay <= 0 || delay >= 1.0) {
  543. /* if incorrect delay, use previous one */
  544. delay = is->frame_last_delay;
  545. }
  546. is->frame_last_delay = delay;
  547. is->frame_last_pts = vp->pts;
  548. /* update delay to follow master synchronisation source */
  549. if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) ||
  550. is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
  551. /* if video is slave, we try to correct big delays by
  552. duplicating or deleting a frame */
  553. ref_clock = get_master_clock(is);
  554. diff = vp->pts - ref_clock;
  555. /* skip or repeat frame. We take into account the
  556. delay to compute the threshold. I still don't know
  557. if it is the best guess */
  558. sync_threshold = AV_SYNC_THRESHOLD;
  559. if (delay > sync_threshold)
  560. sync_threshold = delay;
  561. if (fabs(diff) < AV_NOSYNC_THRESHOLD) {
  562. if (diff <= -sync_threshold)
  563. delay = 0;
  564. else if (diff >= sync_threshold)
  565. delay = 2 * delay;
  566. }
  567. }
  568. is->frame_timer += delay;
  569. /* compute the REAL delay (we need to do that to avoid
  570. long term errors */
  571. actual_delay = is->frame_timer - (av_gettime() / 1000000.0);
  572. if (actual_delay < 0.010) {
  573. /* XXX: should skip picture */
  574. actual_delay = 0.010;
  575. }
  576. /* launch timer for next picture */
  577. schedule_refresh(is, (int)(actual_delay * 1000 + 0.5));
  578. #if defined(DEBUG_SYNC)
  579. printf("video: delay=%0.3f actual_delay=%0.3f pts=%0.3f A-V=%f\n",
  580. delay, actual_delay, vp->pts, -diff);
  581. #endif
  582. /* display picture */
  583. video_display(is);
  584. /* update queue size and signal for next picture */
  585. if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
  586. is->pictq_rindex = 0;
  587. SDL_LockMutex(is->pictq_mutex);
  588. is->pictq_size--;
  589. SDL_CondSignal(is->pictq_cond);
  590. SDL_UnlockMutex(is->pictq_mutex);
  591. }
  592. } else if (is->audio_st) {
  593. /* draw the next audio frame */
  594. schedule_refresh(is, 40);
  595. /* if only audio stream, then display the audio bars (better
  596. than nothing, just to test the implementation */
  597. /* display picture */
  598. video_display(is);
  599. } else {
  600. schedule_refresh(is, 100);
  601. }
  602. if (show_status) {
  603. static int64_t last_time;
  604. int64_t cur_time;
  605. int aqsize, vqsize;
  606. double av_diff;
  607. cur_time = av_gettime();
  608. if (!last_time || (cur_time - last_time) >= 500 * 1000) {
  609. aqsize = 0;
  610. vqsize = 0;
  611. if (is->audio_st)
  612. aqsize = is->audioq.size;
  613. if (is->video_st)
  614. vqsize = is->videoq.size;
  615. av_diff = 0;
  616. if (is->audio_st && is->video_st)
  617. av_diff = get_audio_clock(is) - get_video_clock(is);
  618. printf("%7.2f A-V:%7.3f aq=%5dKB vq=%5dKB \r",
  619. get_master_clock(is), av_diff, aqsize / 1024, vqsize / 1024);
  620. fflush(stdout);
  621. last_time = cur_time;
  622. }
  623. }
  624. }
  625. /* allocate a picture (needs to do that in main thread to avoid
  626. potential locking problems */
  627. static void alloc_picture(void *opaque)
  628. {
  629. VideoState *is = opaque;
  630. VideoPicture *vp;
  631. vp = &is->pictq[is->pictq_windex];
  632. if (vp->bmp)
  633. SDL_FreeYUVOverlay(vp->bmp);
  634. #if 0
  635. /* XXX: use generic function */
  636. /* XXX: disable overlay if no hardware acceleration or if RGB format */
  637. switch(is->video_st->codec.pix_fmt) {
  638. case PIX_FMT_YUV420P:
  639. case PIX_FMT_YUV422P:
  640. case PIX_FMT_YUV444P:
  641. case PIX_FMT_YUV422:
  642. case PIX_FMT_YUV410P:
  643. case PIX_FMT_YUV411P:
  644. is_yuv = 1;
  645. break;
  646. default:
  647. is_yuv = 0;
  648. break;
  649. }
  650. #endif
  651. vp->bmp = SDL_CreateYUVOverlay(is->video_st->codec.width,
  652. is->video_st->codec.height,
  653. SDL_YV12_OVERLAY,
  654. screen);
  655. vp->width = is->video_st->codec.width;
  656. vp->height = is->video_st->codec.height;
  657. SDL_LockMutex(is->pictq_mutex);
  658. vp->allocated = 1;
  659. SDL_CondSignal(is->pictq_cond);
  660. SDL_UnlockMutex(is->pictq_mutex);
  661. }
  662. static int queue_picture(VideoState *is, AVFrame *src_frame, double pts)
  663. {
  664. VideoPicture *vp;
  665. int dst_pix_fmt;
  666. AVPicture pict;
  667. /* wait until we have space to put a new picture */
  668. SDL_LockMutex(is->pictq_mutex);
  669. while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&
  670. !is->videoq.abort_request) {
  671. SDL_CondWait(is->pictq_cond, is->pictq_mutex);
  672. }
  673. SDL_UnlockMutex(is->pictq_mutex);
  674. if (is->videoq.abort_request)
  675. return -1;
  676. vp = &is->pictq[is->pictq_windex];
  677. /* alloc or resize hardware picture buffer */
  678. if (!vp->bmp ||
  679. vp->width != is->video_st->codec.width ||
  680. vp->height != is->video_st->codec.height) {
  681. SDL_Event event;
  682. vp->allocated = 0;
  683. /* the allocation must be done in the main thread to avoid
  684. locking problems */
  685. event.type = FF_ALLOC_EVENT;
  686. event.user.data1 = is;
  687. SDL_PushEvent(&event);
  688. /* wait until the picture is allocated */
  689. SDL_LockMutex(is->pictq_mutex);
  690. while (!vp->allocated && !is->videoq.abort_request) {
  691. SDL_CondWait(is->pictq_cond, is->pictq_mutex);
  692. }
  693. SDL_UnlockMutex(is->pictq_mutex);
  694. if (is->videoq.abort_request)
  695. return -1;
  696. }
  697. /* if the frame is not skipped, then display it */
  698. if (vp->bmp) {
  699. /* get a pointer on the bitmap */
  700. SDL_LockYUVOverlay (vp->bmp);
  701. dst_pix_fmt = PIX_FMT_YUV420P;
  702. pict.data[0] = vp->bmp->pixels[0];
  703. pict.data[1] = vp->bmp->pixels[2];
  704. pict.data[2] = vp->bmp->pixels[1];
  705. pict.linesize[0] = vp->bmp->pitches[0];
  706. pict.linesize[1] = vp->bmp->pitches[2];
  707. pict.linesize[2] = vp->bmp->pitches[1];
  708. img_convert(&pict, dst_pix_fmt,
  709. (AVPicture *)src_frame, is->video_st->codec.pix_fmt,
  710. is->video_st->codec.width, is->video_st->codec.height);
  711. /* update the bitmap content */
  712. SDL_UnlockYUVOverlay(vp->bmp);
  713. vp->pts = pts;
  714. /* now we can update the picture count */
  715. if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
  716. is->pictq_windex = 0;
  717. SDL_LockMutex(is->pictq_mutex);
  718. is->pictq_size++;
  719. SDL_UnlockMutex(is->pictq_mutex);
  720. }
  721. return 0;
  722. }
  723. /* compute the exact PTS for the picture if it is omitted in the stream */
  724. static int output_picture2(VideoState *is, AVFrame *src_frame, double pts1)
  725. {
  726. double frame_delay, pts;
  727. pts = pts1;
  728. /* if B frames are present, and if the current picture is a I
  729. or P frame, we use the last pts */
  730. if (is->video_st->codec.has_b_frames &&
  731. src_frame->pict_type != FF_B_TYPE) {
  732. /* use last pts */
  733. pts = is->video_last_P_pts;
  734. /* get the pts for the next I or P frame if present */
  735. is->video_last_P_pts = pts1;
  736. }
  737. if (pts != 0) {
  738. /* update video clock with pts, if present */
  739. is->video_clock = pts;
  740. } else {
  741. pts = is->video_clock;
  742. }
  743. /* update video clock for next frame */
  744. frame_delay = (double)is->video_st->codec.frame_rate_base /
  745. (double)is->video_st->codec.frame_rate;
  746. /* for MPEG2, the frame can be repeated, so we update the
  747. clock accordingly */
  748. if (src_frame->repeat_pict) {
  749. frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
  750. }
  751. is->video_clock += frame_delay;
  752. #if defined(DEBUG_SYNC) && 0
  753. {
  754. int ftype;
  755. if (src_frame->pict_type == FF_B_TYPE)
  756. ftype = 'B';
  757. else if (src_frame->pict_type == FF_I_TYPE)
  758. ftype = 'I';
  759. else
  760. ftype = 'P';
  761. printf("frame_type=%c clock=%0.3f pts=%0.3f\n",
  762. ftype, pts, pts1);
  763. }
  764. #endif
  765. return queue_picture(is, src_frame, pts);
  766. }
  767. static int video_thread(void *arg)
  768. {
  769. VideoState *is = arg;
  770. AVPacket pkt1, *pkt = &pkt1;
  771. int len1, got_picture;
  772. AVFrame *frame= avcodec_alloc_frame();
  773. double pts;
  774. for(;;) {
  775. while (is->paused && !is->videoq.abort_request) {
  776. SDL_Delay(10);
  777. }
  778. if (packet_queue_get(&is->videoq, pkt, 1) < 0)
  779. break;
  780. /* NOTE: ipts is the PTS of the _first_ picture beginning in
  781. this packet, if any */
  782. pts = 0;
  783. if (pkt->pts != AV_NOPTS_VALUE)
  784. pts = (double)pkt->pts / AV_TIME_BASE;
  785. if (is->video_st->codec.codec_id == CODEC_ID_RAWVIDEO) {
  786. avpicture_fill((AVPicture *)frame, pkt->data,
  787. is->video_st->codec.pix_fmt,
  788. is->video_st->codec.width,
  789. is->video_st->codec.height);
  790. frame->pict_type = FF_I_TYPE;
  791. if (output_picture2(is, frame, pts) < 0)
  792. goto the_end;
  793. } else {
  794. len1 = avcodec_decode_video(&is->video_st->codec,
  795. frame, &got_picture,
  796. pkt->data, pkt->size);
  797. if (len1 < 0)
  798. break;
  799. if (got_picture) {
  800. if (output_picture2(is, frame, pts) < 0)
  801. goto the_end;
  802. }
  803. }
  804. av_free_packet(pkt);
  805. }
  806. the_end:
  807. av_free(frame);
  808. return 0;
  809. }
  810. /* copy samples for viewing in editor window */
  811. static void update_sample_display(VideoState *is, short *samples, int samples_size)
  812. {
  813. int size, len, channels;
  814. channels = is->audio_st->codec.channels;
  815. size = samples_size / sizeof(short);
  816. while (size > 0) {
  817. len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
  818. if (len > size)
  819. len = size;
  820. memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
  821. samples += len;
  822. is->sample_array_index += len;
  823. if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
  824. is->sample_array_index = 0;
  825. size -= len;
  826. }
  827. }
  828. /* return the new audio buffer size (samples can be added or deleted
  829. to get better sync if video or external master clock) */
  830. static int synchronize_audio(VideoState *is, short *samples,
  831. int samples_size1, double pts)
  832. {
  833. int n, samples_size;
  834. double ref_clock;
  835. n = 2 * is->audio_st->codec.channels;
  836. samples_size = samples_size1;
  837. /* if not master, then we try to remove or add samples to correct the clock */
  838. if (((is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st) ||
  839. is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
  840. double diff, avg_diff;
  841. int wanted_size, min_size, max_size, nb_samples;
  842. ref_clock = get_master_clock(is);
  843. diff = get_audio_clock(is) - ref_clock;
  844. if (diff < AV_NOSYNC_THRESHOLD) {
  845. is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
  846. if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
  847. /* not enough measures to have a correct estimate */
  848. is->audio_diff_avg_count++;
  849. } else {
  850. /* estimate the A-V difference */
  851. avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
  852. if (fabs(avg_diff) >= is->audio_diff_threshold) {
  853. wanted_size = samples_size + ((int)(diff * is->audio_st->codec.sample_rate) * n);
  854. nb_samples = samples_size / n;
  855. min_size = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
  856. max_size = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
  857. if (wanted_size < min_size)
  858. wanted_size = min_size;
  859. else if (wanted_size > max_size)
  860. wanted_size = max_size;
  861. /* add or remove samples to correction the synchro */
  862. if (wanted_size < samples_size) {
  863. /* remove samples */
  864. samples_size = wanted_size;
  865. } else if (wanted_size > samples_size) {
  866. uint8_t *samples_end, *q;
  867. int nb;
  868. /* add samples */
  869. nb = (samples_size - wanted_size);
  870. samples_end = (uint8_t *)samples + samples_size - n;
  871. q = samples_end + n;
  872. while (nb > 0) {
  873. memcpy(q, samples_end, n);
  874. q += n;
  875. nb -= n;
  876. }
  877. samples_size = wanted_size;
  878. }
  879. }
  880. #if 0
  881. printf("diff=%f adiff=%f sample_diff=%d apts=%0.3f vpts=%0.3f %f\n",
  882. diff, avg_diff, samples_size - samples_size1,
  883. is->audio_clock, is->video_clock, is->audio_diff_threshold);
  884. #endif
  885. }
  886. } else {
  887. /* too big difference : may be initial PTS errors, so
  888. reset A-V filter */
  889. is->audio_diff_avg_count = 0;
  890. is->audio_diff_cum = 0;
  891. }
  892. }
  893. return samples_size;
  894. }
  895. /* decode one audio frame and returns its uncompressed size */
  896. static int audio_decode_frame(VideoState *is, uint8_t *audio_buf, double *pts_ptr)
  897. {
  898. AVPacket *pkt = &is->audio_pkt;
  899. int n, len1, data_size;
  900. double pts;
  901. for(;;) {
  902. /* NOTE: the audio packet can contain several frames */
  903. while (is->audio_pkt_size > 0) {
  904. len1 = avcodec_decode_audio(&is->audio_st->codec,
  905. (int16_t *)audio_buf, &data_size,
  906. is->audio_pkt_data, is->audio_pkt_size);
  907. if (len1 < 0) {
  908. /* if error, we skip the frame */
  909. is->audio_pkt_size = 0;
  910. break;
  911. }
  912. is->audio_pkt_data += len1;
  913. is->audio_pkt_size -= len1;
  914. if (data_size <= 0)
  915. continue;
  916. /* if no pts, then compute it */
  917. pts = is->audio_clock;
  918. *pts_ptr = pts;
  919. n = 2 * is->audio_st->codec.channels;
  920. is->audio_clock += (double)data_size /
  921. (double)(n * is->audio_st->codec.sample_rate);
  922. #if defined(DEBUG_SYNC)
  923. {
  924. static double last_clock;
  925. printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n",
  926. is->audio_clock - last_clock,
  927. is->audio_clock, pts);
  928. last_clock = is->audio_clock;
  929. }
  930. #endif
  931. return data_size;
  932. }
  933. /* free the current packet */
  934. if (pkt->data)
  935. av_free_packet(pkt);
  936. if (is->paused || is->audioq.abort_request) {
  937. return -1;
  938. }
  939. /* read next packet */
  940. if (packet_queue_get(&is->audioq, pkt, 1) < 0)
  941. return -1;
  942. is->audio_pkt_data = pkt->data;
  943. is->audio_pkt_size = pkt->size;
  944. /* if update the audio clock with the pts */
  945. if (pkt->pts != AV_NOPTS_VALUE) {
  946. is->audio_clock = (double)pkt->pts / AV_TIME_BASE;
  947. }
  948. }
  949. }
  950. /* get the current audio output buffer size, in samples. With SDL, we
  951. cannot have a precise information */
  952. static int audio_write_get_buf_size(VideoState *is)
  953. {
  954. return is->audio_hw_buf_size - is->audio_buf_index;
  955. }
  956. /* prepare a new audio buffer */
  957. void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
  958. {
  959. VideoState *is = opaque;
  960. int audio_size, len1;
  961. double pts;
  962. audio_callback_time = av_gettime();
  963. while (len > 0) {
  964. if (is->audio_buf_index >= is->audio_buf_size) {
  965. audio_size = audio_decode_frame(is, is->audio_buf, &pts);
  966. if (audio_size < 0) {
  967. /* if error, just output silence */
  968. is->audio_buf_size = 1024;
  969. memset(is->audio_buf, 0, is->audio_buf_size);
  970. } else {
  971. if (is->show_audio)
  972. update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
  973. audio_size = synchronize_audio(is, (int16_t *)is->audio_buf, audio_size,
  974. pts);
  975. is->audio_buf_size = audio_size;
  976. }
  977. is->audio_buf_index = 0;
  978. }
  979. len1 = is->audio_buf_size - is->audio_buf_index;
  980. if (len1 > len)
  981. len1 = len;
  982. memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
  983. len -= len1;
  984. stream += len1;
  985. is->audio_buf_index += len1;
  986. }
  987. }
  988. /* open a given stream. Return 0 if OK */
  989. static int stream_component_open(VideoState *is, int stream_index)
  990. {
  991. AVFormatContext *ic = is->ic;
  992. AVCodecContext *enc;
  993. AVCodec *codec;
  994. SDL_AudioSpec wanted_spec, spec;
  995. if (stream_index < 0 || stream_index >= ic->nb_streams)
  996. return -1;
  997. enc = &ic->streams[stream_index]->codec;
  998. /* prepare audio output */
  999. if (enc->codec_type == CODEC_TYPE_AUDIO) {
  1000. wanted_spec.freq = enc->sample_rate;
  1001. wanted_spec.format = AUDIO_S16SYS;
  1002. /* hack for AC3. XXX: suppress that */
  1003. if (enc->channels > 2)
  1004. enc->channels = 2;
  1005. wanted_spec.channels = enc->channels;
  1006. wanted_spec.silence = 0;
  1007. wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
  1008. wanted_spec.callback = sdl_audio_callback;
  1009. wanted_spec.userdata = is;
  1010. if (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
  1011. fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
  1012. return -1;
  1013. }
  1014. is->audio_hw_buf_size = spec.size;
  1015. }
  1016. codec = avcodec_find_decoder(enc->codec_id);
  1017. if (!codec ||
  1018. avcodec_open(enc, codec) < 0)
  1019. return -1;
  1020. switch(enc->codec_type) {
  1021. case CODEC_TYPE_AUDIO:
  1022. is->audio_stream = stream_index;
  1023. is->audio_st = ic->streams[stream_index];
  1024. is->audio_buf_size = 0;
  1025. is->audio_buf_index = 0;
  1026. /* init averaging filter */
  1027. is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
  1028. is->audio_diff_avg_count = 0;
  1029. /* since we do not have a precise anough audio fifo fullness,
  1030. we correct audio sync only if larger than this threshold */
  1031. is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / enc->sample_rate;
  1032. memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
  1033. packet_queue_init(&is->audioq);
  1034. SDL_PauseAudio(0);
  1035. break;
  1036. case CODEC_TYPE_VIDEO:
  1037. is->video_stream = stream_index;
  1038. is->video_st = ic->streams[stream_index];
  1039. is->frame_last_delay = 40e-3;
  1040. is->frame_timer = (double)av_gettime() / 1000000.0;
  1041. is->video_current_pts_time = av_gettime();
  1042. packet_queue_init(&is->videoq);
  1043. is->video_tid = SDL_CreateThread(video_thread, is);
  1044. enc->debug= debug;
  1045. break;
  1046. default:
  1047. break;
  1048. }
  1049. return 0;
  1050. }
  1051. static void stream_component_close(VideoState *is, int stream_index)
  1052. {
  1053. AVFormatContext *ic = is->ic;
  1054. AVCodecContext *enc;
  1055. enc = &ic->streams[stream_index]->codec;
  1056. switch(enc->codec_type) {
  1057. case CODEC_TYPE_AUDIO:
  1058. packet_queue_abort(&is->audioq);
  1059. SDL_CloseAudio();
  1060. packet_queue_end(&is->audioq);
  1061. break;
  1062. case CODEC_TYPE_VIDEO:
  1063. packet_queue_abort(&is->videoq);
  1064. /* note: we also signal this mutex to make sure we deblock the
  1065. video thread in all cases */
  1066. SDL_LockMutex(is->pictq_mutex);
  1067. SDL_CondSignal(is->pictq_cond);
  1068. SDL_UnlockMutex(is->pictq_mutex);
  1069. SDL_WaitThread(is->video_tid, NULL);
  1070. packet_queue_end(&is->videoq);
  1071. break;
  1072. default:
  1073. break;
  1074. }
  1075. avcodec_close(enc);
  1076. switch(enc->codec_type) {
  1077. case CODEC_TYPE_AUDIO:
  1078. is->audio_st = NULL;
  1079. is->audio_stream = -1;
  1080. break;
  1081. case CODEC_TYPE_VIDEO:
  1082. is->video_st = NULL;
  1083. is->video_stream = -1;
  1084. break;
  1085. default:
  1086. break;
  1087. }
  1088. }
  1089. void dump_stream_info(AVFormatContext *s)
  1090. {
  1091. if (s->track != 0)
  1092. fprintf(stderr, "Track: %d\n", s->track);
  1093. if (s->title[0] != '\0')
  1094. fprintf(stderr, "Title: %s\n", s->title);
  1095. if (s->author[0] != '\0')
  1096. fprintf(stderr, "Author: %s\n", s->author);
  1097. if (s->album[0] != '\0')
  1098. fprintf(stderr, "Album: %s\n", s->album);
  1099. if (s->year != 0)
  1100. fprintf(stderr, "Year: %d\n", s->year);
  1101. if (s->genre[0] != '\0')
  1102. fprintf(stderr, "Genre: %s\n", s->genre);
  1103. }
  1104. /* since we have only one decoding thread, we can use a global
  1105. variable instead of a thread local variable */
  1106. static VideoState *global_video_state;
  1107. static int decode_interrupt_cb(void)
  1108. {
  1109. return (global_video_state && global_video_state->abort_request);
  1110. }
  1111. /* this thread gets the stream from the disk or the network */
  1112. static int decode_thread(void *arg)
  1113. {
  1114. VideoState *is = arg;
  1115. AVFormatContext *ic;
  1116. int err, i, ret, video_index, audio_index, use_play;
  1117. AVPacket pkt1, *pkt = &pkt1;
  1118. AVFormatParameters params, *ap = &params;
  1119. video_index = -1;
  1120. audio_index = -1;
  1121. is->video_stream = -1;
  1122. is->audio_stream = -1;
  1123. global_video_state = is;
  1124. url_set_interrupt_cb(decode_interrupt_cb);
  1125. memset(ap, 0, sizeof(*ap));
  1126. ap->image_format = image_format;
  1127. ap->initial_pause = 1; /* we force a pause when starting an RTSP
  1128. stream */
  1129. err = av_open_input_file(&ic, is->filename, is->iformat, 0, ap);
  1130. if (err < 0) {
  1131. print_error(is->filename, err);
  1132. ret = -1;
  1133. goto fail;
  1134. }
  1135. is->ic = ic;
  1136. #ifdef CONFIG_NETWORK
  1137. use_play = (ic->iformat == &rtsp_demux);
  1138. #else
  1139. use_play = 0;
  1140. #endif
  1141. if (!use_play) {
  1142. err = av_find_stream_info(ic);
  1143. if (err < 0) {
  1144. fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
  1145. ret = -1;
  1146. goto fail;
  1147. }
  1148. }
  1149. /* if seeking requested, we execute it */
  1150. if (start_time != AV_NOPTS_VALUE) {
  1151. int64_t timestamp;
  1152. timestamp = start_time;
  1153. /* add the stream start time */
  1154. if (ic->start_time != AV_NOPTS_VALUE)
  1155. timestamp += ic->start_time;
  1156. ret = av_seek_frame(ic, -1, timestamp);
  1157. if (ret < 0) {
  1158. fprintf(stderr, "%s: could not seek to position %0.3f\n",
  1159. is->filename, (double)timestamp / AV_TIME_BASE);
  1160. }
  1161. }
  1162. /* now we can begin to play (RTSP stream only) */
  1163. av_read_play(ic);
  1164. if (use_play) {
  1165. err = av_find_stream_info(ic);
  1166. if (err < 0) {
  1167. fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
  1168. ret = -1;
  1169. goto fail;
  1170. }
  1171. }
  1172. for(i = 0; i < ic->nb_streams; i++) {
  1173. AVCodecContext *enc = &ic->streams[i]->codec;
  1174. switch(enc->codec_type) {
  1175. case CODEC_TYPE_AUDIO:
  1176. if (audio_index < 0 && !audio_disable)
  1177. audio_index = i;
  1178. break;
  1179. case CODEC_TYPE_VIDEO:
  1180. if (video_index < 0 && !video_disable)
  1181. video_index = i;
  1182. break;
  1183. default:
  1184. break;
  1185. }
  1186. }
  1187. if (show_status) {
  1188. dump_format(ic, 0, is->filename, 0);
  1189. dump_stream_info(ic);
  1190. }
  1191. /* open the streams */
  1192. if (audio_index >= 0) {
  1193. stream_component_open(is, audio_index);
  1194. }
  1195. if (video_index >= 0) {
  1196. stream_component_open(is, video_index);
  1197. } else {
  1198. if (!display_disable)
  1199. is->show_audio = 1;
  1200. }
  1201. if (is->video_stream < 0 && is->audio_stream < 0) {
  1202. fprintf(stderr, "%s: could not open codecs\n", is->filename);
  1203. ret = -1;
  1204. goto fail;
  1205. }
  1206. for(;;) {
  1207. if (is->abort_request)
  1208. break;
  1209. #ifdef CONFIG_NETWORK
  1210. if (is->paused != is->last_paused) {
  1211. is->last_paused = is->paused;
  1212. if (is->paused)
  1213. av_read_pause(ic);
  1214. else
  1215. av_read_play(ic);
  1216. }
  1217. if (is->paused && ic->iformat == &rtsp_demux) {
  1218. /* wait 10 ms to avoid trying to get another packet */
  1219. /* XXX: horrible */
  1220. SDL_Delay(10);
  1221. continue;
  1222. }
  1223. #endif
  1224. if (is->seek_req) {
  1225. /* XXX: must lock decoder threads */
  1226. if (is->audio_stream >= 0) {
  1227. packet_queue_flush(&is->audioq);
  1228. }
  1229. if (is->video_stream >= 0) {
  1230. packet_queue_flush(&is->videoq);
  1231. }
  1232. ret = av_seek_frame(is->ic, -1, is->seek_pos);
  1233. if (ret < 0) {
  1234. fprintf(stderr, "%s: error while seeking\n", is->ic->filename);
  1235. }
  1236. is->seek_req = 0;
  1237. }
  1238. /* if the queue are full, no need to read more */
  1239. if (is->audioq.size > MAX_AUDIOQ_SIZE ||
  1240. is->videoq.size > MAX_VIDEOQ_SIZE) {
  1241. /* wait 10 ms */
  1242. SDL_Delay(10);
  1243. continue;
  1244. }
  1245. ret = av_read_frame(ic, pkt);
  1246. if (ret < 0) {
  1247. break;
  1248. }
  1249. if (pkt->stream_index == is->audio_stream) {
  1250. packet_queue_put(&is->audioq, pkt);
  1251. } else if (pkt->stream_index == is->video_stream) {
  1252. packet_queue_put(&is->videoq, pkt);
  1253. } else {
  1254. av_free_packet(pkt);
  1255. }
  1256. }
  1257. /* wait until the end */
  1258. while (!is->abort_request) {
  1259. SDL_Delay(100);
  1260. }
  1261. ret = 0;
  1262. fail:
  1263. /* disable interrupting */
  1264. global_video_state = NULL;
  1265. /* close each stream */
  1266. if (is->audio_stream >= 0)
  1267. stream_component_close(is, is->audio_stream);
  1268. if (is->video_stream >= 0)
  1269. stream_component_close(is, is->video_stream);
  1270. if (is->ic) {
  1271. av_close_input_file(is->ic);
  1272. is->ic = NULL; /* safety */
  1273. }
  1274. url_set_interrupt_cb(NULL);
  1275. if (ret != 0) {
  1276. SDL_Event event;
  1277. event.type = FF_QUIT_EVENT;
  1278. event.user.data1 = is;
  1279. SDL_PushEvent(&event);
  1280. }
  1281. return 0;
  1282. }
  1283. static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
  1284. {
  1285. VideoState *is;
  1286. is = av_mallocz(sizeof(VideoState));
  1287. if (!is)
  1288. return NULL;
  1289. pstrcpy(is->filename, sizeof(is->filename), filename);
  1290. is->iformat = iformat;
  1291. if (screen) {
  1292. is->width = screen->w;
  1293. is->height = screen->h;
  1294. }
  1295. is->ytop = 0;
  1296. is->xleft = 0;
  1297. /* start video display */
  1298. is->pictq_mutex = SDL_CreateMutex();
  1299. is->pictq_cond = SDL_CreateCond();
  1300. /* add the refresh timer to draw the picture */
  1301. schedule_refresh(is, 40);
  1302. is->av_sync_type = av_sync_type;
  1303. is->parse_tid = SDL_CreateThread(decode_thread, is);
  1304. if (!is->parse_tid) {
  1305. av_free(is);
  1306. return NULL;
  1307. }
  1308. return is;
  1309. }
  1310. static void stream_close(VideoState *is)
  1311. {
  1312. VideoPicture *vp;
  1313. int i;
  1314. /* XXX: use a special url_shutdown call to abort parse cleanly */
  1315. is->abort_request = 1;
  1316. SDL_WaitThread(is->parse_tid, NULL);
  1317. /* free all pictures */
  1318. for(i=0;i<VIDEO_PICTURE_QUEUE_SIZE; i++) {
  1319. vp = &is->pictq[i];
  1320. if (vp->bmp) {
  1321. SDL_FreeYUVOverlay(vp->bmp);
  1322. vp->bmp = NULL;
  1323. }
  1324. }
  1325. SDL_DestroyMutex(is->pictq_mutex);
  1326. SDL_DestroyCond(is->pictq_cond);
  1327. }
  1328. void stream_cycle_channel(VideoState *is, int codec_type)
  1329. {
  1330. AVFormatContext *ic = is->ic;
  1331. int start_index, stream_index;
  1332. AVStream *st;
  1333. if (codec_type == CODEC_TYPE_VIDEO)
  1334. start_index = is->video_stream;
  1335. else
  1336. start_index = is->audio_stream;
  1337. if (start_index < 0)
  1338. return;
  1339. stream_index = start_index;
  1340. for(;;) {
  1341. if (++stream_index >= is->ic->nb_streams)
  1342. stream_index = 0;
  1343. if (stream_index == start_index)
  1344. return;
  1345. st = ic->streams[stream_index];
  1346. if (st->codec.codec_type == codec_type) {
  1347. /* check that parameters are OK */
  1348. switch(codec_type) {
  1349. case CODEC_TYPE_AUDIO:
  1350. if (st->codec.sample_rate != 0 &&
  1351. st->codec.channels != 0)
  1352. goto the_end;
  1353. break;
  1354. case CODEC_TYPE_VIDEO:
  1355. goto the_end;
  1356. default:
  1357. break;
  1358. }
  1359. }
  1360. }
  1361. the_end:
  1362. stream_component_close(is, start_index);
  1363. stream_component_open(is, stream_index);
  1364. }
  1365. void toggle_full_screen(void)
  1366. {
  1367. int w, h, flags;
  1368. is_full_screen = !is_full_screen;
  1369. if (!fs_screen_width) {
  1370. /* use default SDL method */
  1371. SDL_WM_ToggleFullScreen(screen);
  1372. } else {
  1373. /* use the recorded resolution */
  1374. flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
  1375. if (is_full_screen) {
  1376. w = fs_screen_width;
  1377. h = fs_screen_height;
  1378. flags |= SDL_FULLSCREEN;
  1379. } else {
  1380. w = screen_width;
  1381. h = screen_height;
  1382. flags |= SDL_RESIZABLE;
  1383. }
  1384. screen = SDL_SetVideoMode(w, h, 0, flags);
  1385. cur_stream->width = w;
  1386. cur_stream->height = h;
  1387. }
  1388. }
  1389. void toggle_pause(void)
  1390. {
  1391. if (cur_stream)
  1392. stream_pause(cur_stream);
  1393. }
  1394. void do_exit(void)
  1395. {
  1396. if (cur_stream) {
  1397. stream_close(cur_stream);
  1398. cur_stream = NULL;
  1399. }
  1400. if (show_status)
  1401. printf("\n");
  1402. SDL_Quit();
  1403. exit(0);
  1404. }
  1405. void toggle_audio_display(void)
  1406. {
  1407. if (cur_stream) {
  1408. cur_stream->show_audio = !cur_stream->show_audio;
  1409. }
  1410. }
  1411. /* handle an event sent by the GUI */
  1412. void event_loop(void)
  1413. {
  1414. SDL_Event event;
  1415. double incr, pos, frac;
  1416. for(;;) {
  1417. SDL_WaitEvent(&event);
  1418. switch(event.type) {
  1419. case SDL_KEYDOWN:
  1420. switch(event.key.keysym.sym) {
  1421. case SDLK_ESCAPE:
  1422. case SDLK_q:
  1423. do_exit();
  1424. break;
  1425. case SDLK_f:
  1426. toggle_full_screen();
  1427. break;
  1428. case SDLK_p:
  1429. case SDLK_SPACE:
  1430. toggle_pause();
  1431. break;
  1432. case SDLK_a:
  1433. if (cur_stream)
  1434. stream_cycle_channel(cur_stream, CODEC_TYPE_AUDIO);
  1435. break;
  1436. case SDLK_v:
  1437. if (cur_stream)
  1438. stream_cycle_channel(cur_stream, CODEC_TYPE_VIDEO);
  1439. break;
  1440. case SDLK_w:
  1441. toggle_audio_display();
  1442. break;
  1443. case SDLK_LEFT:
  1444. incr = -10.0;
  1445. goto do_seek;
  1446. case SDLK_RIGHT:
  1447. incr = 10.0;
  1448. goto do_seek;
  1449. case SDLK_UP:
  1450. incr = 60.0;
  1451. goto do_seek;
  1452. case SDLK_DOWN:
  1453. incr = -60.0;
  1454. do_seek:
  1455. if (cur_stream) {
  1456. pos = get_master_clock(cur_stream);
  1457. pos += incr;
  1458. stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE));
  1459. }
  1460. break;
  1461. default:
  1462. break;
  1463. }
  1464. break;
  1465. case SDL_MOUSEBUTTONDOWN:
  1466. if (cur_stream) {
  1467. int ns, hh, mm, ss;
  1468. int tns, thh, tmm, tss;
  1469. tns = cur_stream->ic->duration/1000000LL;
  1470. thh = tns/3600;
  1471. tmm = (tns%3600)/60;
  1472. tss = (tns%60);
  1473. frac = (double)event.button.x/(double)cur_stream->width;
  1474. ns = frac*tns;
  1475. hh = ns/3600;
  1476. mm = (ns%3600)/60;
  1477. ss = (ns%60);
  1478. fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100,
  1479. hh, mm, ss, thh, tmm, tss);
  1480. stream_seek(cur_stream, (int64_t)(cur_stream->ic->start_time+frac*cur_stream->ic->duration));
  1481. }
  1482. break;
  1483. case SDL_VIDEORESIZE:
  1484. if (cur_stream) {
  1485. screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
  1486. SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
  1487. cur_stream->width = event.resize.w;
  1488. cur_stream->height = event.resize.h;
  1489. }
  1490. break;
  1491. case SDL_QUIT:
  1492. case FF_QUIT_EVENT:
  1493. do_exit();
  1494. break;
  1495. case FF_ALLOC_EVENT:
  1496. alloc_picture(event.user.data1);
  1497. break;
  1498. case FF_REFRESH_EVENT:
  1499. video_refresh_timer(event.user.data1);
  1500. break;
  1501. default:
  1502. break;
  1503. }
  1504. }
  1505. }
  1506. void opt_width(const char *arg)
  1507. {
  1508. screen_width = atoi(arg);
  1509. }
  1510. void opt_height(const char *arg)
  1511. {
  1512. screen_height = atoi(arg);
  1513. }
  1514. static void opt_format(const char *arg)
  1515. {
  1516. file_iformat = av_find_input_format(arg);
  1517. if (!file_iformat) {
  1518. fprintf(stderr, "Unknown input format: %s\n", arg);
  1519. exit(1);
  1520. }
  1521. }
  1522. static void opt_image_format(const char *arg)
  1523. {
  1524. AVImageFormat *f;
  1525. for(f = first_image_format; f != NULL; f = f->next) {
  1526. if (!strcmp(arg, f->name))
  1527. break;
  1528. }
  1529. if (!f) {
  1530. fprintf(stderr, "Unknown image format: '%s'\n", arg);
  1531. exit(1);
  1532. }
  1533. image_format = f;
  1534. }
  1535. #ifdef CONFIG_NETWORK
  1536. void opt_rtp_tcp(void)
  1537. {
  1538. /* only tcp protocol */
  1539. rtsp_default_protocols = (1 << RTSP_PROTOCOL_RTP_TCP);
  1540. }
  1541. #endif
  1542. void opt_sync(const char *arg)
  1543. {
  1544. if (!strcmp(arg, "audio"))
  1545. av_sync_type = AV_SYNC_AUDIO_MASTER;
  1546. else if (!strcmp(arg, "video"))
  1547. av_sync_type = AV_SYNC_VIDEO_MASTER;
  1548. else if (!strcmp(arg, "ext"))
  1549. av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
  1550. else
  1551. show_help();
  1552. }
  1553. void opt_seek(const char *arg)
  1554. {
  1555. start_time = parse_date(arg, 1);
  1556. }
  1557. static void opt_debug(const char *arg)
  1558. {
  1559. debug = atoi(arg);
  1560. }
  1561. const OptionDef options[] = {
  1562. { "h", 0, {(void*)show_help}, "show help" },
  1563. { "x", HAS_ARG, {(void*)opt_width}, "force displayed width", "width" },
  1564. { "y", HAS_ARG, {(void*)opt_height}, "force displayed height", "height" },
  1565. #if 0
  1566. /* disabled as SDL/X11 does not support it correctly on application launch */
  1567. { "fs", OPT_BOOL, {(void*)&is_full_screen}, "force full screen" },
  1568. #endif
  1569. { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
  1570. { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
  1571. { "ss", HAS_ARG, {(void*)&opt_seek}, "seek to a given position in seconds", "pos" },
  1572. { "nodisp", OPT_BOOL, {(void*)&display_disable}, "disable graphical display" },
  1573. { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
  1574. { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
  1575. { "stats", OPT_BOOL | OPT_EXPERT, {(void*)&show_status}, "show status", "" },
  1576. { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
  1577. #ifdef CONFIG_NETWORK
  1578. { "rtp_tcp", OPT_EXPERT, {(void*)&opt_rtp_tcp}, "force RTP/TCP protocol usage", "" },
  1579. #endif
  1580. { "sync", HAS_ARG | OPT_EXPERT, {(void*)&opt_sync}, "set audio-video sync. type (type=audio/video/ext)", "type" },
  1581. { NULL, },
  1582. };
  1583. void show_help(void)
  1584. {
  1585. printf("ffplay version " FFMPEG_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
  1586. "usage: ffplay [options] input_file\n"
  1587. "Simple media player\n");
  1588. printf("\n");
  1589. show_help_options(options, "Main options:\n",
  1590. OPT_EXPERT, 0);
  1591. show_help_options(options, "\nAdvanced options:\n",
  1592. OPT_EXPERT, OPT_EXPERT);
  1593. printf("\nWhile playing:\n"
  1594. "q, ESC quit\n"
  1595. "f toggle full screen\n"
  1596. "p, SPC pause\n"
  1597. "a cycle audio channel\n"
  1598. "v cycle video channel\n"
  1599. "w show audio waves\n"
  1600. "left/right seek backward/forward 10 seconds\n"
  1601. "down/up seek backward/forward 1 minute\n"
  1602. "mouse click seek to percentage in file corresponding to fraction of width\n"
  1603. );
  1604. exit(1);
  1605. }
  1606. void parse_arg_file(const char *filename)
  1607. {
  1608. if (!strcmp(filename, "-"))
  1609. filename = "pipe:";
  1610. input_filename = filename;
  1611. }
  1612. /* Called from the main */
  1613. int main(int argc, char **argv)
  1614. {
  1615. int flags, w, h;
  1616. /* register all codecs, demux and protocols */
  1617. av_register_all();
  1618. parse_options(argc, argv, options);
  1619. if (!input_filename)
  1620. show_help();
  1621. if (display_disable) {
  1622. video_disable = 1;
  1623. }
  1624. flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
  1625. #ifndef CONFIG_WIN32
  1626. flags |= SDL_INIT_EVENTTHREAD; /* Not supported on win32 */
  1627. #endif
  1628. if (SDL_Init (flags)) {
  1629. fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
  1630. exit(1);
  1631. }
  1632. if (!display_disable) {
  1633. #ifdef HAVE_X11
  1634. /* save the screen resolution... SDL should allow full screen
  1635. by resizing the window */
  1636. {
  1637. Display *dpy;
  1638. dpy = XOpenDisplay(NULL);
  1639. if (dpy) {
  1640. fs_screen_width = DisplayWidth(dpy, DefaultScreen(dpy));
  1641. fs_screen_height = DisplayHeight(dpy, DefaultScreen(dpy));
  1642. XCloseDisplay(dpy);
  1643. }
  1644. }
  1645. #endif
  1646. flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
  1647. if (is_full_screen && fs_screen_width) {
  1648. w = fs_screen_width;
  1649. h = fs_screen_height;
  1650. flags |= SDL_FULLSCREEN;
  1651. } else {
  1652. w = screen_width;
  1653. h = screen_height;
  1654. flags |= SDL_RESIZABLE;
  1655. }
  1656. screen = SDL_SetVideoMode(w, h, 0, flags);
  1657. if (!screen) {
  1658. fprintf(stderr, "SDL: could not set video mode - exiting\n");
  1659. exit(1);
  1660. }
  1661. SDL_WM_SetCaption("FFplay", "FFplay");
  1662. }
  1663. SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
  1664. SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
  1665. SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
  1666. SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
  1667. cur_stream = stream_open(input_filename, file_iformat);
  1668. event_loop();
  1669. /* never returns */
  1670. return 0;
  1671. }