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.

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