-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudioEncoder.cpp
More file actions
416 lines (298 loc) · 12.3 KB
/
Copy pathAudioEncoder.cpp
File metadata and controls
416 lines (298 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#include "stdafx.h"
#include <mfapi.h>
#include <wmcodecdsp.h>
#include <Mferror.h>
#include <stdexcept>
#include <propvarutil.h>
#include "AudioEncoder.h"
static void SetBooleanPropertyStoreValue(IPropertyStore* propertyStore, const PROPERTYKEY& key, BOOL value)
{
PROPVARIANT var;
HRESULT hr;
if (!propertyStore) throw std::exception("Null parameter: propertyStore");
if (SUCCEEDED(hr = InitPropVariantFromBoolean(value, &var)))
{
hr = propertyStore->SetValue(key, var);
}
PropVariantClear(&var);
if (FAILED(hr))
throw std::exception("Unable to set PropertyStore value");
}
static void SetUint32PropertyStoreValue(IPropertyStore* propertyStore, const PROPERTYKEY& key, UINT32 value)
{
PROPVARIANT var;
HRESULT hr;
if (!propertyStore) throw std::exception("Null parameter: propertyStore");
if (SUCCEEDED(hr = InitPropVariantFromUInt32(value, &var)))
{
hr = propertyStore->SetValue(key, var);
}
PropVariantClear(&var);
if (FAILED(hr))
throw std::exception("Unable to set PropertyStore value");
}
AudioEncoderParameters::AudioEncoderParameters(CompressionFamily compressionFamily, UINT32 qualityLevel, UINT32 channelCount, UINT32 samplesPerSecond, UINT32 bitsPerSample)
{
_compressionFamily = compressionFamily;
_qualityLevel = qualityLevel;
_channelCount = channelCount;
_samplesPerSecond = samplesPerSecond;
_bitsPerSample = bitsPerSample;
}
AudioEncoderParameters* AudioEncoderParameters::CreateQualityBasedVbrParameters(UINT32 qualityLevel, UINT32 channelCount, UINT32 samplesPerSecond, UINT32 bitsPerSample)
{
// TODO add parameter validation
return new AudioEncoderParameters(CompressionFamily::QualityBasedVariableBitRate, qualityLevel, channelCount, samplesPerSecond, bitsPerSample);
}
AudioEncoderParameters* AudioEncoderParameters::CreateLosslessEncoderParameters(UINT32 channelCount, UINT32 samplesPerSecond, UINT32 bitsPerSample)
{
return new AudioEncoderParameters(CompressionFamily::Lossless, 100, channelCount, samplesPerSecond, bitsPerSample);
}
BOOL AudioEncoderParameters::IsLossless()
{
return _compressionFamily == CompressionFamily::Lossless;
}
BOOL AudioEncoderParameters::IsQualityBasedVbr()
{
return (_compressionFamily == CompressionFamily::QualityBasedVariableBitRate) || (_compressionFamily == CompressionFamily::Lossless);
}
UINT32 AudioEncoderParameters::GetQualityLevel()
{
return _qualityLevel;
}
UINT32 AudioEncoderParameters::GetChannelCount()
{
return _channelCount;
}
UINT32 AudioEncoderParameters::GetBitsPerSample()
{
return _bitsPerSample;
}
UINT32 AudioEncoderParameters::GetSamplesPerSecond()
{
return _samplesPerSecond;
}
IMFMediaType* AudioEncoder::GetEncoderMediaType(AudioEncoderParameters* encoderParameters)
{
IMFMediaType* result;
IPropertyStore *propertyStore = nullptr; // TODO when can this be released safely?
//We need to find a suitable output media type
//We need to create the encoder to get the available output types
//and discard the instance.
IMFActivate **transformActivationObjs;
UINT32 transformCount;
MFT_REGISTER_TYPE_INFO regTypeInfo;
regTypeInfo.guidMajorType = MFMediaType_Audio;
regTypeInfo.guidSubtype = (encoderParameters->IsLossless()) ? MFAudioFormat_WMAudio_Lossless : MFAudioFormat_WMAudioV8;
// Look for an encoder.
HRESULT hr = MFTEnumEx(MFT_CATEGORY_AUDIO_ENCODER, MFT_ENUM_FLAG_TRANSCODE_ONLY, nullptr, ®TypeInfo, &transformActivationObjs, &transformCount);
if ((hr != S_OK) || (transformCount < 1))
throw std::exception("No Media Foundation encoders found");
// Regardless how many activation objects returned, just instantiate the first one
// (would I want to instantiate another? Why? Which one?)
IMFActivate *activationObj = *transformActivationObjs;
IMFTransform *mfEncoder = nullptr;
WCHAR transformName[128];
UINT32 nameLen;
do
{
if (!SUCCEEDED(hr = activationObj->GetString(MFT_FRIENDLY_NAME_Attribute, transformName, sizeof(transformName), &nameLen)))
break;
if (!SUCCEEDED(activationObj->ActivateObject(IID_PPV_ARGS(&mfEncoder))))
break;
if (encoderParameters->IsQualityBasedVbr())
{
if (!SUCCEEDED(hr = mfEncoder->QueryInterface(IID_PPV_ARGS(&propertyStore))))
break;
SetEncoderPropertiesForQualityBasedVbr(propertyStore, encoderParameters->GetQualityLevel());
}
} while (0);
if (FAILED(hr))
throw std::exception("Unable to activate encoder MFT");
// enumerate output types and try to find the appropriate one for our purposes
UINT32 channelCount, samplesPerSecond, bitsPerSample;
DWORD index = 0;
int desiredChannelCount = encoderParameters->GetChannelCount();
int desiredSamplesPerSecond = encoderParameters->GetSamplesPerSecond();
int desiredBitsPerSample = encoderParameters->GetBitsPerSample();
while (true)
{
IMFMediaType *mediaType;
hr = mfEncoder->GetOutputAvailableType(0, index++, &mediaType);
if (hr == MF_E_NO_MORE_TYPES)
break;
// Get the AM_MEDIA_TYPE structure from the media type, in case we want to need
// to differentiate between Standard and Pro WMA codecs in the future...
AM_MEDIA_TYPE *amMediaType;
mediaType->GetRepresentation(AM_MEDIA_TYPE_REPRESENTATION, (LPVOID *)&amMediaType);
WAVEFORMATEX *waveFormat = (WAVEFORMATEX *)amMediaType->pbFormat;
// there's only a few things we're interested in with the output type, so only bother grabbing those values
hr = mediaType->GetUINT32(MF_MT_AUDIO_NUM_CHANNELS, &channelCount);
hr = mediaType->GetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, &samplesPerSecond);
hr = mediaType->GetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, &bitsPerSample);
if ((channelCount == desiredChannelCount) && (samplesPerSecond == desiredSamplesPerSecond) && (bitsPerSample == desiredBitsPerSample))
{
result = mediaType;
break;
}
else
{
mediaType->Release();
}
}
if (propertyStore) propertyStore->Release();
if (mfEncoder) mfEncoder->Release();
activationObj->ShutdownObject();
// release all the activation pointers that got allocated...
for (UINT32 i = 0; i < transformCount; i++)
{
IMFActivate *temp = *(transformActivationObjs + i);
temp->Release();
}
// ...and free the activation array object
CoTaskMemFree(transformActivationObjs);
return result;
}
void AudioEncoder::SetEncoderPropertiesForQualityBasedVbr(IPropertyStore* propertyStore, UINT32 quality)
{
SetBooleanPropertyStoreValue(propertyStore, MFPKEY_VBRENABLED, TRUE);
SetBooleanPropertyStoreValue(propertyStore, MFPKEY_CONSTRAIN_ENUMERATED_VBRQUALITY, TRUE);
SetUint32PropertyStoreValue(propertyStore, MFPKEY_DESIRED_VBRQUALITY, quality);
}
static IMFTopology* BuildEncodingTopography(MediaSource* source, IMFTransform* audioEncoder, MediaSink* sink)
{
IMFTopology* mfTopology = nullptr;
IMFTopologyNode* encoderNode = nullptr;
IMFTopologyNode* sourceNode = nullptr;
IMFTopologyNode* outputNode = nullptr;
//Create the topology that represents the encoding pipeline
HRESULT hr = MFCreateTopology(&mfTopology);
do {
// Add source node
sourceNode = source->CreateTopologySourceNode();
if (!SUCCEEDED(hr = mfTopology->AddNode(sourceNode)))
break;
// Add encoder node
// this is a little more convoluted than hoped for, but bear with me.
// at first glance it seems odd that we'd create the compressor transform
// through the MediaSink object. But, it turns
// out the the media sink holds the two main ingredients needed to
// create the encoder: the output stream MediaType, and, crucially,
// the EncodingConfigurationPropertyStore that's a requirement if
// you want to do quality-based VBR.
//
// Originally I had a method in MediaSink that functioned similiar to the
// MediaSource::CreateTopologySourceNode() and MediaSink::CreateTopologyOutputNode().
// This worked ok, but another problem with quality-based VBR is (apparently)
// you're supposed to set some properties on the output stream,
// based on values computed by the encoder during compressions.
// The original example code jumped thorugh hoops to get back a reference
// to the encoder by traversing the full topology, but I felt
// it was much more understandable to first save a reference to
// the actual encoder object, and use that for the post-processing
// property patch.
//
// Say that ten times quick!
hr = MFCreateTopologyNode(MF_TOPOLOGY_TRANSFORM_NODE, &encoderNode);
// Set the object pointer.
hr = encoderNode->SetObject(audioEncoder);
if (!SUCCEEDED(hr = mfTopology->AddNode(encoderNode)))
break;
// connect the source node to the encoder
if (!SUCCEEDED(hr = sourceNode->ConnectOutput(0, encoderNode, 0)))
break;
// Add sink node
outputNode = sink->CreateTopologyOutputNode(1);
if (!SUCCEEDED(hr = mfTopology->AddNode(outputNode)))
break;
// connect the transform node to the output node
if (!SUCCEEDED(hr = encoderNode->ConnectOutput(0, outputNode, 0)))
break;
} while (0);
if (sourceNode) sourceNode->Release();
if (outputNode) outputNode->Release();
if (encoderNode) encoderNode->Release();
if (FAILED(hr))
throw std::exception("Unable to construct topology");
return mfTopology;
}
static HRESULT UpdateVbrStreamProperties(IMFTransform* audioEncoder, MediaSink* mediaSink)
{
IPropertyStore* encoderPropertyStore;
HRESULT hr;
hr = audioEncoder->QueryInterface(IID_PPV_ARGS(&encoderPropertyStore));
mediaSink->UpdatePostEncodeStreamSinkProperties(1, encoderPropertyStore);
return hr;
}
static HRESULT GetNextMediaSessionEvent(IMFMediaSession* mfMediaSession, MediaEventType* mediaEventType, MF_TOPOSTATUS* eventTopologyStatus)
{
IMFMediaEvent* mfMediaEvent = nullptr;
HRESULT eventStatus, hr;
do
{
if (!SUCCEEDED(hr = mfMediaSession->GetEvent(0, &mfMediaEvent)))
break;
if (!SUCCEEDED(hr = mfMediaEvent->GetType(mediaEventType)))
break;
if (!SUCCEEDED(hr = mfMediaEvent->GetStatus(&eventStatus)))
break;
*eventTopologyStatus = (MF_TOPOSTATUS)MFGetAttributeUINT32(mfMediaEvent, MF_EVENT_TOPOLOGY_STATUS, MF_TOPOSTATUS_INVALID);
} while (0);
if (mfMediaEvent) mfMediaEvent->Release();
if (FAILED(hr))
{
throw std::exception("Error retrieving MediaSession event");
}
return eventStatus;
}
void AudioEncoder::Encode(MediaSource* mediaSource, MediaSink* mediaSink, AudioEncoderParameters* encoderParameters)
{
IMFMediaSession* mfMediaSession = nullptr;
MediaEventType mediaEventType;
MF_TOPOSTATUS topologyStatus;
HRESULT eventStatus, hr;
IMFTransform* audioEncoder = mediaSink->GetAudioEncoderForStream(1);
IMFTopology* topology = BuildEncodingTopography(mediaSource, audioEncoder, mediaSink);
if (!SUCCEEDED(MFCreateMediaSession(nullptr, &mfMediaSession)))
throw std::exception("Unable to create MediaSession");
if (!SUCCEEDED(mfMediaSession->SetTopology(MFSESSION_SETTOPOLOGY_IMMEDIATE, topology)))
throw std::exception("Unable to set topology on MediaSession");
// MediaSession loop start
eventStatus = GetNextMediaSessionEvent(mfMediaSession, &mediaEventType, &topologyStatus);
while (SUCCEEDED(eventStatus) && (mediaEventType != MESessionClosed))
{
if ((mediaEventType == MESessionTopologyStatus) && (topologyStatus == MF_TOPOSTATUS_READY))
{
PROPVARIANT startingPosition;
PropVariantInit(&startingPosition);
if (!SUCCEEDED(hr = mfMediaSession->Start(nullptr, &startingPosition)))
break;
}
else if (mediaEventType == MEEndOfPresentation)
{
if (encoderParameters->IsQualityBasedVbr())
{
if (!SUCCEEDED(hr = UpdateVbrStreamProperties(audioEncoder, mediaSink)))
break;
}
}
else if (mediaEventType == MESessionEnded)
{
// MediaSession->GetEvent() MUST be called at least once
// after making the the following call to
// MediaSession->Close(), otherwise you'll end up
// with an constant bitrate file instead of a VBR
// one. I have not figured out why.
if (!SUCCEEDED(hr = mfMediaSession->Close()))
break;
}
eventStatus = GetNextMediaSessionEvent(mfMediaSession, &mediaEventType, &topologyStatus);
}
hr = mfMediaSession->Shutdown();
mfMediaSession->Release();
topology->Release();
if (FAILED(hr))
{
throw std::exception("Error occurred encoding file");
}
}