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.

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