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.

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