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.

1940 lines
56KB

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