| 25 | } |
| 26 | |
| 27 | bool VideoStream::processFrame() { |
| 28 | if (_avFormatContext == nullptr || !_isPlaying) |
| 29 | return false; |
| 30 | |
| 31 | const std::unique_ptr<AVPacket, void (*)(AVPacket *)> packet(av_packet_alloc(), [](AVPacket *p) { av_packet_free(&p); }); |
| 32 | |
| 33 | if (av_read_frame(_avFormatContext, packet.get()) < 0) { |
| 34 | _isPlaying = false; |
| 35 | return true; |
| 36 | } |
| 37 | |
| 38 | if (packet->stream_index == _videoStreamIdx) { |
| 39 | int avError; |
| 40 | |
| 41 | if ((avError = avcodec_send_packet(_videoCodecContext, packet.get())) < 0) |
| 42 | throw std::runtime_error(absl::StrCat("Error decoding video packet: ", avErrorCodeToString(avError))); |
| 43 | |
| 44 | if ((avError = avcodec_receive_frame(_videoCodecContext, _avFrame)) < 0) |
| 45 | throw std::runtime_error(absl::StrCat("Error decoding video packet: ", avErrorCodeToString(avError))); |
| 46 | |
| 47 | uint8_t *data[AV_NUM_DATA_POINTERS]; |
| 48 | data[0] = _yPlane.data(); |
| 49 | data[1] = _uPlane.data(); |
| 50 | data[2] = _vPlane.data(); |
| 51 | |
| 52 | int lineSize[AV_NUM_DATA_POINTERS]; |
| 53 | lineSize[0] = _videoCodecContext->width; |
| 54 | lineSize[1] = _uvPitch; |
| 55 | lineSize[2] = _uvPitch; |
| 56 | |
| 57 | _framesReady = true; |
| 58 | |
| 59 | sws_scale(_swsContext, _avFrame->data, _avFrame->linesize, 0, _videoCodecContext->height, data, lineSize); |
| 60 | if (SDL_UpdateYUVTexture(_texture.get(), nullptr, _yPlane.data(), _videoCodecContext->width, _uPlane.data(), _uvPitch, _vPlane.data(), _uvPitch) < 0) { |
| 61 | throw std::runtime_error("Cannot set YUV data"); |
| 62 | } |
| 63 | |
| 64 | return true; |
| 65 | } |
| 66 | |
| 67 | if (packet->stream_index == _audioStreamIdx) { |
| 68 | int avError; |
| 69 | |
| 70 | if ((avError = avcodec_send_packet(_audioCodecContext, packet.get())) < 0) |
| 71 | throw std::runtime_error(absl::StrCat("Error decoding audio packet: ", avErrorCodeToString(avError))); |
| 72 | |
| 73 | while (true) { |
| 74 | if ((avError = avcodec_receive_frame(_audioCodecContext, _avFrame)) < 0) { |
| 75 | if (avError == AVERROR(EAGAIN) || avError == AVERROR_EOF) |
| 76 | break; |
| 77 | |
| 78 | throw std::runtime_error(absl::StrCat("Error decoding audio packet: ", avErrorCodeToString(avError))); |
| 79 | } |
| 80 | |
| 81 | int _lineSize; |
| 82 | const auto outSamples = swr_get_out_samples(_resampleContext, _avFrame->nb_samples); |
| 83 | const auto audioOutSize = av_samples_get_buffer_size(&_lineSize, 2, outSamples, AV_SAMPLE_FMT_S16, 0); |
| 84 | uint8_t *ptr[1] = {_audioOutBuffer}; |