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.

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