VideoStream.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. #include "VideoStream.h"
  2. #include <iostream>
  3. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
  4. #define av_frame_alloc avcodec_alloc_frame
  5. #define av_frame_free avcodec_free_frame
  6. #endif
  7. const uint8_t VideoStream::endcode[] = { 0, 0, 1, 0xb7 };
  8. VideoStream::VideoStream(int width, int height, const std::string& filename, int bitrate, int fps, const char* preset) :
  9. width{ width & (~1) }, height{ height & (~1) }
  10. {
  11. // only needed with ffmpeg version < 4
  12. //avcodec_register_all();
  13. codec = avcodec_find_encoder(AV_CODEC_ID_H264);
  14. if (!codec) {
  15. fprintf(stderr, "invalid codec\n");
  16. exit(1);
  17. }
  18. AVOutputFormat* oformat = av_guess_format(nullptr, filename.c_str(), nullptr);
  19. if (!oformat)
  20. oformat = av_guess_format("mp4", nullptr, nullptr);
  21. if (oformat == nullptr)
  22. throw "invalid format";
  23. codecContext = avcodec_alloc_context3(codec);
  24. pkt = av_packet_alloc();
  25. if (!pkt)
  26. exit(1);
  27. codecContext->bit_rate = bitrate * 1000;
  28. codecContext->width = width;
  29. codecContext->height = height;
  30. codecContext->time_base = AVRational{ 1, fps };
  31. codecContext->framerate = AVRational{ fps, 1 };
  32. codecContext->gop_size = 5; /* emit one intra frame every five frames */
  33. codecContext->max_b_frames = 1;
  34. codecContext->pix_fmt = AV_PIX_FMT_YUV420P;
  35. formatContext = avformat_alloc_context();
  36. formatContext->oformat = oformat;
  37. formatContext->video_codec_id = oformat->video_codec;
  38. stream = avformat_new_stream(formatContext, codec);
  39. if (!stream)
  40. throw "error";
  41. params = avcodec_parameters_alloc();
  42. avcodec_parameters_from_context(params, codecContext);
  43. stream->codecpar = params;
  44. /*AVCPBProperties *props;
  45. props = (AVCPBProperties*) av_stream_new_side_data(
  46. stream, AV_PKT_DATA_CPB_PROPERTIES, sizeof(*props));
  47. props->buffer_size = 1024 * 1024;
  48. props->max_bitrate = 0;
  49. props->min_bitrate = 0;
  50. props->avg_bitrate = 0;
  51. props->vbv_delay = UINT64_MAX;*/
  52. if (codec->id == AV_CODEC_ID_H264)
  53. av_opt_set(codecContext->priv_data, "preset", preset, 0);
  54. if (avcodec_open2(codecContext, codec, nullptr) < 0) {
  55. fprintf(stderr, "could not open codec\n");
  56. exit(1);
  57. }
  58. avio_open(&formatContext->pb, filename.c_str(), AVIO_FLAG_WRITE);
  59. if (avformat_write_header(formatContext, NULL) < 0) {
  60. throw "error";
  61. }
  62. /*file = fopen(filename.c_str(), "wb");
  63. if (!file) {
  64. fprintf(stderr, "could not open %s\n", filename.c_str());
  65. exit(1);
  66. }*/
  67. picture = av_frame_alloc();
  68. av_frame_make_writable(picture);
  69. picture->format = codecContext->pix_fmt;
  70. picture->width = codecContext->width;
  71. picture->height = codecContext->height;
  72. int retval = av_frame_get_buffer(picture, 0);
  73. if (retval < 0) {
  74. fprintf(stderr, "could not alloc the frame data\n");
  75. exit(1);
  76. }
  77. //av_image_alloc(picture->data, picture->linesize, width, height, codecContext->pix_fmt, 32);
  78. swsContext = sws_getContext(width, height,
  79. AV_PIX_FMT_RGB24, width, height,
  80. AV_PIX_FMT_YUV420P, 0, 0, 0, 0);
  81. }
  82. void VideoStream::encode(AVFrame* frame)
  83. {
  84. int ret;
  85. /* send the frame to the encoder */
  86. ret = avcodec_send_frame(codecContext, frame);
  87. if (ret < 0) {
  88. fprintf(stderr, "error sending a frame for encoding\n");
  89. exit(1);
  90. }
  91. while (ret >= 0) {
  92. ret = avcodec_receive_packet(codecContext, pkt);
  93. //ret = avcodec_encode_video2(codecContext, pkt, picture, &gotPacket);
  94. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  95. return;
  96. else if (ret < 0) {
  97. fprintf(stderr, "error during encoding\n");
  98. exit(1);
  99. }
  100. printf("encoded frame %3d\"PRId64\" (size=%5d)\n", pkt->pts, pkt->size);
  101. //fwrite(pkt->data, 1, pkt->size, outfile);
  102. //av_interleaved_write_frame(formatContext, pkt);
  103. av_packet_rescale_ts(pkt, AVRational{1, 60}, stream->time_base);
  104. pkt->stream_index = stream->index;
  105. av_write_frame(formatContext, pkt);
  106. av_packet_unref(pkt);
  107. }
  108. }
  109. VideoStream::~VideoStream()
  110. {
  111. /* flush the encoder */
  112. encode(nullptr);
  113. av_write_trailer(this->formatContext);
  114. /* add sequence end code to have a real MPEG file */
  115. //fwrite(endcode, 1, sizeof(endcode), file);
  116. //fclose(file);
  117. avcodec_close(codecContext);
  118. avio_close(formatContext->pb);
  119. av_frame_unref(picture);
  120. //av_free(codecContext);
  121. avcodec_parameters_free(&params);
  122. avcodec_free_context(&codecContext);
  123. av_frame_free(&picture);
  124. av_packet_free(&pkt);
  125. /*
  126. AVPacket pkt;
  127. av_init_packet(&pkt);
  128. pkt.data = nullptr;
  129. pkt.size = 0;
  130. for (;;) {
  131. avcodec_send_frame(codecContext, NULL);
  132. if (avcodec_receive_packet(codecContext, &pkt) == 0) {
  133. av_interleaved_write_frame(codecContext, &pkt);
  134. av_packet_unref(&pkt);
  135. }
  136. else {
  137. break;
  138. }
  139. }
  140. av_write_trailer();
  141. if (!(oformat->flags & AVFMT_NOFILE)) {
  142. int err = avio_close(ofctx->pb);
  143. if (err < 0) {
  144. Debug("Failed to close file", err);
  145. }
  146. }*/
  147. }
  148. void VideoStream::addFrame(const Bitmap<RGBColor>& frame)
  149. {
  150. int retval = av_frame_make_writable(picture);
  151. if (retval < 0)
  152. exit(1);
  153. /* prepare a dummy image */
  154. /* Y */
  155. /*for(int y = 0; y < height; y++) {
  156. for(int x = 0; x < width; x++) {
  157. picture->data[0][y * picture->linesize[0] + x] = frame.get(x, y).r / 2;
  158. }
  159. }*/
  160. /* Cb and Cr */
  161. /*for(int y=0;y<height / 2;y++) {
  162. for(int x=0;x<width / 2;x++) {
  163. picture->data[1][y * picture->linesize[1] + x] = frame.get(x * 2, y * 2).g / 2;
  164. picture->data[2][y * picture->linesize[2] + x] = frame.get(x * 2, y * 2).b / 2;
  165. }
  166. }*/
  167. /*auto gammaCorrect = [] (const RGBColor& rgb) {
  168. const float gamma = 2.2f;
  169. return RGBColor {
  170. uint8_t(::powf(rgb.r / 255.0f, 1.0f / gamma) * 255),
  171. uint8_t(::powf(rgb.g / 255.0f, 1.0f / gamma) * 255),
  172. uint8_t(::powf(rgb.b / 255.0f, 1.0f / gamma) * 255),
  173. };
  174. };
  175. Bitmap<RGBColor> gammaCorrected = frame.map<RGBColor>(gammaCorrect);*/
  176. const uint8_t* pixelPointer[] = { reinterpret_cast<const uint8_t*>(frame.pixels.get()), 0 };
  177. const int linesizeIn[] = { int(frame.width * sizeof(RGBColor)) };
  178. sws_scale(swsContext, pixelPointer, linesizeIn, 0,
  179. frame.height, picture->data, picture->linesize);
  180. picture->pts = frameIndex++;
  181. /* encode the image */
  182. encode(picture);
  183. }