VideoStream.cpp 6.6 KB

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