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.

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