I want to extract albumart from mp3 files
so i use taglib library
extracting title and artist succed.
but when i try to extract album art, it occurs error.
void MusicContainer::getAlbumArt(const char* path) {
static const char *IdPicture = "APIC";
TagLib::MPEG::File mpegFile(path);
TagLib::ID3v2::Tag *id3v2tag = mpegFile.ID3v2Tag();
TagLib::ID3v2::FrameList Frame;
TagLib::ID3v2::AttachedPictureFrame *PicFrame;
void *RetImage = NULL, *SrcImage;
unsigned long Size;
FILE *jpegFile;
errno_t err = fopen_s(&jpegFile, "d:\\FromId3.jpg", "wb");
if (id3v2tag)
{
// picture frame
Frame = id3v2tag->frameListMap()[IdPicture];//error occurs on this line.
if (!Frame.isEmpty())
{
for (TagLib::ID3v2::FrameList::ConstIterator it = Frame.begin(); it != Frame.end(); ++it)
{
PicFrame = (TagLib::ID3v2::AttachedPictureFrame *)(*it);
// if ( PicFrame->type() ==
//TagLib::ID3v2::AttachedPictureFrame::FrontCover)
{
// extract image (in it’s compressed form)
Size = PicFrame->picture().size();
SrcImage = malloc(Size);
if (SrcImage)
{
memcpy(SrcImage, PicFrame->picture().data(), Size);
fwrite(SrcImage, Size, 1, jpegFile);
fclose(jpegFile);
free(SrcImage);
}
}
}
}
}
else
{
cout << "id3v2 not present";
}
}
error message
Exception thrown: write access violation.
_Parent_proxy was 0x10011EE0.
If there is a handler for this exception, the program may be safely continued.
tell me how to fix it.
Related
I need to decode some H.264 frames into raw format (YUV420).
I receive packets which contains frame by some custom protocol.
How can I pass received H.264 frames into GStreamermm API to decode?
In current time I read them tutorials (unfortunately this is GST - API of C version), but can't find actual GStreamermm API documentation.
Please, point me in any documents or examples of how to do it.
I was able to implement the transfer data via pipeline and retrieve decoding raw video frames using C++ version. Here is raw example:
struct WebPipeline {
Glib::RefPtr<Gst::AppSrc> appsrc;
Glib::RefPtr<Gst::AppSink> appdst;
Glib::RefPtr<Gst::Element> h264parser;
Glib::RefPtr<Gst::Element> avdec_h264;
Glib::RefPtr<Gst::Element> jpegenc;
Glib::RefPtr<Gst::Pipeline> pipe;
bool accepts_data {false};
};
WebPipePtr ExampleClass::CreatePipeline() {
auto web_pipe = std::make_shared<WebPipeline>();
web_pipe->appsrc = Gst::AppSrc::create("web_appsrc");
if (!web_pipe->appsrc) {
throw std::runtime_error("Can't create AppSrc");
}
web_pipe->appdst = Gst::AppSink::create("web_appdst");
if (!web_pipe->appdst) {
throw std::runtime_error("Can't create AppSink");
}
web_pipe->h264parser = Gst::ElementFactory::create_element("h264parse", "h264_parser");
if (!web_pipe->h264parser) {
throw std::runtime_error("Can't create h264parse");
}
web_pipe->avdec_h264 = Gst::ElementFactory::create_element("avdec_h264", "avdec264");
if (!web_pipe->avdec_h264) {
throw std::runtime_error("Can't create avdec_h264");
}
web_pipe->jpegenc = Gst::ElementFactory::create_element("jpegenc");
if (!web_pipe->jpegenc) {
throw std::runtime_error("Can't create jpegenc");
}
web_pipe->pipe = Gst::Pipeline::create("websocket_pipe");
if (!web_pipe->pipe) {
throw std::runtime_error("Can't create pipeline");
}
web_pipe->appdst->property_emit_signals() = true;
web_pipe->appdst->set_sync(false);
web_pipe->appdst->signal_new_sample().connect(sigc::bind(sigc::mem_fun(this, &ExampleClass::PullFromPipe), web_pipe->appdst));
web_pipe->appsrc->property_emit_signals() = true;
web_pipe->appsrc->signal_need_data().connect(sigc::bind(sigc::mem_fun(this, &ExampleClass::EnableAcceptance), web_pipe));
web_pipe->appsrc->signal_enough_data().connect(sigc::bind(sigc::mem_fun(this, &ExampleClass::DisableAcceptance), web_pipe));
web_pipe->pipe->add(web_pipe->appsrc)->add(web_pipe->h264parser)->add(web_pipe->avdec_h264)->add(web_pipe->jpegenc)->add(web_pipe->appdst);
web_pipe->appsrc->link(web_pipe->h264parser)->link(web_pipe->avdec_h264)->link(web_pipe->jpegenc)->link(web_pipe->appdst);
web_pipe->pipe->set_state(Gst::STATE_PLAYING);
return web_pipe;
}
void ExampleClass::EnableAcceptance(guint, WebPipePtr pipe) {
if (!pipe->accepts_data) {
BOOST_LOG_SEV(GetLogger(), log::info) << "Begin push frames";
pipe->accepts_data = true;
}
}
void ExampleClass::DisableAcceptance(WebPipePtr pipe) {
if (pipe->accepts_data) {
BOOST_LOG_SEV(GetLogger(), log::info) << "Begin drop frames";
pipe->accepts_data = false;
}
}
void ExampleClass::PushToPipe(WebPipePtr pipe, std::vector<uint8_t>&& frames) {
if (!pipe->accepts_data) {
return Gst::FLOW_CUSTOM_ERROR;
}
GstBuffer* buffer = gst_buffer_new_wrapped_full(static_cast<GstMemoryFlags>(GST_MEMORY_FLAG_READONLY | GST_MEMORY_FLAG_PHYSICALLY_CONTIGUOUS),
const_cast<uint8_t*>(frame.data()),
frame.size(),
0,
frame.size(),
reinterpret_cast<gpointer>(frame_ref), // inner implementation of some sort of wrapper
destroy); // lamda-destructor
buffer->set_pts(time);
return pipe->appsrc->push_buffer(buffer);
}
Gst::FlowReturn ExampleClass::PullFromPipe(const Glib::RefPtr<Gst::AppSink>& appsink) {
auto sample = appsink->pull_sample();
if (!sample) {
return Gst::FLOW_ERROR;
}
if (appsink->property_eos()) {
return Gst::FLOW_EOS;
}
Gst::ClockTime timestamp = 0;
{
auto buffer = sample->get_buffer();
if (!buffer) {
throw std::runtime_error("Can't get buffer from sample");
}
timestamp = buffer->get_pts();
}
// process sample...
return Gst::FLOW_OK;
}
This is how i load pdf using Google's PDFIUM library. I receive void*:
doc = FPDF_LoadDocument("media1.pdf", NULL);
Now i want to save this document in vector of FPDF_DOCUMENT which is basically void* that i receive back from above code. This is how i am saving it in vector:
pdfs.push_back(doc);
Problem is when i do out of scope of this method, i dont have access to that memory pointed by doc. I guess when doc goes out of scope, GC frees that memory. I got to know about this Valgrid debugging tool.
doc is declared in same function as command to load pdf is.
I basically want to retain loaded pdf so that i can later access it and render pages from it.
Valgrind output:
==4816== 64 bytes in 1 blocks are definitely lost in loss record 175 of 616
==4816== at 0x4C2A105: operator new(unsigned long) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==4816== by 0x85175B: FPDFBitmap_Create (in /home/ec2-user/Vid/dist/Debug/GNU-MacOSX/video_creator_mount)
==4816== by 0x4586A1: Blrt::PDFManager::RenderPDFPage(int, int) (PDFManager.cc:159)
Following is method in PDFManager:
std::unique_ptr<Canvas::LoadedPDFInfo> PDFManager::LoadPDF(const std::vector<uint8_t>& data, size_t dataSize)
{
if(!initPDFIUM) {
InitPDFIUM();
currentPDFHandle = 0;
}
FPDF_DOCUMENT doc;
// doc = FPDF_LoadMemDocument(&data[0], dataSize, nullptr);
doc = FPDF_LoadDocument("media1.pdf", NULL);
if (!doc) {
unsigned long err = FPDF_GetLastError();
fprintf(stderr, "Load pdf docs unsuccessful: ");
switch (err) {
case FPDF_ERR_SUCCESS:
fprintf(stderr, "Success");
break;
case FPDF_ERR_UNKNOWN:
fprintf(stderr, "Unknown error");
break;
case FPDF_ERR_FILE:
fprintf(stderr, "File not found or could not be opened");
break;
case FPDF_ERR_FORMAT:
fprintf(stderr, "File not in PDF format or corrupted");
break;
case FPDF_ERR_PASSWORD:
fprintf(stderr, "Password required or incorrect password");
break;
case FPDF_ERR_SECURITY:
fprintf(stderr, "Unsupported security scheme");
break;
case FPDF_ERR_PAGE:
fprintf(stderr, "Page not found or content error");
break;
default:
fprintf(stderr, "Unknown error %ld", err);
}
fprintf(stderr, ".\n");
return nullptr;
}
pdfs.push_back(doc);
//doc = nullptr;
std::unique_ptr<Canvas::LoadedPDFInfo> pdfInfo(new Canvas::LoadedPDFInfo);
pdfInfo->handle = ++currentPDFHandle;
pdfInfo->totalPageNum = FPDF_GetPageCount(doc);
std::cout << "ERROR\n";
return pdfInfo;
}
pdfs is vector declared in PDFManager.h:
namespace Blrt
{
class PDFManager
{
public:
static std::unique_ptr<Canvas::LoadedPDFInfo> LoadPDF(const std::vector<uint8_t>& data, size_t dataSize);
static std::unique_ptr<Canvas::TextureData> RenderPDFPage(int32_t pdfHandle, int32_t pageNum);
static void Dispose();
private:
static void InitPDFIUM();
static void UnsupportedHandler(UNSUPPORT_INFO*, int type);
static bool initPDFIUM;
static int32_t currentPDFHandle;
static std::vector<FPDF_DOCUMENT> pdfs;
static int32_t nextMultipleOf4(size_t num);
};
}
Following is part of a method where i am accessing pdfs to access pdf data loaded using above mentioned method:
std::unique_ptr<Canvas::TextureData> PDFManager::RenderPDFPage(int32_t pdfHandle, int32_t pageNum)
{
if (pdfs[pdfHandle-1]) {
auto pdf = *(pdfs[pdfHandle-1]);
std::cout << pdfHandle << " " << pageNum << " " <<pdfs.size() << "\n";
if (1 <= pageNum && pageNum <= FPDF_GetPageCount(pdf)) {
auto page = FPDF_LoadPage(pdf, pageNum);
if(page) {
auto textPage = FPDFText_LoadPage(page);
if (textPage) {
auto scale = 2.0;
auto maxTexSize = VideoCreator::VideoCreator::MaxTextureSize;
auto orgWidth = FPDF_GetPageWidth(page);
auto orgHeight = FPDF_GetPageHeight(page);
auto targetWidth = orgWidth * scale;
auto targetHeight = orgHeight * scale;
if (targetWidth > targetHeight) {
if (targetWidth > maxTexSize) {
scale = maxTexSize / targetWidth;
}
} else {
if (targetHeight > maxTexSize) {
scale = maxTexSize / targetHeight;
}
}
From the valgrind message, it isn't the doc you're leaking, it's the bitmap you create later. The doc is not cleaned up as there is no gc in c++. You have to close the document yourself.
But, to fix the error, you need to cleanup the bitmap you created in PDFManager.cc:159.
I have a very annoying OpenCV error, that i can't understand, and handle with.
I write an application which gets mjpg's stream from ip camera, and process it, but when i try to load image from stream, sometimes i have
[mjpeg # 0000000000428480] overread 8
error, and i don't know why.
Even if i try to skip this issue, and try to load next frame from the stream, the application stucks on
frameStatus = cameraHandler->read(mat);
This is code for connection establishing:
void ImageProcessor::connectWithCamera(VideoCapture * cameraHandler) {
if (cameraHandler != nullptr) {
Logger::log("Closing existing camera stream.");
cameraHandler->release();
delete cameraHandler;
}
Logger::log("Camera configuration and connection establishing.");
cameraHandler = new VideoCapture();
cameraHandler->set(CV_CAP_PROP_FRAME_WIDTH, config.RESOLUTION_WIDTH);
cameraHandler->set(CV_CAP_PROP_FRAME_HEIGHT, config.RESOLUTION_HEIGHT);
cameraHandler->set(CV_CAP_PROP_FPS, config.CAMERA_FPS);
cameraHandler->set(CV_CAP_PROP_FOURCC, CV_FOURCC('M', 'J', 'P', 'G'));
while (!cameraHandler->open(config.LINK)) {
Logger::log("Cannot connect to camera! Trying again.");
}
}
And this is code for capturing images:
void ImageProcessor::start() {
VideoCapture * cameraHandler = new VideoCapture();
this->connectWithCamera(cameraHandler);
this->connectWithServer(this->serverConnection);
Logger::log("Id sending.");
serverConnection->send(config.TOKEN + "\n");
Logger::log("Computations starting.");
Mat mat;
Result * result = nullptr;
int delta = 1000 / cameraHandler->get(CV_CAP_PROP_FPS);
char frameErrorCounter = 0;
bool frameStatus;
while (true) {
frameStatus = false;
cv::waitKey(delta);
try {
frameStatus = cameraHandler->read(mat);
} catch (std::exception& e) {
std::string message = e.what();
Logger::log("Critical camera error! : " + message);
}
if (!frameStatus) {
Logger::log("Cannot read a frame from source. ");
++frameErrorCounter;
if (!cameraHandler->isOpened() || frameErrorCounter >= this->GET_FRAME_ERROR_COUNTER) {
Logger::log("Probably camera is disconnected. Trying to establish connection again.");
frameErrorCounter = 0;
this->connectWithCamera(cameraHandler);
Logger::log("Computations starting.");
}
continue;
}
result = processImage(mat);
std::string stringResult;
if (result == nullptr) {
stringResult = this->NO_RESULT;
delete result;
result = nullptr;
} else {
stringResult = result->toJson();
}
if (!serverConnection->send(stringResult)) {
Logger::log("Server connection lost, trying to establish it again.");
serverConnection->close();
while (!serverConnection->isOpen()) {
this->connectWithServer(serverConnection);
}
}
mat.release();
}
}
Thanks in advance!
i got problem when using "FILE* file;" with C++ on WP8.
My app crash when meet the line above.
When i debug, i saw:
1. All the member of this variable "file" got message:
(file)->_ptr: Unable to read memory.
(file)->_cnt: Unable to read memory.
(file)->_base: Unable to read memory.
(file)->_flag: Unable to read memory.
(file)->_file: Unable to read memory.
(file)->_charbuf: Unable to read memory.
(file)->_tmpfname: Unable to read memory.
(file)->_bufsiz: Unable to read memory.
I have no idea to fix it.
And this is the code i Use:
void SubMenu::LoadConfig(float dt)
{
TiXmlDocument doc;
bool flag = doc.LoadFile("Config\Config.xml");// Error here.
TiXmlElement* root = doc.FirstChildElement();
for (TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement())
{
std::string elemName = elem->Value();
int Star = atoi(elem->GetText());
if (elemName == "Tractor")
{
this->AddStarPoint(Level1, 4, Star);
}
if (elemName == "EggsCatch")
{
this->AddStarPoint(Level2, 3, Star);
}
if (elemName == "EggsCatch2")
{
this->AddStarPoint(Level3, 4, Star);
}
}
}
This is tinyxml.cpp got function LoadFile:
bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding )
{
TIXML_STRING filename( _filename );
value = filename;
// reading in binary mode so that tinyxml can normalize the EOL
FILE* file = TiXmlFOpen( value.c_str (), "rb" ); // Error here.
if ( file )
{
bool result = LoadFile( file, encoding );
fclose( file );
return result;
}
else
{
SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
return false;
}
}
Please help!
Thanks!
I suppose file == NULL because of a single backslash \ in the path. Try
(simpler) replacing it with a slash "Config/Config.xml", or
(better) escape it with another backslash "Config\\Config.xml".
I have developed TTS engine in .NET. Now I want to expose it over web.
I have used the base64 string encoding to transfer the WAV format, but it is slow when I pass longer text.
Now I'm considering to build some MP3 streaming (maybe with NAudio) where I will convert the WAV formated MemoryStream into MP3 stream and pass it to the client. Does anyone has some experience with this?
Does anyone has experience how to convert WAV MemoryStream with NAudio to MP3 MemoryStream?
public class MP3StreamingPanel2 : UserControl
{
enum StreamingPlaybackState
{
Stopped,
Playing,
Buffering,
Paused
}
private BufferedWaveProvider bufferedWaveProvider;
private IWavePlayer waveOut;
private volatile StreamingPlaybackState playbackState;
private volatile bool fullyDownloaded;
private HttpWebRequest webRequest;
public void StreamMP32(string url)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
SettingsSection section = (SettingsSection)config.GetSection("system.net/settings");
section.HttpWebRequest.UseUnsafeHeaderParsing = true;
config.Save();
this.fullyDownloaded = false;
webRequest = (HttpWebRequest)WebRequest.Create(url);
int metaInt = 0; // blocksize of mp3 data
webRequest.Headers.Clear();
webRequest.Headers.Add("GET", "/ HTTP/1.0");
// needed to receive metadata informations
webRequest.Headers.Add("Icy-MetaData", "1");
webRequest.UserAgent = "WinampMPEG/5.09";
HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)webRequest.GetResponse();
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.RequestCanceled)
{
//ShowError(e.Message);
}
return;
}
byte[] buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame
try
{
// read blocksize to find metadata block
metaInt = Convert.ToInt32(resp.GetResponseHeader("icy-metaint"));
}
catch
{
}
IMp3FrameDecompressor decompressor = null;
try
{
using (var responseStream = resp.GetResponseStream())
{
var readFullyStream = new ReadFullyStream(responseStream);
readFullyStream.metaInt = metaInt;
do
{
if (bufferedWaveProvider != null && bufferedWaveProvider.BufferLength - bufferedWaveProvider.BufferedBytes < bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
{
Debug.WriteLine("Buffer getting full, taking a break");
Thread.Sleep(500);
}
else
{
Mp3Frame frame = null;
try
{
frame = Mp3Frame.LoadFromStream(readFullyStream, true);
}
catch (EndOfStreamException)
{
this.fullyDownloaded = true;
// reached the end of the MP3 file / stream
break;
}
catch (WebException)
{
// probably we have aborted download from the GUI thread
break;
}
if (decompressor == null)
{
// don't think these details matter too much - just help ACM select the right codec
// however, the buffered provider doesn't know what sample rate it is working at
// until we have a frame
WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
decompressor = new AcmMp3FrameDecompressor(waveFormat);
this.bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
this.bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(20); // allow us to get well ahead of ourselves
//this.bufferedWaveProvider.BufferedDuration = 250;
}
int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
//Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
bufferedWaveProvider.AddSamples(buffer, 0, decompressed);
}
} while (playbackState != StreamingPlaybackState.Stopped);
Debug.WriteLine("Exiting");
// was doing this in a finally block, but for some reason
// we are hanging on response stream .Dispose so never get there
decompressor.Dispose();
}
}
finally
{
if (decompressor != null)
{
decompressor.Dispose();
}
}
}
}
NAudio does not include an MP3 encoder. When I need to encode MP3 I use lame.exe. If you don't want to go via a file, lame.exe allows you to read from stdin and write to stdout, so if you redirect standard in and out on the process you can convert on the fly.