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.

1952 lines
57KB

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