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.

1941 lines
56KB

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