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.

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