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.

1767 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= avcodec_alloc_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. av_free(frame);
  782. return 0;
  783. }
  784. /* copy samples for viewing in editor window */
  785. static void update_sample_display(VideoState *is, short *samples, int samples_size)
  786. {
  787. int size, len, channels;
  788. channels = is->audio_st->codec.channels;
  789. size = samples_size / sizeof(short);
  790. while (size > 0) {
  791. len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
  792. if (len > size)
  793. len = size;
  794. memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
  795. samples += len;
  796. is->sample_array_index += len;
  797. if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
  798. is->sample_array_index = 0;
  799. size -= len;
  800. }
  801. }
  802. /* return the new audio buffer size (samples can be added or deleted
  803. to get better sync if video or external master clock) */
  804. static int synchronize_audio(VideoState *is, short *samples,
  805. int samples_size1, double pts)
  806. {
  807. int n, samples_size;
  808. double ref_clock;
  809. n = 2 * is->audio_st->codec.channels;
  810. samples_size = samples_size1;
  811. /* if not master, then we try to remove or add samples to correct the clock */
  812. if (((is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st) ||
  813. is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
  814. double diff, avg_diff;
  815. int wanted_size, min_size, max_size, nb_samples;
  816. ref_clock = get_master_clock(is);
  817. diff = get_audio_clock(is) - ref_clock;
  818. if (diff < AV_NOSYNC_THRESHOLD) {
  819. is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
  820. if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
  821. /* not enough measures to have a correct estimate */
  822. is->audio_diff_avg_count++;
  823. } else {
  824. /* estimate the A-V difference */
  825. avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
  826. if (fabs(avg_diff) >= is->audio_diff_threshold) {
  827. wanted_size = samples_size + ((int)(diff * is->audio_st->codec.sample_rate) * n);
  828. nb_samples = samples_size / n;
  829. min_size = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
  830. max_size = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
  831. if (wanted_size < min_size)
  832. wanted_size = min_size;
  833. else if (wanted_size > max_size)
  834. wanted_size = max_size;
  835. /* add or remove samples to correction the synchro */
  836. if (wanted_size < samples_size) {
  837. /* remove samples */
  838. samples_size = wanted_size;
  839. } else if (wanted_size > samples_size) {
  840. uint8_t *samples_end, *q;
  841. int nb;
  842. /* add samples */
  843. nb = (samples_size - wanted_size);
  844. samples_end = (uint8_t *)samples + samples_size - n;
  845. q = samples_end + n;
  846. while (nb > 0) {
  847. memcpy(q, samples_end, n);
  848. q += n;
  849. nb -= n;
  850. }
  851. samples_size = wanted_size;
  852. }
  853. }
  854. #if 0
  855. printf("diff=%f adiff=%f sample_diff=%d apts=%0.3f vpts=%0.3f %f\n",
  856. diff, avg_diff, samples_size - samples_size1,
  857. is->audio_clock, is->video_clock, is->audio_diff_threshold);
  858. #endif
  859. }
  860. } else {
  861. /* too big difference : may be initial PTS errors, so
  862. reset A-V filter */
  863. is->audio_diff_avg_count = 0;
  864. is->audio_diff_cum = 0;
  865. }
  866. }
  867. return samples_size;
  868. }
  869. /* decode one audio frame and returns its uncompressed size */
  870. static int audio_decode_frame(VideoState *is, uint8_t *audio_buf, double *pts_ptr)
  871. {
  872. AVPacket *pkt = &is->audio_pkt;
  873. int len1, data_size;
  874. double pts;
  875. for(;;) {
  876. if (is->paused || is->audioq.abort_request) {
  877. return -1;
  878. }
  879. while (is->audio_pkt_size > 0) {
  880. len1 = avcodec_decode_audio(&is->audio_st->codec,
  881. (int16_t *)audio_buf, &data_size,
  882. is->audio_pkt_data, is->audio_pkt_size);
  883. if (len1 < 0)
  884. break;
  885. is->audio_pkt_data += len1;
  886. is->audio_pkt_size -= len1;
  887. if (data_size > 0) {
  888. pts = 0;
  889. if (is->audio_pkt_ipts != AV_NOPTS_VALUE)
  890. pts = (double)is->audio_pkt_ipts * is->ic->pts_num / is->ic->pts_den;
  891. /* if no pts, then compute it */
  892. if (pts != 0) {
  893. is->audio_clock = pts;
  894. } else {
  895. int n;
  896. n = 2 * is->audio_st->codec.channels;
  897. is->audio_clock += (double)data_size / (double)(n * is->audio_st->codec.sample_rate);
  898. }
  899. #if defined(DEBUG_SYNC)
  900. {
  901. static double last_clock;
  902. printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n",
  903. is->audio_clock - last_clock,
  904. is->audio_clock, pts);
  905. last_clock = is->audio_clock;
  906. }
  907. #endif
  908. *pts_ptr = is->audio_clock;
  909. is->audio_pkt_ipts = AV_NOPTS_VALUE;
  910. /* we got samples : we can exit now */
  911. return data_size;
  912. }
  913. }
  914. /* free previous packet if any */
  915. if (pkt->destruct)
  916. av_free_packet(pkt);
  917. /* read next packet */
  918. if (packet_queue_get(&is->audioq, pkt, 1) < 0)
  919. return -1;
  920. is->audio_pkt_data = pkt->data;
  921. is->audio_pkt_size = pkt->size;
  922. is->audio_pkt_ipts = pkt->pts;
  923. }
  924. }
  925. /* get the current audio output buffer size, in samples. With SDL, we
  926. cannot have a precise information */
  927. static int audio_write_get_buf_size(VideoState *is)
  928. {
  929. return is->audio_hw_buf_size - is->audio_buf_index;
  930. }
  931. /* prepare a new audio buffer */
  932. void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
  933. {
  934. VideoState *is = opaque;
  935. int audio_size, len1;
  936. double pts;
  937. audio_callback_time = av_gettime();
  938. while (len > 0) {
  939. if (is->audio_buf_index >= is->audio_buf_size) {
  940. audio_size = audio_decode_frame(is, is->audio_buf, &pts);
  941. if (audio_size < 0) {
  942. /* if error, just output silence */
  943. is->audio_buf_size = 1024;
  944. memset(is->audio_buf, 0, is->audio_buf_size);
  945. } else {
  946. if (is->show_audio)
  947. update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
  948. audio_size = synchronize_audio(is, (int16_t *)is->audio_buf, audio_size,
  949. pts);
  950. is->audio_buf_size = audio_size;
  951. }
  952. is->audio_buf_index = 0;
  953. }
  954. len1 = is->audio_buf_size - is->audio_buf_index;
  955. if (len1 > len)
  956. len1 = len;
  957. memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
  958. len -= len1;
  959. stream += len1;
  960. is->audio_buf_index += len1;
  961. }
  962. }
  963. /* open a given stream. Return 0 if OK */
  964. static int stream_component_open(VideoState *is, int stream_index)
  965. {
  966. AVFormatContext *ic = is->ic;
  967. AVCodecContext *enc;
  968. AVCodec *codec;
  969. SDL_AudioSpec wanted_spec, spec;
  970. if (stream_index < 0 || stream_index >= ic->nb_streams)
  971. return -1;
  972. enc = &ic->streams[stream_index]->codec;
  973. /* prepare audio output */
  974. if (enc->codec_type == CODEC_TYPE_AUDIO) {
  975. wanted_spec.freq = enc->sample_rate;
  976. wanted_spec.format = AUDIO_S16SYS;
  977. /* hack for AC3. XXX: suppress that */
  978. if (enc->channels > 2)
  979. enc->channels = 2;
  980. wanted_spec.channels = enc->channels;
  981. wanted_spec.silence = 0;
  982. wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
  983. wanted_spec.callback = sdl_audio_callback;
  984. wanted_spec.userdata = is;
  985. if (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
  986. fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
  987. return -1;
  988. }
  989. is->audio_hw_buf_size = spec.size;
  990. }
  991. codec = avcodec_find_decoder(enc->codec_id);
  992. if (!codec ||
  993. avcodec_open(enc, codec) < 0)
  994. return -1;
  995. switch(enc->codec_type) {
  996. case CODEC_TYPE_AUDIO:
  997. is->audio_stream = stream_index;
  998. is->audio_st = ic->streams[stream_index];
  999. is->audio_buf_size = 0;
  1000. is->audio_buf_index = 0;
  1001. is->audio_pkt_size = 0;
  1002. /* init averaging filter */
  1003. is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
  1004. is->audio_diff_avg_count = 0;
  1005. /* since we do not have a precise anough audio fifo fullness,
  1006. we correct audio sync only if larger than this threshold */
  1007. is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / enc->sample_rate;
  1008. memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
  1009. packet_queue_init(&is->audioq);
  1010. SDL_PauseAudio(0);
  1011. break;
  1012. case CODEC_TYPE_VIDEO:
  1013. is->video_stream = stream_index;
  1014. is->video_st = ic->streams[stream_index];
  1015. is->frame_last_delay = 40e-3;
  1016. is->frame_timer = (double)av_gettime() / 1000000.0;
  1017. is->picture_start = 1;
  1018. is->video_current_pts_time = av_gettime();
  1019. packet_queue_init(&is->videoq);
  1020. is->video_tid = SDL_CreateThread(video_thread, is);
  1021. break;
  1022. default:
  1023. break;
  1024. }
  1025. return 0;
  1026. }
  1027. static void stream_component_close(VideoState *is, int stream_index)
  1028. {
  1029. AVFormatContext *ic = is->ic;
  1030. AVCodecContext *enc;
  1031. enc = &ic->streams[stream_index]->codec;
  1032. switch(enc->codec_type) {
  1033. case CODEC_TYPE_AUDIO:
  1034. packet_queue_abort(&is->audioq);
  1035. SDL_CloseAudio();
  1036. packet_queue_end(&is->audioq);
  1037. break;
  1038. case CODEC_TYPE_VIDEO:
  1039. packet_queue_abort(&is->videoq);
  1040. /* note: we also signal this mutex to make sure we deblock the
  1041. video thread in all cases */
  1042. SDL_LockMutex(is->pictq_mutex);
  1043. SDL_CondSignal(is->pictq_cond);
  1044. SDL_UnlockMutex(is->pictq_mutex);
  1045. SDL_WaitThread(is->video_tid, NULL);
  1046. packet_queue_end(&is->videoq);
  1047. break;
  1048. default:
  1049. break;
  1050. }
  1051. avcodec_close(enc);
  1052. switch(enc->codec_type) {
  1053. case CODEC_TYPE_AUDIO:
  1054. is->audio_st = NULL;
  1055. is->audio_stream = -1;
  1056. break;
  1057. case CODEC_TYPE_VIDEO:
  1058. is->video_st = NULL;
  1059. is->video_stream = -1;
  1060. break;
  1061. default:
  1062. break;
  1063. }
  1064. }
  1065. void dump_stream_info(AVFormatContext *s)
  1066. {
  1067. if (s->track != 0)
  1068. fprintf(stderr, "Track: %d\n", s->track);
  1069. if (s->title[0] != '\0')
  1070. fprintf(stderr, "Title: %s\n", s->title);
  1071. if (s->author[0] != '\0')
  1072. fprintf(stderr, "Author: %s\n", s->author);
  1073. if (s->album[0] != '\0')
  1074. fprintf(stderr, "Album: %s\n", s->album);
  1075. if (s->year != 0)
  1076. fprintf(stderr, "Year: %d\n", s->year);
  1077. if (s->genre[0] != '\0')
  1078. fprintf(stderr, "Genre: %s\n", s->genre);
  1079. }
  1080. /* since we have only one decoding thread, we can use a global
  1081. variable instead of a thread local variable */
  1082. static VideoState *global_video_state;
  1083. static int decode_interrupt_cb(void)
  1084. {
  1085. return (global_video_state && global_video_state->abort_request);
  1086. }
  1087. /* this thread gets the stream from the disk or the network */
  1088. static int decode_thread(void *arg)
  1089. {
  1090. VideoState *is = arg;
  1091. AVFormatContext *ic;
  1092. int err, i, ret, video_index, audio_index;
  1093. AVPacket pkt1, *pkt = &pkt1;
  1094. AVFormatParameters params, *ap = &params;
  1095. video_index = -1;
  1096. audio_index = -1;
  1097. is->video_stream = -1;
  1098. is->audio_stream = -1;
  1099. global_video_state = is;
  1100. url_set_interrupt_cb(decode_interrupt_cb);
  1101. memset(ap, 0, sizeof(*ap));
  1102. ap->image_format = image_format;
  1103. err = av_open_input_file(&ic, is->filename, is->iformat, 0, ap);
  1104. if (err < 0) {
  1105. print_error(is->filename, err);
  1106. ret = -1;
  1107. goto fail;
  1108. }
  1109. is->ic = ic;
  1110. err = av_find_stream_info(ic);
  1111. if (err < 0) {
  1112. fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
  1113. ret = -1;
  1114. goto fail;
  1115. }
  1116. for(i = 0; i < ic->nb_streams; i++) {
  1117. AVCodecContext *enc = &ic->streams[i]->codec;
  1118. switch(enc->codec_type) {
  1119. case CODEC_TYPE_AUDIO:
  1120. if (audio_index < 0 && !audio_disable)
  1121. audio_index = i;
  1122. break;
  1123. case CODEC_TYPE_VIDEO:
  1124. if (video_index < 0 && !video_disable)
  1125. video_index = i;
  1126. break;
  1127. default:
  1128. break;
  1129. }
  1130. }
  1131. if (show_status) {
  1132. dump_format(ic, 0, is->filename, 0);
  1133. dump_stream_info(ic);
  1134. }
  1135. /* open the streams */
  1136. if (audio_index >= 0) {
  1137. stream_component_open(is, audio_index);
  1138. }
  1139. if (video_index >= 0) {
  1140. stream_component_open(is, video_index);
  1141. } else {
  1142. if (!display_disable)
  1143. is->show_audio = 1;
  1144. }
  1145. if (is->video_stream < 0 && is->audio_stream < 0) {
  1146. fprintf(stderr, "%s: could not open codecs\n", is->filename);
  1147. ret = -1;
  1148. goto fail;
  1149. }
  1150. for(;;) {
  1151. if (is->abort_request)
  1152. break;
  1153. #ifdef CONFIG_NETWORK
  1154. if (is->paused != is->last_paused) {
  1155. is->last_paused = is->paused;
  1156. if (ic->iformat == &rtsp_demux) {
  1157. if (is->paused)
  1158. rtsp_pause(ic);
  1159. else
  1160. rtsp_resume(ic);
  1161. }
  1162. }
  1163. if (is->paused && ic->iformat == &rtsp_demux) {
  1164. /* wait 10 ms to avoid trying to get another packet */
  1165. /* XXX: horrible */
  1166. SDL_Delay(10);
  1167. continue;
  1168. }
  1169. #endif
  1170. /* if the queue are full, no need to read more */
  1171. if (is->audioq.size > MAX_AUDIOQ_SIZE ||
  1172. is->videoq.size > MAX_VIDEOQ_SIZE) {
  1173. /* wait 10 ms */
  1174. SDL_Delay(10);
  1175. continue;
  1176. }
  1177. ret = av_read_packet(ic, pkt);
  1178. if (ret < 0) {
  1179. break;
  1180. }
  1181. if (pkt->stream_index == is->audio_stream) {
  1182. packet_queue_put(&is->audioq, pkt);
  1183. } else if (pkt->stream_index == is->video_stream) {
  1184. packet_queue_put(&is->videoq, pkt);
  1185. } else {
  1186. av_free_packet(pkt);
  1187. }
  1188. }
  1189. /* wait until the end */
  1190. while (!is->abort_request) {
  1191. SDL_Delay(100);
  1192. }
  1193. ret = 0;
  1194. fail:
  1195. /* disable interrupting */
  1196. global_video_state = NULL;
  1197. /* close each stream */
  1198. if (is->audio_stream >= 0)
  1199. stream_component_close(is, is->audio_stream);
  1200. if (is->video_stream >= 0)
  1201. stream_component_close(is, is->video_stream);
  1202. if (is->ic) {
  1203. av_close_input_file(is->ic);
  1204. is->ic = NULL; /* safety */
  1205. }
  1206. url_set_interrupt_cb(NULL);
  1207. if (ret != 0) {
  1208. SDL_Event event;
  1209. event.type = FF_QUIT_EVENT;
  1210. event.user.data1 = is;
  1211. SDL_PushEvent(&event);
  1212. }
  1213. return 0;
  1214. }
  1215. /* pause or resume the video */
  1216. static void stream_pause(VideoState *is)
  1217. {
  1218. is->paused = !is->paused;
  1219. }
  1220. static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
  1221. {
  1222. VideoState *is;
  1223. is = av_mallocz(sizeof(VideoState));
  1224. if (!is)
  1225. return NULL;
  1226. pstrcpy(is->filename, sizeof(is->filename), filename);
  1227. is->iformat = iformat;
  1228. if (screen) {
  1229. is->width = screen->w;
  1230. is->height = screen->h;
  1231. }
  1232. is->ytop = 0;
  1233. is->xleft = 0;
  1234. /* start video display */
  1235. is->pictq_mutex = SDL_CreateMutex();
  1236. is->pictq_cond = SDL_CreateCond();
  1237. /* add the refresh timer to draw the picture */
  1238. schedule_refresh(is, 40);
  1239. is->av_sync_type = av_sync_type;
  1240. is->parse_tid = SDL_CreateThread(decode_thread, is);
  1241. if (!is->parse_tid) {
  1242. av_free(is);
  1243. return NULL;
  1244. }
  1245. return is;
  1246. }
  1247. static void stream_close(VideoState *is)
  1248. {
  1249. VideoPicture *vp;
  1250. int i;
  1251. /* XXX: use a special url_shutdown call to abort parse cleanly */
  1252. is->abort_request = 1;
  1253. SDL_WaitThread(is->parse_tid, NULL);
  1254. /* free all pictures */
  1255. for(i=0;i<VIDEO_PICTURE_QUEUE_SIZE; i++) {
  1256. vp = &is->pictq[i];
  1257. if (vp->bmp) {
  1258. SDL_FreeYUVOverlay(vp->bmp);
  1259. vp->bmp = NULL;
  1260. }
  1261. }
  1262. SDL_DestroyMutex(is->pictq_mutex);
  1263. SDL_DestroyCond(is->pictq_cond);
  1264. }
  1265. void stream_cycle_channel(VideoState *is, int codec_type)
  1266. {
  1267. AVFormatContext *ic = is->ic;
  1268. int start_index, stream_index;
  1269. AVStream *st;
  1270. if (codec_type == CODEC_TYPE_VIDEO)
  1271. start_index = is->video_stream;
  1272. else
  1273. start_index = is->audio_stream;
  1274. if (start_index < 0)
  1275. return;
  1276. stream_index = start_index;
  1277. for(;;) {
  1278. if (++stream_index >= is->ic->nb_streams)
  1279. stream_index = 0;
  1280. if (stream_index == start_index)
  1281. return;
  1282. st = ic->streams[stream_index];
  1283. if (st->codec.codec_type == codec_type) {
  1284. /* check that parameters are OK */
  1285. switch(codec_type) {
  1286. case CODEC_TYPE_AUDIO:
  1287. if (st->codec.sample_rate != 0 &&
  1288. st->codec.channels != 0)
  1289. goto the_end;
  1290. break;
  1291. case CODEC_TYPE_VIDEO:
  1292. goto the_end;
  1293. default:
  1294. break;
  1295. }
  1296. }
  1297. }
  1298. the_end:
  1299. stream_component_close(is, start_index);
  1300. stream_component_open(is, stream_index);
  1301. }
  1302. void toggle_full_screen(void)
  1303. {
  1304. int w, h, flags;
  1305. is_full_screen = !is_full_screen;
  1306. if (!fs_screen_width) {
  1307. /* use default SDL method */
  1308. SDL_WM_ToggleFullScreen(screen);
  1309. } else {
  1310. /* use the recorded resolution */
  1311. flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
  1312. if (is_full_screen) {
  1313. w = fs_screen_width;
  1314. h = fs_screen_height;
  1315. flags |= SDL_FULLSCREEN;
  1316. } else {
  1317. w = screen_width;
  1318. h = screen_height;
  1319. flags |= SDL_RESIZABLE;
  1320. }
  1321. screen = SDL_SetVideoMode(w, h, 0, flags);
  1322. cur_stream->width = w;
  1323. cur_stream->height = h;
  1324. }
  1325. }
  1326. void toggle_pause(void)
  1327. {
  1328. if (cur_stream)
  1329. stream_pause(cur_stream);
  1330. }
  1331. void do_exit(void)
  1332. {
  1333. if (cur_stream) {
  1334. stream_close(cur_stream);
  1335. cur_stream = NULL;
  1336. }
  1337. if (show_status)
  1338. printf("\n");
  1339. SDL_Quit();
  1340. exit(0);
  1341. }
  1342. void toggle_audio_display(void)
  1343. {
  1344. if (cur_stream) {
  1345. cur_stream->show_audio = !cur_stream->show_audio;
  1346. }
  1347. }
  1348. /* handle an event sent by the GUI */
  1349. void event_loop(void)
  1350. {
  1351. SDL_Event event;
  1352. for(;;) {
  1353. SDL_WaitEvent(&event);
  1354. switch(event.type) {
  1355. case SDL_KEYDOWN:
  1356. switch(event.key.keysym.sym) {
  1357. case SDLK_ESCAPE:
  1358. case SDLK_q:
  1359. do_exit();
  1360. break;
  1361. case SDLK_f:
  1362. toggle_full_screen();
  1363. break;
  1364. case SDLK_p:
  1365. case SDLK_SPACE:
  1366. toggle_pause();
  1367. break;
  1368. case SDLK_a:
  1369. if (cur_stream)
  1370. stream_cycle_channel(cur_stream, CODEC_TYPE_AUDIO);
  1371. break;
  1372. case SDLK_v:
  1373. if (cur_stream)
  1374. stream_cycle_channel(cur_stream, CODEC_TYPE_VIDEO);
  1375. break;
  1376. case SDLK_w:
  1377. toggle_audio_display();
  1378. break;
  1379. default:
  1380. break;
  1381. }
  1382. break;
  1383. case SDL_VIDEORESIZE:
  1384. if (cur_stream) {
  1385. screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
  1386. SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
  1387. cur_stream->width = event.resize.w;
  1388. cur_stream->height = event.resize.h;
  1389. }
  1390. break;
  1391. case SDL_QUIT:
  1392. case FF_QUIT_EVENT:
  1393. do_exit();
  1394. break;
  1395. case FF_ALLOC_EVENT:
  1396. alloc_picture(event.user.data1);
  1397. break;
  1398. case FF_REFRESH_EVENT:
  1399. video_refresh_timer(event.user.data1);
  1400. break;
  1401. default:
  1402. break;
  1403. }
  1404. }
  1405. }
  1406. void opt_width(const char *arg)
  1407. {
  1408. screen_width = atoi(arg);
  1409. }
  1410. void opt_height(const char *arg)
  1411. {
  1412. screen_height = atoi(arg);
  1413. }
  1414. static void opt_format(const char *arg)
  1415. {
  1416. file_iformat = av_find_input_format(arg);
  1417. if (!file_iformat) {
  1418. fprintf(stderr, "Unknown input format: %s\n", arg);
  1419. exit(1);
  1420. }
  1421. }
  1422. static void opt_image_format(const char *arg)
  1423. {
  1424. AVImageFormat *f;
  1425. for(f = first_image_format; f != NULL; f = f->next) {
  1426. if (!strcmp(arg, f->name))
  1427. break;
  1428. }
  1429. if (!f) {
  1430. fprintf(stderr, "Unknown image format: '%s'\n", arg);
  1431. exit(1);
  1432. }
  1433. image_format = f;
  1434. }
  1435. #ifdef CONFIG_NETWORK
  1436. void opt_rtp_tcp(void)
  1437. {
  1438. /* only tcp protocol */
  1439. rtsp_default_protocols = (1 << RTSP_PROTOCOL_RTP_TCP);
  1440. }
  1441. #endif
  1442. void opt_sync(const char *arg)
  1443. {
  1444. if (!strcmp(arg, "audio"))
  1445. av_sync_type = AV_SYNC_AUDIO_MASTER;
  1446. else if (!strcmp(arg, "video"))
  1447. av_sync_type = AV_SYNC_VIDEO_MASTER;
  1448. else if (!strcmp(arg, "ext"))
  1449. av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
  1450. else
  1451. show_help();
  1452. }
  1453. const OptionDef options[] = {
  1454. { "h", 0, {(void*)show_help}, "show help" },
  1455. { "x", HAS_ARG, {(void*)opt_width}, "force displayed width", "width" },
  1456. { "y", HAS_ARG, {(void*)opt_height}, "force displayed height", "height" },
  1457. #if 0
  1458. /* disabled as SDL/X11 does not support it correctly on application launch */
  1459. { "fs", OPT_BOOL, {(void*)&is_full_screen}, "force full screen" },
  1460. #endif
  1461. { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
  1462. { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
  1463. { "nodisp", OPT_BOOL, {(void*)&display_disable}, "disable graphical display" },
  1464. { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
  1465. { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
  1466. { "stats", OPT_BOOL | OPT_EXPERT, {(void*)&show_status}, "show status", "" },
  1467. #ifdef CONFIG_NETWORK
  1468. { "rtp_tcp", OPT_EXPERT, {(void*)&opt_rtp_tcp}, "force RTP/TCP protocol usage", "" },
  1469. #endif
  1470. { "sync", HAS_ARG | OPT_EXPERT, {(void*)&opt_sync}, "set audio-video sync. type (type=audio/video/ext)", "type" },
  1471. { NULL, },
  1472. };
  1473. void show_help(void)
  1474. {
  1475. printf("ffplay version " FFMPEG_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
  1476. "usage: ffplay [options] input_file\n"
  1477. "Simple media player\n");
  1478. printf("\n");
  1479. show_help_options(options, "Main options:\n",
  1480. OPT_EXPERT, 0);
  1481. show_help_options(options, "\nAdvanced options:\n",
  1482. OPT_EXPERT, OPT_EXPERT);
  1483. printf("\nWhile playing:\n"
  1484. "q, ESC quit\n"
  1485. "f toggle full screen\n"
  1486. "p, SPC pause\n"
  1487. "a cycle audio channel\n"
  1488. "v cycle video channel\n"
  1489. "w show audio waves\n"
  1490. );
  1491. exit(1);
  1492. }
  1493. void parse_arg_file(const char *filename)
  1494. {
  1495. if (!strcmp(filename, "-"))
  1496. filename = "pipe:";
  1497. input_filename = filename;
  1498. }
  1499. /* Called from the main */
  1500. int main(int argc, char **argv)
  1501. {
  1502. int flags, w, h;
  1503. /* register all codecs, demux and protocols */
  1504. av_register_all();
  1505. parse_options(argc, argv, options);
  1506. if (!input_filename)
  1507. show_help();
  1508. if (display_disable) {
  1509. video_disable = 1;
  1510. }
  1511. flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
  1512. #ifndef CONFIG_WIN32
  1513. flags |= SDL_INIT_EVENTTHREAD; /* Not supported on win32 */
  1514. #endif
  1515. if (SDL_Init (flags)) {
  1516. fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
  1517. exit(1);
  1518. }
  1519. if (!display_disable) {
  1520. #ifdef HAVE_X11
  1521. /* save the screen resolution... SDL should allow full screen
  1522. by resizing the window */
  1523. {
  1524. Display *dpy;
  1525. dpy = XOpenDisplay(NULL);
  1526. if (dpy) {
  1527. fs_screen_width = DisplayWidth(dpy, DefaultScreen(dpy));
  1528. fs_screen_height = DisplayHeight(dpy, DefaultScreen(dpy));
  1529. XCloseDisplay(dpy);
  1530. }
  1531. }
  1532. #endif
  1533. flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
  1534. if (is_full_screen && fs_screen_width) {
  1535. w = fs_screen_width;
  1536. h = fs_screen_height;
  1537. flags |= SDL_FULLSCREEN;
  1538. } else {
  1539. w = screen_width;
  1540. h = screen_height;
  1541. flags |= SDL_RESIZABLE;
  1542. }
  1543. screen = SDL_SetVideoMode(w, h, 0, flags);
  1544. if (!screen) {
  1545. fprintf(stderr, "SDL: could not set video mode - exiting\n");
  1546. exit(1);
  1547. }
  1548. SDL_WM_SetCaption("FFplay", "FFplay");
  1549. }
  1550. SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
  1551. SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
  1552. SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
  1553. SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
  1554. cur_stream = stream_open(input_filename, file_iformat);
  1555. event_loop();
  1556. /* never returns */
  1557. return 0;
  1558. }