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.

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