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.

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