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.

1993 lines
58KB

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