video.cpp
上传用户:qccn516
上传日期:2013-05-02
资源大小:3382k
文件大小:2k
源码类别:

游戏引擎

开发平台:

Visual C++

  1. /* Video
  2.  *
  3.  * Copyright (C) 2003-2004, Alexander Zaprjagaev <frustum@frustum.org>
  4.  *
  5.  * This program is free software; you can redistribute it and/or modify
  6.  * it under the terms of the GNU General Public License as published by
  7.  * the Free Software Foundation; either version 2 of the License, or
  8.  * (at your option) any later version.
  9.  *
  10.  * This program 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
  13.  * GNU General Public License for more details.
  14.  *
  15.  * You should have received a copy of the GNU General Public License
  16.  * along with this program; if not, write to the Free Software
  17.  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  18.  */
  19. #include <stdio.h>
  20. #include "video.h"
  21. Video::Video(const char *name,int width,int height,int bitrate) {
  22. avcodec_init();
  23. avcodec_register_all();
  24. codec = avcodec_find_encoder(CODEC_ID_MPEG2VIDEO);
  25. c = avcodec_alloc_context();
  26. c->bit_rate = bitrate;
  27. c->width = width;
  28. c->height = height;
  29. c->frame_rate = 25;
  30. c->frame_rate_base= 1;
  31. c->gop_size = 10;
  32. c->max_b_frames = 1;
  33. avcodec_open(c,codec);
  34. picture = avcodec_alloc_frame();
  35. yuv = avcodec_alloc_frame();
  36. int size = avpicture_get_size(PIX_FMT_YUV420P,width,height);
  37. yuv_data = (uint8_t*)malloc(size);
  38. avpicture_fill((AVPicture*)yuv,yuv_data,PIX_FMT_YUV420P,width,height);
  39. outbuf_size = 1024 * 1024;
  40. outbuf = (uint8_t*)malloc(outbuf_size);
  41. file = fopen(name,"wb");
  42. }
  43. Video::~Video() {
  44. char buf[4] = { 0x00, 0x00, 0x01, 0xb7 };
  45. fwrite(buf,1,4,file);
  46. fclose(file);
  47. avcodec_close(c);
  48. free(c);
  49. free(yuv);
  50. free(yuv_data);
  51. free(picture);
  52. }
  53. /*
  54.  */
  55. void Video::save(unsigned char *data,int flip) {
  56. if(flip) {
  57. for(int y = 0; y < c->height / 2; y++) {
  58. unsigned char *l0 = &data[c->width * y * 3];
  59. unsigned char *l1 = &data[c->width * (c->height - y - 1) * 3];
  60. for(int x = 0; x < c->width * 3; x++) {
  61. unsigned char l = *l0;
  62. *l0++ = *l1;
  63. *l1++ = l;
  64. }
  65. }
  66. }
  67. avpicture_fill((AVPicture*)picture,(uint8_t*)data,PIX_FMT_RGB24,c->width,c->height);
  68. img_convert((AVPicture*)yuv,PIX_FMT_YUV420P,(AVPicture*)picture,PIX_FMT_RGB24,c->width,c->height);
  69. int out_size = avcodec_encode_video(c,outbuf,outbuf_size,yuv);
  70. fwrite(outbuf,1,out_size,file);
  71. }