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.

1768 lines
51KB

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