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.

1866 lines
54KB

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