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.

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