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.

1937 lines
56KB

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