1 /* 2 * Copyright (c) 2002, 2003 Jerome Duval (jerome.duval@free.fr) 3 * Distributed under the terms of the MIT License. 4 */ 5 6 //! Multi-audio replacement media addon for BeOS 7 8 9 #include "MultiAudioNode.h" 10 11 #include <stdio.h> 12 #include <string.h> 13 14 #include <Autolock.h> 15 #include <Buffer.h> 16 #include <BufferGroup.h> 17 #include <Catalog.h> 18 #include <ParameterWeb.h> 19 #include <String.h> 20 21 #include <Referenceable.h> 22 23 #include "MultiAudioUtility.h" 24 #ifdef DEBUG 25 # define PRINTING 26 #endif 27 #include "debug.h" 28 #include "Resampler.h" 29 30 #undef B_TRANSLATION_CONTEXT 31 #define B_TRANSLATION_CONTEXT "MultiAudio" 32 33 #define PARAMETER_ID_INPUT_FREQUENCY 1 34 #define PARAMETER_ID_OUTPUT_FREQUENCY 2 35 36 37 //This represent an hardware output 38 class node_input { 39 public: 40 node_input(media_input& input, media_format format); 41 ~node_input(); 42 43 int32 fChannelId; 44 media_input fInput; 45 media_format fPreferredFormat; 46 media_format fFormat; 47 volatile uint32 fBufferCycle; 48 multi_buffer_info fOldBufferInfo; 49 BBuffer* fBuffer; 50 Resampler *fResampler; 51 }; 52 53 54 //This represent an hardware input 55 class node_output { 56 public: 57 node_output(media_output& output, media_format format); 58 ~node_output(); 59 60 int32 fChannelId; 61 media_output fOutput; 62 media_format fPreferredFormat; 63 media_format fFormat; 64 65 BBufferGroup* fBufferGroup; 66 bool fOutputEnabled; 67 uint64 fSamplesSent; 68 volatile uint32 fBufferCycle; 69 multi_buffer_info fOldBufferInfo; 70 Resampler *fResampler; 71 }; 72 73 74 struct FrameRateChangeCookie : public BReferenceable { 75 float oldFrameRate; 76 uint32 id; 77 }; 78 79 80 struct sample_rate_info { 81 uint32 multiAudioRate; 82 const char* name; 83 }; 84 85 86 static const sample_rate_info kSampleRateInfos[] = { 87 {B_SR_8000, "8000"}, 88 {B_SR_11025, "11025"}, 89 {B_SR_12000, "12000"}, 90 {B_SR_16000, "16000"}, 91 {B_SR_22050, "22050"}, 92 {B_SR_24000, "24000"}, 93 {B_SR_32000, "32000"}, 94 {B_SR_44100, "44100"}, 95 {B_SR_48000, "48000"}, 96 {B_SR_64000, "64000"}, 97 {B_SR_88200, "88200"}, 98 {B_SR_96000, "96000"}, 99 {B_SR_176400, "176400"}, 100 {B_SR_192000, "192000"}, 101 {B_SR_384000, "384000"}, 102 {B_SR_1536000, "1536000"}, 103 {} 104 }; 105 106 107 const char* kMultiControlString[] = { 108 "NAME IS ATTACHED", 109 B_TRANSLATE("Output"), B_TRANSLATE("Input"), B_TRANSLATE("Setup"), 110 B_TRANSLATE("Tone control"), B_TRANSLATE("Extended Setup"), 111 B_TRANSLATE("Enhanced Setup"), B_TRANSLATE("Master"), B_TRANSLATE("Beep"), 112 B_TRANSLATE("Phone"), B_TRANSLATE("Mic"), B_TRANSLATE("Line"), 113 B_TRANSLATE("CD"), B_TRANSLATE("Video"), B_TRANSLATE("Aux"), 114 B_TRANSLATE("Wave"), B_TRANSLATE("Gain"), B_TRANSLATE("Level"), 115 B_TRANSLATE("Volume"), B_TRANSLATE("Mute"), B_TRANSLATE("Enable"), 116 B_TRANSLATE("Stereo mix"), B_TRANSLATE("Mono mix"), 117 B_TRANSLATE("Output stereo mix"), B_TRANSLATE("Output mono mix"), 118 B_TRANSLATE("Output bass"), B_TRANSLATE("Output treble"), 119 B_TRANSLATE("Output 3D center"), B_TRANSLATE("Output 3D depth"), 120 B_TRANSLATE("Headphones"), B_TRANSLATE("SPDIF") 121 }; 122 123 124 // #pragma mark - 125 126 127 node_input::node_input(media_input& input, media_format format) 128 { 129 CALLED(); 130 fInput = input; 131 fPreferredFormat = format; 132 fBufferCycle = 1; 133 fBuffer = NULL; 134 fResampler = NULL; 135 } 136 137 138 node_input::~node_input() 139 { 140 CALLED(); 141 } 142 143 144 // #pragma mark - 145 146 147 node_output::node_output(media_output& output, media_format format) 148 : 149 fBufferGroup(NULL), 150 fOutputEnabled(true) 151 { 152 CALLED(); 153 fOutput = output; 154 fPreferredFormat = format; 155 fBufferCycle = 1; 156 fResampler = NULL; 157 } 158 159 160 node_output::~node_output() 161 { 162 CALLED(); 163 } 164 165 166 // #pragma mark - 167 168 169 MultiAudioNode::MultiAudioNode(BMediaAddOn* addon, const char* name, 170 MultiAudioDevice* device, int32 internalID, BMessage* config) 171 : 172 BMediaNode(name), 173 BBufferConsumer(B_MEDIA_RAW_AUDIO), 174 BBufferProducer(B_MEDIA_RAW_AUDIO), 175 BMediaEventLooper(), 176 fBufferLock("multi audio buffers"), 177 fThread(-1), 178 fDevice(device), 179 fTimeSourceStarted(false), 180 fWeb(NULL), 181 fConfig() 182 { 183 CALLED(); 184 fInitStatus = B_NO_INIT; 185 186 if (!device) 187 return; 188 189 fAddOn = addon; 190 fId = internalID; 191 192 AddNodeKind(B_PHYSICAL_OUTPUT); 193 AddNodeKind(B_PHYSICAL_INPUT); 194 195 // initialize our preferred format objects 196 memset(&fOutputPreferredFormat, 0, sizeof(fOutputPreferredFormat)); // set everything to wildcard first 197 fOutputPreferredFormat.type = B_MEDIA_RAW_AUDIO; 198 fOutputPreferredFormat.u.raw_audio.format = MultiAudio::convert_to_media_format(fDevice->FormatInfo().output.format); 199 fOutputPreferredFormat.u.raw_audio.valid_bits = MultiAudio::convert_to_valid_bits(fDevice->FormatInfo().output.format); 200 fOutputPreferredFormat.u.raw_audio.channel_count = 2; 201 fOutputPreferredFormat.u.raw_audio.frame_rate = MultiAudio::convert_to_sample_rate(fDevice->FormatInfo().output.rate); // measured in Hertz 202 fOutputPreferredFormat.u.raw_audio.byte_order = B_MEDIA_HOST_ENDIAN; 203 204 // we'll use the consumer's preferred buffer size, if any 205 fOutputPreferredFormat.u.raw_audio.buffer_size = fDevice->BufferList().return_playback_buffer_size 206 * (fOutputPreferredFormat.u.raw_audio.format & media_raw_audio_format::B_AUDIO_SIZE_MASK) 207 * fOutputPreferredFormat.u.raw_audio.channel_count; 208 209 // initialize our preferred format objects 210 memset(&fInputPreferredFormat, 0, sizeof(fInputPreferredFormat)); // set everything to wildcard first 211 fInputPreferredFormat.type = B_MEDIA_RAW_AUDIO; 212 fInputPreferredFormat.u.raw_audio.format = MultiAudio::convert_to_media_format(fDevice->FormatInfo().input.format); 213 fInputPreferredFormat.u.raw_audio.valid_bits = MultiAudio::convert_to_valid_bits(fDevice->FormatInfo().input.format); 214 fInputPreferredFormat.u.raw_audio.channel_count = 2; 215 fInputPreferredFormat.u.raw_audio.frame_rate = MultiAudio::convert_to_sample_rate(fDevice->FormatInfo().input.rate); // measured in Hertz 216 fInputPreferredFormat.u.raw_audio.byte_order = B_MEDIA_HOST_ENDIAN; 217 218 // we'll use the consumer's preferred buffer size, if any 219 fInputPreferredFormat.u.raw_audio.buffer_size = fDevice->BufferList().return_record_buffer_size 220 * (fInputPreferredFormat.u.raw_audio.format & media_raw_audio_format::B_AUDIO_SIZE_MASK) 221 * fInputPreferredFormat.u.raw_audio.channel_count; 222 223 224 if (config != NULL) { 225 fConfig = *config; 226 PRINT_OBJECT(*config); 227 } 228 229 fInitStatus = B_OK; 230 } 231 232 233 MultiAudioNode::~MultiAudioNode() 234 { 235 CALLED(); 236 fAddOn->GetConfigurationFor(this, NULL); 237 238 _StopOutputThread(); 239 BMediaEventLooper::Quit(); 240 241 fWeb = NULL; 242 } 243 244 245 status_t 246 MultiAudioNode::InitCheck() const 247 { 248 CALLED(); 249 return fInitStatus; 250 } 251 252 253 void 254 MultiAudioNode::GetFlavor(flavor_info* info, int32 id) 255 { 256 CALLED(); 257 if (info == NULL) 258 return; 259 260 info->flavor_flags = 0; 261 info->possible_count = 1; // one flavor at a time 262 info->in_format_count = 0; // no inputs 263 info->in_formats = 0; 264 info->out_format_count = 0; // no outputs 265 info->out_formats = 0; 266 info->internal_id = id; 267 268 info->name = (char*)"MultiAudioNode Node"; 269 info->info = (char*)"The MultiAudioNode node outputs to multi_audio " 270 "drivers."; 271 info->kinds = B_BUFFER_CONSUMER | B_BUFFER_PRODUCER | B_TIME_SOURCE 272 | B_PHYSICAL_OUTPUT | B_PHYSICAL_INPUT | B_CONTROLLABLE; 273 info->in_format_count = 1; // 1 input 274 media_format* inFormats = new media_format[info->in_format_count]; 275 GetFormat(&inFormats[0]); 276 info->in_formats = inFormats; 277 278 info->out_format_count = 1; // 1 output 279 media_format* outFormats = new media_format[info->out_format_count]; 280 GetFormat(&outFormats[0]); 281 info->out_formats = outFormats; 282 } 283 284 285 void 286 MultiAudioNode::GetFormat(media_format* format) 287 { 288 CALLED(); 289 if (format == NULL) 290 return; 291 292 format->type = B_MEDIA_RAW_AUDIO; 293 format->require_flags = B_MEDIA_MAUI_UNDEFINED_FLAGS; 294 format->deny_flags = B_MEDIA_MAUI_UNDEFINED_FLAGS; 295 format->u.raw_audio = media_raw_audio_format::wildcard; 296 } 297 298 299 //#pragma mark - BMediaNode 300 301 302 BMediaAddOn* 303 MultiAudioNode::AddOn(int32* _internalID) const 304 { 305 CALLED(); 306 // BeBook says this only gets called if we were in an add-on. 307 if (fAddOn != 0 && _internalID != NULL) 308 *_internalID = fId; 309 310 return fAddOn; 311 } 312 313 314 void 315 MultiAudioNode::Preroll() 316 { 317 CALLED(); 318 // XXX:Performance opportunity 319 BMediaNode::Preroll(); 320 } 321 322 323 status_t 324 MultiAudioNode::HandleMessage(int32 message, const void* data, size_t size) 325 { 326 CALLED(); 327 return B_ERROR; 328 } 329 330 331 void 332 MultiAudioNode::NodeRegistered() 333 { 334 CALLED(); 335 336 if (fInitStatus != B_OK) { 337 ReportError(B_NODE_IN_DISTRESS); 338 return; 339 } 340 341 node_input *currentInput = NULL; 342 int32 currentId = 0; 343 344 for (int32 i = 0; i < fDevice->Description().output_channel_count; i++) { 345 if (currentInput == NULL 346 || (fDevice->Description().channels[i].designations & B_CHANNEL_MONO_BUS) 347 || (fDevice->Description().channels[currentId].designations & B_CHANNEL_STEREO_BUS 348 && ( fDevice->Description().channels[i].designations & B_CHANNEL_LEFT || 349 !(fDevice->Description().channels[i].designations & B_CHANNEL_STEREO_BUS))) 350 || (fDevice->Description().channels[currentId].designations & B_CHANNEL_SURROUND_BUS 351 && ( fDevice->Description().channels[i].designations & B_CHANNEL_LEFT || 352 !(fDevice->Description().channels[i].designations & B_CHANNEL_SURROUND_BUS))) 353 ) { 354 PRINT(("NodeRegistered() : creating an input for %" B_PRIi32 "\n", 355 i)); 356 PRINT(("%" B_PRId32 "\t%d\t0x%" B_PRIx32 "\t0x%" B_PRIx32 "\n", 357 fDevice->Description().channels[i].channel_id, 358 fDevice->Description().channels[i].kind, 359 fDevice->Description().channels[i].designations, 360 fDevice->Description().channels[i].connectors)); 361 362 media_input* input = new media_input; 363 364 input->format = fOutputPreferredFormat; 365 input->destination.port = ControlPort(); 366 input->destination.id = fInputs.CountItems(); 367 input->node = Node(); 368 sprintf(input->name, "output %" B_PRId32, input->destination.id); 369 370 currentInput = new node_input(*input, fOutputPreferredFormat); 371 currentInput->fPreferredFormat.u.raw_audio.channel_count = 1; 372 currentInput->fInput.format = currentInput->fPreferredFormat; 373 delete currentInput->fResampler; 374 currentInput->fResampler = new 375 Resampler(currentInput->fPreferredFormat.AudioFormat(), 376 fOutputPreferredFormat.AudioFormat()); 377 378 currentInput->fChannelId = fDevice->Description().channels[i].channel_id; 379 fInputs.AddItem(currentInput); 380 381 currentId = i; 382 } else { 383 PRINT(("NodeRegistered() : adding a channel\n")); 384 currentInput->fPreferredFormat.u.raw_audio.channel_count++; 385 currentInput->fInput.format = currentInput->fPreferredFormat; 386 } 387 currentInput->fInput.format.u.raw_audio.format = media_raw_audio_format::wildcard.format; 388 } 389 390 node_output *currentOutput = NULL; 391 currentId = 0; 392 393 for (int32 i = fDevice->Description().output_channel_count; 394 i < fDevice->Description().output_channel_count 395 + fDevice->Description().input_channel_count; i++) { 396 if (currentOutput == NULL 397 || (fDevice->Description().channels[i].designations & B_CHANNEL_MONO_BUS) 398 || (fDevice->Description().channels[currentId].designations & B_CHANNEL_STEREO_BUS 399 && ( fDevice->Description().channels[i].designations & B_CHANNEL_LEFT || 400 !(fDevice->Description().channels[i].designations & B_CHANNEL_STEREO_BUS))) 401 || (fDevice->Description().channels[currentId].designations & B_CHANNEL_SURROUND_BUS 402 && ( fDevice->Description().channels[i].designations & B_CHANNEL_LEFT || 403 !(fDevice->Description().channels[i].designations & B_CHANNEL_SURROUND_BUS))) 404 ) { 405 PRINT(("NodeRegistered() : creating an output for %" B_PRIi32 "\n", 406 i)); 407 PRINT(("%" B_PRId32 "\t%d\t0x%" B_PRIx32 "\t0x%" B_PRIx32 "\n", 408 fDevice->Description().channels[i].channel_id, 409 fDevice->Description().channels[i].kind, 410 fDevice->Description().channels[i].designations, 411 fDevice->Description().channels[i].connectors)); 412 413 media_output *output = new media_output; 414 415 output->format = fInputPreferredFormat; 416 output->destination = media_destination::null; 417 output->source.port = ControlPort(); 418 output->source.id = fOutputs.CountItems(); 419 output->node = Node(); 420 sprintf(output->name, "input %" B_PRId32, output->source.id); 421 422 currentOutput = new node_output(*output, fInputPreferredFormat); 423 currentOutput->fPreferredFormat.u.raw_audio.channel_count = 1; 424 currentOutput->fOutput.format = currentOutput->fPreferredFormat; 425 delete currentOutput->fResampler; 426 currentOutput->fResampler = new 427 Resampler(fInputPreferredFormat.AudioFormat(), 428 currentOutput->fPreferredFormat.AudioFormat()); 429 430 currentOutput->fChannelId = fDevice->Description().channels[i].channel_id; 431 fOutputs.AddItem(currentOutput); 432 433 currentId = i; 434 } else { 435 PRINT(("NodeRegistered() : adding a channel\n")); 436 currentOutput->fPreferredFormat.u.raw_audio.channel_count++; 437 currentOutput->fOutput.format = currentOutput->fPreferredFormat; 438 } 439 } 440 441 // Set up our parameter web 442 fWeb = MakeParameterWeb(); 443 SetParameterWeb(fWeb); 444 445 // Apply configuration 446 #ifdef PRINTING 447 bigtime_t start = system_time(); 448 #endif 449 450 int32 index = 0; 451 int32 parameterID = 0; 452 const void *data; 453 ssize_t size; 454 while (fConfig.FindInt32("parameterID", index, ¶meterID) == B_OK) { 455 if (fConfig.FindData("parameterData", B_RAW_TYPE, index, &data, &size) 456 == B_OK) { 457 SetParameterValue(parameterID, TimeSource()->Now(), data, size); 458 } 459 index++; 460 } 461 462 PRINT(("apply configuration in : %" B_PRIdBIGTIME "\n", 463 system_time() - start)); 464 465 SetPriority(B_REAL_TIME_PRIORITY); 466 Run(); 467 } 468 469 470 status_t 471 MultiAudioNode::RequestCompleted(const media_request_info& info) 472 { 473 CALLED(); 474 475 if (info.what != media_request_info::B_REQUEST_FORMAT_CHANGE) 476 return B_OK; 477 478 FrameRateChangeCookie* cookie 479 = (FrameRateChangeCookie*)info.user_data; 480 if (cookie == NULL) 481 return B_OK; 482 483 BReference<FrameRateChangeCookie> cookieReference(cookie, true); 484 485 // if the request failed, we reset the frame rate 486 if (info.status != B_OK) { 487 if (cookie->id == PARAMETER_ID_INPUT_FREQUENCY) { 488 _SetNodeInputFrameRate(cookie->oldFrameRate); 489 if (fDevice->Description().output_rates & B_SR_SAME_AS_INPUT) 490 _SetNodeOutputFrameRate(cookie->oldFrameRate); 491 } else if (cookie->id == PARAMETER_ID_OUTPUT_FREQUENCY) 492 _SetNodeOutputFrameRate(cookie->oldFrameRate); 493 494 // TODO: If we have multiple connections, we should request to change 495 // the format back! 496 } 497 498 return B_OK; 499 } 500 501 502 void 503 MultiAudioNode::SetTimeSource(BTimeSource* timeSource) 504 { 505 CALLED(); 506 } 507 508 509 // #pragma mark - BBufferConsumer 510 511 512 status_t 513 MultiAudioNode::AcceptFormat(const media_destination& dest, 514 media_format* format) 515 { 516 // Check to make sure the format is okay, then remove 517 // any wildcards corresponding to our requirements. 518 CALLED(); 519 520 if (format == NULL) 521 return B_BAD_VALUE; 522 if (format->type != B_MEDIA_RAW_AUDIO) 523 return B_MEDIA_BAD_FORMAT; 524 525 node_input *channel = _FindInput(dest); 526 if (channel == NULL) 527 return B_MEDIA_BAD_DESTINATION; 528 529 /* media_format * myFormat = GetFormat(); 530 fprintf(stderr,"proposed format: "); 531 print_media_format(format); 532 fprintf(stderr,"\n"); 533 fprintf(stderr,"my format: "); 534 print_media_format(myFormat); 535 fprintf(stderr,"\n");*/ 536 // Be's format_is_compatible doesn't work. 537 // if (!format_is_compatible(*format,*myFormat)) { 538 539 channel->fFormat = channel->fPreferredFormat; 540 541 /*if(format->u.raw_audio.format == media_raw_audio_format::B_AUDIO_FLOAT 542 && channel->fPreferredFormat.u.raw_audio.format == media_raw_audio_format::B_AUDIO_SHORT) 543 format->u.raw_audio.format = media_raw_audio_format::B_AUDIO_FLOAT; 544 else*/ 545 format->u.raw_audio.format = channel->fPreferredFormat.u.raw_audio.format; 546 format->u.raw_audio.valid_bits = channel->fPreferredFormat.u.raw_audio.valid_bits; 547 548 format->u.raw_audio.frame_rate = channel->fPreferredFormat.u.raw_audio.frame_rate; 549 format->u.raw_audio.channel_count = channel->fPreferredFormat.u.raw_audio.channel_count; 550 format->u.raw_audio.byte_order = B_MEDIA_HOST_ENDIAN; 551 format->u.raw_audio.buffer_size = fDevice->BufferList().return_playback_buffer_size 552 * (format->u.raw_audio.format & media_raw_audio_format::B_AUDIO_SIZE_MASK) 553 * format->u.raw_audio.channel_count; 554 555 /*media_format myFormat; 556 GetFormat(&myFormat); 557 if (!format_is_acceptible(*format,myFormat)) { 558 fprintf(stderr,"<- B_MEDIA_BAD_FORMAT\n"); 559 return B_MEDIA_BAD_FORMAT; 560 }*/ 561 //AddRequirements(format); 562 return B_OK; 563 } 564 565 566 status_t 567 MultiAudioNode::GetNextInput(int32* cookie, media_input* _input) 568 { 569 CALLED(); 570 if (_input == NULL) 571 return B_BAD_VALUE; 572 573 if (*cookie >= fInputs.CountItems() || *cookie < 0) 574 return B_BAD_INDEX; 575 576 node_input *channel = (node_input *)fInputs.ItemAt(*cookie); 577 *_input = channel->fInput; 578 *cookie += 1; 579 PRINT(("input.format : %" B_PRIu32 "\n", 580 channel->fInput.format.u.raw_audio.format)); 581 return B_OK; 582 } 583 584 585 void 586 MultiAudioNode::DisposeInputCookie(int32 cookie) 587 { 588 CALLED(); 589 // nothing to do since our cookies are just integers 590 } 591 592 593 void 594 MultiAudioNode::BufferReceived(BBuffer* buffer) 595 { 596 //CALLED(); 597 switch (buffer->Header()->type) { 598 /*case B_MEDIA_PARAMETERS: 599 { 600 status_t status = ApplyParameterData(buffer->Data(),buffer->SizeUsed()); 601 if (status != B_OK) { 602 fprintf(stderr,"ApplyParameterData in MultiAudioNode::BufferReceived failed\n"); 603 } 604 buffer->Recycle(); 605 } 606 break;*/ 607 case B_MEDIA_RAW_AUDIO: 608 if (buffer->Flags() & BBuffer::B_SMALL_BUFFER) { 609 fprintf(stderr,"NOT IMPLEMENTED: B_SMALL_BUFFER in MultiAudioNode::BufferReceived\n"); 610 // XXX: implement this part 611 buffer->Recycle(); 612 } else { 613 media_timed_event event(buffer->Header()->start_time, BTimedEventQueue::B_HANDLE_BUFFER, 614 buffer, BTimedEventQueue::B_RECYCLE_BUFFER); 615 status_t status = EventQueue()->AddEvent(event); 616 if (status != B_OK) { 617 fprintf(stderr,"EventQueue()->AddEvent(event) in MultiAudioNode::BufferReceived failed\n"); 618 buffer->Recycle(); 619 } 620 } 621 break; 622 default: 623 fprintf(stderr,"unexpected buffer type in MultiAudioNode::BufferReceived\n"); 624 buffer->Recycle(); 625 break; 626 } 627 } 628 629 630 void 631 MultiAudioNode::ProducerDataStatus(const media_destination& forWhom, 632 int32 status, bigtime_t atPerformanceTime) 633 { 634 //CALLED(); 635 636 node_input *channel = _FindInput(forWhom); 637 if (channel == NULL) { 638 fprintf(stderr,"invalid destination received in MultiAudioNode::ProducerDataStatus\n"); 639 return; 640 } 641 642 media_timed_event event(atPerformanceTime, BTimedEventQueue::B_DATA_STATUS, 643 &channel->fInput, BTimedEventQueue::B_NO_CLEANUP, status, 0, NULL); 644 EventQueue()->AddEvent(event); 645 } 646 647 648 status_t 649 MultiAudioNode::GetLatencyFor(const media_destination& forWhom, 650 bigtime_t* _latency, media_node_id* _timeSource) 651 { 652 CALLED(); 653 if (_latency == NULL || _timeSource == NULL) 654 return B_BAD_VALUE; 655 656 node_input *channel = _FindInput(forWhom); 657 if (channel == NULL) 658 return B_MEDIA_BAD_DESTINATION; 659 660 *_latency = EventLatency(); 661 *_timeSource = TimeSource()->ID(); 662 return B_OK; 663 } 664 665 666 status_t 667 MultiAudioNode::Connected(const media_source& producer, 668 const media_destination& where, const media_format& with_format, 669 media_input* out_input) 670 { 671 CALLED(); 672 if (out_input == 0) { 673 fprintf(stderr, "<- B_BAD_VALUE\n"); 674 return B_BAD_VALUE; // no crashing 675 } 676 677 node_input *channel = _FindInput(where); 678 679 if (channel == NULL) { 680 fprintf(stderr, "<- B_MEDIA_BAD_DESTINATION\n"); 681 return B_MEDIA_BAD_DESTINATION; 682 } 683 684 _UpdateInternalLatency(with_format); 685 686 // record the agreed upon values 687 channel->fInput.source = producer; 688 channel->fInput.format = with_format; 689 *out_input = channel->fInput; 690 691 _StartOutputThreadIfNeeded(); 692 693 return B_OK; 694 } 695 696 697 void 698 MultiAudioNode::Disconnected(const media_source& producer, 699 const media_destination& where) 700 { 701 CALLED(); 702 node_input *channel = _FindInput(where); 703 704 if (channel == NULL || channel->fInput.source != producer) 705 return; 706 707 channel->fInput.source = media_source::null; 708 channel->fInput.format = channel->fPreferredFormat; 709 710 BAutolock locker(fBufferLock); 711 _FillWithZeros(*channel); 712 //GetFormat(&channel->fInput.format); 713 } 714 715 716 status_t 717 MultiAudioNode::FormatChanged(const media_source& producer, 718 const media_destination& consumer, int32 change_tag, 719 const media_format& format) 720 { 721 CALLED(); 722 node_input *channel = _FindInput(consumer); 723 724 if(channel==NULL) { 725 fprintf(stderr,"<- B_MEDIA_BAD_DESTINATION\n"); 726 return B_MEDIA_BAD_DESTINATION; 727 } 728 if (channel->fInput.source != producer) { 729 return B_MEDIA_BAD_SOURCE; 730 } 731 732 return B_ERROR; 733 } 734 735 736 status_t 737 MultiAudioNode::SeekTagRequested(const media_destination& destination, 738 bigtime_t in_target_time, 739 uint32 in_flags, 740 media_seek_tag * out_seek_tag, 741 bigtime_t * out_tagged_time, 742 uint32 * out_flags) 743 { 744 CALLED(); 745 return BBufferConsumer::SeekTagRequested(destination,in_target_time,in_flags, 746 out_seek_tag,out_tagged_time,out_flags); 747 } 748 749 750 // #pragma mark - BBufferProducer 751 752 753 status_t 754 MultiAudioNode::FormatSuggestionRequested(media_type type, int32 /*quality*/, 755 media_format* format) 756 { 757 // FormatSuggestionRequested() is not necessarily part of the format negotiation 758 // process; it's simply an interrogation -- the caller wants to see what the node's 759 // preferred data format is, given a suggestion by the caller. 760 CALLED(); 761 762 if (!format) 763 { 764 fprintf(stderr, "\tERROR - NULL format pointer passed in!\n"); 765 return B_BAD_VALUE; 766 } 767 768 // this is the format we'll be returning (our preferred format) 769 *format = fInputPreferredFormat; 770 771 // a wildcard type is okay; we can specialize it 772 if (type == B_MEDIA_UNKNOWN_TYPE) type = B_MEDIA_RAW_AUDIO; 773 774 // we only support raw audio 775 if (type != B_MEDIA_RAW_AUDIO) return B_MEDIA_BAD_FORMAT; 776 else return B_OK; 777 } 778 779 780 status_t 781 MultiAudioNode::FormatProposal(const media_source& output, media_format* format) 782 { 783 // FormatProposal() is the first stage in the BMediaRoster::Connect() process. We hand 784 // out a suggested format, with wildcards for any variations we support. 785 CALLED(); 786 node_output *channel = _FindOutput(output); 787 788 // is this a proposal for our select output? 789 if (channel == NULL) 790 { 791 fprintf(stderr, "MultiAudioNode::FormatProposal returning B_MEDIA_BAD_SOURCE\n"); 792 return B_MEDIA_BAD_SOURCE; 793 } 794 795 // we only support floating-point raw audio, so we always return that, but we 796 // supply an error code depending on whether we found the proposal acceptable. 797 media_type requestedType = format->type; 798 *format = channel->fPreferredFormat; 799 if ((requestedType != B_MEDIA_UNKNOWN_TYPE) && (requestedType != B_MEDIA_RAW_AUDIO)) 800 { 801 fprintf(stderr, "MultiAudioNode::FormatProposal returning B_MEDIA_BAD_FORMAT\n"); 802 return B_MEDIA_BAD_FORMAT; 803 } 804 else return B_OK; // raw audio or wildcard type, either is okay by us 805 } 806 807 808 status_t 809 MultiAudioNode::FormatChangeRequested(const media_source& source, 810 const media_destination& destination, media_format* format, 811 int32* _deprecated_) 812 { 813 CALLED(); 814 815 // we don't support any other formats, so we just reject any format changes. 816 return B_ERROR; 817 } 818 819 820 status_t 821 MultiAudioNode::GetNextOutput(int32* cookie, media_output* out_output) 822 { 823 CALLED(); 824 825 if ((*cookie < fOutputs.CountItems()) && (*cookie >= 0)) { 826 node_output *channel = (node_output *)fOutputs.ItemAt(*cookie); 827 *out_output = channel->fOutput; 828 *cookie += 1; 829 return B_OK; 830 } else 831 return B_BAD_INDEX; 832 } 833 834 835 status_t 836 MultiAudioNode::DisposeOutputCookie(int32 cookie) 837 { 838 CALLED(); 839 // do nothing because we don't use the cookie for anything special 840 return B_OK; 841 } 842 843 844 status_t 845 MultiAudioNode::SetBufferGroup(const media_source& for_source, 846 BBufferGroup* newGroup) 847 { 848 CALLED(); 849 850 node_output *channel = _FindOutput(for_source); 851 852 // is this our output? 853 if (channel == NULL) 854 { 855 fprintf(stderr, "MultiAudioNode::SetBufferGroup returning B_MEDIA_BAD_SOURCE\n"); 856 return B_MEDIA_BAD_SOURCE; 857 } 858 859 // Are we being passed the buffer group we're already using? 860 if (newGroup == channel->fBufferGroup) return B_OK; 861 862 // Ahh, someone wants us to use a different buffer group. At this point we delete 863 // the one we are using and use the specified one instead. If the specified group is 864 // NULL, we need to recreate one ourselves, and use *that*. Note that if we're 865 // caching a BBuffer that we requested earlier, we have to Recycle() that buffer 866 // *before* deleting the buffer group, otherwise we'll deadlock waiting for that 867 // buffer to be recycled! 868 delete channel->fBufferGroup; // waits for all buffers to recycle 869 if (newGroup != NULL) 870 { 871 // we were given a valid group; just use that one from now on 872 channel->fBufferGroup = newGroup; 873 } 874 else 875 { 876 // we were passed a NULL group pointer; that means we construct 877 // our own buffer group to use from now on 878 size_t size = channel->fOutput.format.u.raw_audio.buffer_size; 879 int32 count = int32(fLatency / BufferDuration() + 1 + 1); 880 BBufferGroup* group = new BBufferGroup(size, count); 881 if (group == NULL || group->InitCheck() != B_OK) { 882 delete group; 883 fprintf(stderr, "MultiAudioNode::SetBufferGroup failed to" 884 "instantiate a new group.\n"); 885 return B_ERROR; 886 } 887 channel->fBufferGroup = group; 888 } 889 890 return B_OK; 891 } 892 893 894 status_t 895 MultiAudioNode::PrepareToConnect(const media_source& what, 896 const media_destination& where, media_format* format, 897 media_source* source, char* name) 898 { 899 CALLED(); 900 901 // is this our output? 902 node_output* channel = _FindOutput(what); 903 if (channel == NULL) { 904 fprintf(stderr, "MultiAudioNode::PrepareToConnect returning B_MEDIA_BAD_SOURCE\n"); 905 return B_MEDIA_BAD_SOURCE; 906 } 907 908 // are we already connected? 909 if (channel->fOutput.destination != media_destination::null) 910 return B_MEDIA_ALREADY_CONNECTED; 911 912 // the format may not yet be fully specialized (the consumer might have 913 // passed back some wildcards). Finish specializing it now, and return an 914 // error if we don't support the requested format. 915 if (format->type != B_MEDIA_RAW_AUDIO) { 916 fprintf(stderr, "\tnon-raw-audio format?!\n"); 917 return B_MEDIA_BAD_FORMAT; 918 } 919 920 // !!! validate all other fields except for buffer_size here, because the 921 // consumer might have supplied different values from AcceptFormat()? 922 923 // check the buffer size, which may still be wildcarded 924 if (format->u.raw_audio.buffer_size 925 == media_raw_audio_format::wildcard.buffer_size) { 926 format->u.raw_audio.buffer_size = 2048; 927 // pick something comfortable to suggest 928 fprintf(stderr, "\tno buffer size provided, suggesting %lu\n", 929 format->u.raw_audio.buffer_size); 930 } else { 931 fprintf(stderr, "\tconsumer suggested buffer_size %lu\n", 932 format->u.raw_audio.buffer_size); 933 } 934 935 // Now reserve the connection, and return information about it 936 channel->fOutput.destination = where; 937 channel->fOutput.format = *format; 938 939 *source = channel->fOutput.source; 940 #ifdef __HAIKU__ 941 strlcpy(name, channel->fOutput.name, B_MEDIA_NAME_LENGTH); 942 #else 943 strncpy(name, channel->fOutput.name, B_MEDIA_NAME_LENGTH); 944 #endif 945 return B_OK; 946 } 947 948 949 void 950 MultiAudioNode::Connect(status_t error, const media_source& source, 951 const media_destination& destination, const media_format& format, 952 char* name) 953 { 954 CALLED(); 955 956 // is this our output? 957 node_output* channel = _FindOutput(source); 958 if (channel == NULL) { 959 fprintf(stderr, "MultiAudioNode::Connect returning (cause : B_MEDIA_BAD_SOURCE)\n"); 960 return; 961 } 962 963 // If something earlier failed, Connect() might still be called, but with 964 // a non-zero error code. When that happens we simply unreserve the 965 // connection and do nothing else. 966 if (error) { 967 channel->fOutput.destination = media_destination::null; 968 channel->fOutput.format = channel->fPreferredFormat; 969 return; 970 } 971 972 // Okay, the connection has been confirmed. Record the destination and 973 // format that we agreed on, and report our connection name again. 974 channel->fOutput.destination = destination; 975 channel->fOutput.format = format; 976 #ifdef __HAIKU__ 977 strlcpy(name, channel->fOutput.name, B_MEDIA_NAME_LENGTH); 978 #else 979 strncpy(name, channel->fOutput.name, B_MEDIA_NAME_LENGTH); 980 #endif 981 982 // reset our buffer duration, etc. to avoid later calculations 983 bigtime_t duration = channel->fOutput.format.u.raw_audio.buffer_size * 10000 984 / ((channel->fOutput.format.u.raw_audio.format & media_raw_audio_format::B_AUDIO_SIZE_MASK) 985 * channel->fOutput.format.u.raw_audio.channel_count) 986 / ((int32)(channel->fOutput.format.u.raw_audio.frame_rate / 100)); 987 988 SetBufferDuration(duration); 989 990 // Now that we're connected, we can determine our downstream latency. 991 // Do so, then make sure we get our events early enough. 992 media_node_id id; 993 FindLatencyFor(channel->fOutput.destination, &fLatency, &id); 994 PRINT(("\tdownstream latency = %" B_PRIdBIGTIME "\n", fLatency)); 995 996 fInternalLatency = BufferDuration(); 997 PRINT(("\tbuffer-filling took %" B_PRIdBIGTIME " usec on this machine\n", 998 fInternalLatency)); 999 //SetEventLatency(fLatency + fInternalLatency); 1000 1001 // Set up the buffer group for our connection, as long as nobody handed us 1002 // a buffer group (via SetBufferGroup()) prior to this. That can happen, 1003 // for example, if the consumer calls SetOutputBuffersFor() on us from 1004 // within its Connected() method. 1005 if (!channel->fBufferGroup) 1006 _AllocateBuffers(*channel); 1007 1008 _StartOutputThreadIfNeeded(); 1009 } 1010 1011 1012 void 1013 MultiAudioNode::Disconnect(const media_source& what, 1014 const media_destination& where) 1015 { 1016 CALLED(); 1017 1018 // is this our output? 1019 node_output* channel = _FindOutput(what); 1020 if (channel == NULL) { 1021 fprintf(stderr, "MultiAudioNode::Disconnect() returning (cause : B_MEDIA_BAD_SOURCE)\n"); 1022 return; 1023 } 1024 1025 // Make sure that our connection is the one being disconnected 1026 if (where == channel->fOutput.destination 1027 && what == channel->fOutput.source) { 1028 channel->fOutput.destination = media_destination::null; 1029 channel->fOutput.format = channel->fPreferredFormat; 1030 delete channel->fBufferGroup; 1031 channel->fBufferGroup = NULL; 1032 } else { 1033 fprintf(stderr, "\tDisconnect() called with wrong source/destination (" 1034 "%" B_PRId32 "/%" B_PRId32 "), ours is (%" B_PRId32 "/%" B_PRId32 1035 ")\n", what.id, where.id, channel->fOutput.source.id, 1036 channel->fOutput.destination.id); 1037 } 1038 } 1039 1040 1041 void 1042 MultiAudioNode::LateNoticeReceived(const media_source& what, bigtime_t howMuch, 1043 bigtime_t performanceTime) 1044 { 1045 CALLED(); 1046 1047 // is this our output? 1048 node_output *channel = _FindOutput(what); 1049 if (channel == NULL) 1050 return; 1051 1052 // If we're late, we need to catch up. Respond in a manner appropriate 1053 // to our current run mode. 1054 if (RunMode() == B_RECORDING) { 1055 // A hardware capture node can't adjust; it simply emits buffers at 1056 // appropriate points. We (partially) simulate this by not adjusting 1057 // our behavior upon receiving late notices -- after all, the hardware 1058 // can't choose to capture "sooner".... 1059 } else if (RunMode() == B_INCREASE_LATENCY) { 1060 // We're late, and our run mode dictates that we try to produce buffers 1061 // earlier in order to catch up. This argues that the downstream nodes 1062 // are not properly reporting their latency, but there's not much we can 1063 // do about that at the moment, so we try to start producing buffers 1064 // earlier to compensate. 1065 fInternalLatency += howMuch; 1066 SetEventLatency(fLatency + fInternalLatency); 1067 1068 fprintf(stderr, "\tincreasing latency to %" B_PRIdBIGTIME"\n", 1069 fLatency + fInternalLatency); 1070 } else { 1071 // The other run modes dictate various strategies for sacrificing data 1072 // quality in the interests of timely data delivery. The way *we* do 1073 // this is to skip a buffer, which catches us up in time by one buffer 1074 // duration. 1075 /*size_t nSamples = fOutput.format.u.raw_audio.buffer_size / sizeof(float); 1076 mSamplesSent += nSamples;*/ 1077 1078 fprintf(stderr, "\tskipping a buffer to try to catch up\n"); 1079 } 1080 } 1081 1082 1083 void 1084 MultiAudioNode::EnableOutput(const media_source& what, bool enabled, 1085 int32* _deprecated_) 1086 { 1087 CALLED(); 1088 1089 // If I had more than one output, I'd have to walk my list of output 1090 // records to see which one matched the given source, and then 1091 // enable/disable that one. But this node only has one output, so I 1092 // just make sure the given source matches, then set the enable state 1093 // accordingly. 1094 node_output *channel = _FindOutput(what); 1095 if (channel != NULL) 1096 channel->fOutputEnabled = enabled; 1097 } 1098 1099 1100 void 1101 MultiAudioNode::AdditionalBufferRequested(const media_source& source, 1102 media_buffer_id previousBuffer, bigtime_t previousTime, 1103 const media_seek_tag* previousTag) 1104 { 1105 CALLED(); 1106 // we don't support offline mode 1107 return; 1108 } 1109 1110 1111 // #pragma mark - BMediaEventLooper 1112 1113 1114 void 1115 MultiAudioNode::HandleEvent(const media_timed_event* event, bigtime_t lateness, 1116 bool realTimeEvent) 1117 { 1118 //CALLED(); 1119 switch (event->type) { 1120 case BTimedEventQueue::B_START: 1121 _HandleStart(event, lateness, realTimeEvent); 1122 break; 1123 case BTimedEventQueue::B_SEEK: 1124 _HandleSeek(event, lateness, realTimeEvent); 1125 break; 1126 case BTimedEventQueue::B_WARP: 1127 _HandleWarp(event, lateness, realTimeEvent); 1128 break; 1129 case BTimedEventQueue::B_STOP: 1130 _HandleStop(event, lateness, realTimeEvent); 1131 break; 1132 case BTimedEventQueue::B_HANDLE_BUFFER: 1133 if (RunState() == BMediaEventLooper::B_STARTED) 1134 _HandleBuffer(event, lateness, realTimeEvent); 1135 break; 1136 case BTimedEventQueue::B_DATA_STATUS: 1137 _HandleDataStatus(event, lateness, realTimeEvent); 1138 break; 1139 case BTimedEventQueue::B_PARAMETER: 1140 _HandleParameter(event, lateness, realTimeEvent); 1141 break; 1142 default: 1143 fprintf(stderr," unknown event type: %" B_PRId32 "\n", event->type); 1144 break; 1145 } 1146 } 1147 1148 1149 status_t 1150 MultiAudioNode::_HandleBuffer(const media_timed_event* event, 1151 bigtime_t lateness, bool realTimeEvent) 1152 { 1153 //CALLED(); 1154 BBuffer* buffer = const_cast<BBuffer*>((BBuffer*)event->pointer); 1155 if (buffer == NULL) 1156 return B_BAD_VALUE; 1157 1158 //PRINT(("buffer->Header()->destination : %i\n", buffer->Header()->destination)); 1159 1160 node_input* channel = _FindInput(buffer->Header()->destination); 1161 if (channel == NULL) { 1162 buffer->Recycle(); 1163 return B_MEDIA_BAD_DESTINATION; 1164 } 1165 1166 // if the buffer is late, we ignore it and report the fact to the producer 1167 // who sent it to us 1168 if (RunMode() != B_OFFLINE && RunMode() != B_RECORDING && lateness > 0) { 1169 // lateness doesn't matter in offline mode or in recording mode 1170 //mLateBuffers++; 1171 NotifyLateProducer(channel->fInput.source, lateness, event->event_time); 1172 fprintf(stderr," <- LATE BUFFER : %" B_PRIdBIGTIME "\n", lateness); 1173 buffer->Recycle(); 1174 } else { 1175 //WriteBuffer(buffer, *channel); 1176 // TODO: This seems like a very fragile mechanism to wait until 1177 // the previous buffer for this channel has been processed... 1178 if (channel->fBuffer != NULL) { 1179 PRINT(("MultiAudioNode::HandleBuffer snoozing recycling channelId : %" 1180 B_PRIi32 ", how_early:%" B_PRIdBIGTIME "\n", 1181 channel->fChannelId, lateness)); 1182 //channel->fBuffer->Recycle(); 1183 snooze(100); 1184 if (channel->fBuffer != NULL) 1185 buffer->Recycle(); 1186 else 1187 channel->fBuffer = buffer; 1188 } else { 1189 //PRINT(("MultiAudioNode::HandleBuffer writing channelId : %li, how_early:%Ld\n", channel->fChannelId, howEarly)); 1190 channel->fBuffer = buffer; 1191 } 1192 } 1193 return B_OK; 1194 } 1195 1196 1197 status_t 1198 MultiAudioNode::_HandleDataStatus(const media_timed_event* event, 1199 bigtime_t lateness, bool realTimeEvent) 1200 { 1201 //CALLED(); 1202 PRINT(("MultiAudioNode::HandleDataStatus status:%" B_PRIi32 1203 ", lateness:%" B_PRIiBIGTIME "\n", event->data, lateness)); 1204 switch (event->data) { 1205 case B_DATA_NOT_AVAILABLE: 1206 break; 1207 case B_DATA_AVAILABLE: 1208 break; 1209 case B_PRODUCER_STOPPED: 1210 break; 1211 default: 1212 break; 1213 } 1214 return B_OK; 1215 } 1216 1217 1218 status_t 1219 MultiAudioNode::_HandleStart(const media_timed_event *event, bigtime_t lateness, 1220 bool realTimeEvent) 1221 { 1222 CALLED(); 1223 if (RunState() != B_STARTED) { 1224 } 1225 return B_OK; 1226 } 1227 1228 1229 status_t 1230 MultiAudioNode::_HandleSeek(const media_timed_event* event, bigtime_t lateness, 1231 bool realTimeEvent) 1232 { 1233 CALLED(); 1234 PRINT(("MultiAudioNode::HandleSeek(t=%" B_PRIdBIGTIME ",d=%" B_PRIi32 1235 ",bd=%" B_PRId64 ")\n", 1236 event->event_time,event->data,event->bigdata)); 1237 return B_OK; 1238 } 1239 1240 1241 status_t 1242 MultiAudioNode::_HandleWarp(const media_timed_event* event, bigtime_t lateness, 1243 bool realTimeEvent) 1244 { 1245 CALLED(); 1246 return B_OK; 1247 } 1248 1249 1250 status_t 1251 MultiAudioNode::_HandleStop(const media_timed_event* event, bigtime_t lateness, 1252 bool realTimeEvent) 1253 { 1254 CALLED(); 1255 // flush the queue so downstreamers don't get any more 1256 EventQueue()->FlushEvents(0, BTimedEventQueue::B_ALWAYS, true, 1257 BTimedEventQueue::B_HANDLE_BUFFER); 1258 1259 //_StopOutputThread(); 1260 return B_OK; 1261 } 1262 1263 1264 status_t 1265 MultiAudioNode::_HandleParameter(const media_timed_event* event, 1266 bigtime_t lateness, bool realTimeEvent) 1267 { 1268 CALLED(); 1269 return B_OK; 1270 } 1271 1272 1273 // #pragma mark - BTimeSource 1274 1275 1276 void 1277 MultiAudioNode::SetRunMode(run_mode mode) 1278 { 1279 CALLED(); 1280 PRINT(("MultiAudioNode::SetRunMode mode:%i\n", mode)); 1281 //BTimeSource::SetRunMode(mode); 1282 } 1283 1284 1285 status_t 1286 MultiAudioNode::TimeSourceOp(const time_source_op_info& op, void* _reserved) 1287 { 1288 CALLED(); 1289 switch (op.op) { 1290 case B_TIMESOURCE_START: 1291 PRINT(("TimeSourceOp op B_TIMESOURCE_START\n")); 1292 if (RunState() != BMediaEventLooper::B_STARTED) { 1293 fTimeSourceStarted = true; 1294 _StartOutputThreadIfNeeded(); 1295 1296 media_timed_event startEvent(0, BTimedEventQueue::B_START); 1297 EventQueue()->AddEvent(startEvent); 1298 } 1299 break; 1300 case B_TIMESOURCE_STOP: 1301 PRINT(("TimeSourceOp op B_TIMESOURCE_STOP\n")); 1302 if (RunState() == BMediaEventLooper::B_STARTED) { 1303 media_timed_event stopEvent(0, BTimedEventQueue::B_STOP); 1304 EventQueue()->AddEvent(stopEvent); 1305 fTimeSourceStarted = false; 1306 _StopOutputThread(); 1307 PublishTime(0, 0, 0); 1308 } 1309 break; 1310 case B_TIMESOURCE_STOP_IMMEDIATELY: 1311 PRINT(("TimeSourceOp op B_TIMESOURCE_STOP_IMMEDIATELY\n")); 1312 if (RunState() == BMediaEventLooper::B_STARTED) { 1313 media_timed_event stopEvent(0, BTimedEventQueue::B_STOP); 1314 EventQueue()->AddEvent(stopEvent); 1315 fTimeSourceStarted = false; 1316 _StopOutputThread(); 1317 PublishTime(0, 0, 0); 1318 } 1319 break; 1320 case B_TIMESOURCE_SEEK: 1321 PRINT(("TimeSourceOp op B_TIMESOURCE_SEEK\n")); 1322 BroadcastTimeWarp(op.real_time, op.performance_time); 1323 break; 1324 default: 1325 break; 1326 } 1327 return B_OK; 1328 } 1329 1330 1331 // #pragma mark - BControllable 1332 1333 1334 status_t 1335 MultiAudioNode::GetParameterValue(int32 id, bigtime_t* lastChange, void* value, 1336 size_t* size) 1337 { 1338 CALLED(); 1339 1340 PRINT(("id : %" B_PRIi32 "\n", id)); 1341 BParameter* parameter = NULL; 1342 for (int32 i = 0; i < fWeb->CountParameters(); i++) { 1343 parameter = fWeb->ParameterAt(i); 1344 if (parameter->ID() == id) 1345 break; 1346 } 1347 1348 if (parameter == NULL) { 1349 // Hmmm, we were asked for a parameter that we don't actually 1350 // support. Report an error back to the caller. 1351 PRINT(("\terror - asked for illegal parameter %" B_PRId32 "\n", id)); 1352 return B_ERROR; 1353 } 1354 1355 if (id == PARAMETER_ID_INPUT_FREQUENCY 1356 || id == PARAMETER_ID_OUTPUT_FREQUENCY) { 1357 const multi_format_info& info = fDevice->FormatInfo(); 1358 1359 uint32 rate = id == PARAMETER_ID_INPUT_FREQUENCY 1360 ? info.input.rate : info.output.rate; 1361 1362 if (*size < sizeof(rate)) 1363 return B_ERROR; 1364 1365 memcpy(value, &rate, sizeof(rate)); 1366 *size = sizeof(rate); 1367 return B_OK; 1368 } 1369 1370 multi_mix_value_info info; 1371 multi_mix_value values[2]; 1372 info.values = values; 1373 info.item_count = 0; 1374 multi_mix_control* controls = fDevice->MixControlInfo().controls; 1375 int32 control_id = controls[id - 100].id; 1376 1377 if (*size < sizeof(float)) 1378 return B_ERROR; 1379 1380 if (parameter->Type() == BParameter::B_CONTINUOUS_PARAMETER) { 1381 info.item_count = 1; 1382 values[0].id = control_id; 1383 1384 if (parameter->CountChannels() == 2) { 1385 if (*size < 2*sizeof(float)) 1386 return B_ERROR; 1387 info.item_count = 2; 1388 values[1].id = controls[id + 1 - 100].id; 1389 } 1390 } else if(parameter->Type() == BParameter::B_DISCRETE_PARAMETER) { 1391 info.item_count = 1; 1392 values[0].id = control_id; 1393 } 1394 1395 if (info.item_count > 0) { 1396 status_t status = fDevice->GetMix(&info); 1397 if (status != B_OK) { 1398 fprintf(stderr, "Failed on DRIVER_GET_MIX\n"); 1399 } else { 1400 if (parameter->Type() == BParameter::B_CONTINUOUS_PARAMETER) { 1401 ((float*)value)[0] = values[0].gain; 1402 *size = sizeof(float); 1403 1404 if (parameter->CountChannels() == 2) { 1405 ((float*)value)[1] = values[1].gain; 1406 *size = 2*sizeof(float); 1407 } 1408 1409 for (uint32 i = 0; i < *size / sizeof(float); i++) { 1410 PRINT(("GetParameterValue B_CONTINUOUS_PARAMETER value[%" 1411 B_PRIi32 "] : %f\n", i, ((float*)value)[i])); 1412 } 1413 } else if (parameter->Type() == BParameter::B_DISCRETE_PARAMETER) { 1414 BDiscreteParameter* discrete = (BDiscreteParameter*)parameter; 1415 if (discrete->CountItems() <= 2) 1416 ((int32*)value)[0] = values[0].enable ? 1 : 0; 1417 else 1418 ((int32*)value)[0] = values[0].mux; 1419 1420 *size = sizeof(int32); 1421 1422 for (uint32 i = 0; i < *size / sizeof(int32); i++) { 1423 PRINT(("GetParameterValue B_DISCRETE_PARAMETER value[%" B_PRIi32 1424 "] : %" B_PRIi32 "\n", i, ((int32*)value)[i])); 1425 } 1426 } 1427 } 1428 } 1429 return B_OK; 1430 } 1431 1432 1433 void 1434 MultiAudioNode::SetParameterValue(int32 id, bigtime_t performanceTime, 1435 const void* value, size_t size) 1436 { 1437 CALLED(); 1438 PRINT(("id : %" B_PRIi32 ", performance_time : %" B_PRIdBIGTIME 1439 ", size : %" B_PRIuSIZE "\n", id, performanceTime, size)); 1440 1441 BParameter* parameter = NULL; 1442 for (int32 i = 0; i < fWeb->CountParameters(); i++) { 1443 parameter = fWeb->ParameterAt(i); 1444 if (parameter->ID() == id) 1445 break; 1446 } 1447 1448 if (parameter == NULL) 1449 return; 1450 1451 if (id == PARAMETER_ID_OUTPUT_FREQUENCY 1452 || (id == PARAMETER_ID_INPUT_FREQUENCY 1453 && (fDevice->Description().output_rates & B_SR_SAME_AS_INPUT))) { 1454 uint32 rate; 1455 if (size < sizeof(rate)) 1456 return; 1457 memcpy(&rate, value, sizeof(rate)); 1458 1459 if (rate == fOutputPreferredFormat.u.raw_audio.frame_rate) 1460 return; 1461 1462 // create a cookie RequestCompleted() can get the old frame rate from, 1463 // if anything goes wrong 1464 FrameRateChangeCookie* cookie 1465 = new(std::nothrow) FrameRateChangeCookie; 1466 if (cookie == NULL) 1467 return; 1468 1469 cookie->oldFrameRate = fOutputPreferredFormat.u.raw_audio.frame_rate; 1470 cookie->id = id; 1471 BReference<FrameRateChangeCookie> cookieReference(cookie, true); 1472 1473 // NOTE: What we should do is call RequestFormatChange() for all 1474 // connections and change the device's format in RequestCompleted(). 1475 // Unfortunately we need the new buffer size first, which we only get 1476 // from the device after changing the format. So we do that now and 1477 // reset it in RequestCompleted(), if something went wrong. This causes 1478 // the buffers we receive until then to be played incorrectly leading 1479 // to unpleasant noise. 1480 float frameRate = MultiAudio::convert_to_sample_rate(rate); 1481 if (_SetNodeInputFrameRate(frameRate) != B_OK) 1482 return; 1483 1484 for (int32 i = 0; i < fInputs.CountItems(); i++) { 1485 node_input* channel = (node_input*)fInputs.ItemAt(i); 1486 if (channel->fInput.source == media_source::null) 1487 continue; 1488 1489 media_format newFormat = channel->fInput.format; 1490 newFormat.u.raw_audio.frame_rate = frameRate; 1491 newFormat.u.raw_audio.buffer_size 1492 = fOutputPreferredFormat.u.raw_audio.buffer_size; 1493 1494 int32 changeTag = 0; 1495 status_t error = RequestFormatChange(channel->fInput.source, 1496 channel->fInput.destination, newFormat, NULL, &changeTag); 1497 if (error == B_OK) 1498 cookie->AcquireReference(); 1499 } 1500 1501 if (id != PARAMETER_ID_INPUT_FREQUENCY) 1502 return; 1503 //Do not return cause we should go in the next if 1504 } 1505 1506 if (id == PARAMETER_ID_INPUT_FREQUENCY) { 1507 uint32 rate; 1508 if (size < sizeof(rate)) 1509 return; 1510 memcpy(&rate, value, sizeof(rate)); 1511 1512 if (rate == fInputPreferredFormat.u.raw_audio.frame_rate) 1513 return; 1514 1515 // create a cookie RequestCompleted() can get the old frame rate from, 1516 // if anything goes wrong 1517 FrameRateChangeCookie* cookie 1518 = new(std::nothrow) FrameRateChangeCookie; 1519 if (cookie == NULL) 1520 return; 1521 1522 cookie->oldFrameRate = fInputPreferredFormat.u.raw_audio.frame_rate; 1523 cookie->id = id; 1524 BReference<FrameRateChangeCookie> cookieReference(cookie, true); 1525 1526 // NOTE: What we should do is call RequestFormatChange() for all 1527 // connections and change the device's format in RequestCompleted(). 1528 // Unfortunately we need the new buffer size first, which we only get 1529 // from the device after changing the format. So we do that now and 1530 // reset it in RequestCompleted(), if something went wrong. This causes 1531 // the buffers we receive until then to be played incorrectly leading 1532 // to unpleasant noise. 1533 float frameRate = MultiAudio::convert_to_sample_rate(rate); 1534 if (_SetNodeOutputFrameRate(frameRate) != B_OK) 1535 return; 1536 1537 for (int32 i = 0; i < fOutputs.CountItems(); i++) { 1538 node_output* channel = (node_output*)fOutputs.ItemAt(i); 1539 if (channel->fOutput.source == media_source::null) 1540 continue; 1541 1542 media_format newFormat = channel->fOutput.format; 1543 newFormat.u.raw_audio.frame_rate = frameRate; 1544 newFormat.u.raw_audio.buffer_size 1545 = fInputPreferredFormat.u.raw_audio.buffer_size; 1546 1547 int32 changeTag = 0; 1548 status_t error = RequestFormatChange(channel->fOutput.source, 1549 channel->fOutput.destination, newFormat, NULL, &changeTag); 1550 if (error == B_OK) 1551 cookie->AcquireReference(); 1552 } 1553 1554 return; 1555 } 1556 1557 multi_mix_value_info info; 1558 multi_mix_value values[2]; 1559 info.values = values; 1560 info.item_count = 0; 1561 multi_mix_control* controls = fDevice->MixControlInfo().controls; 1562 int32 control_id = controls[id - 100].id; 1563 1564 if (parameter->Type() == BParameter::B_CONTINUOUS_PARAMETER) { 1565 for (uint32 i = 0; i < size / sizeof(float); i++) { 1566 PRINT(("SetParameterValue B_CONTINUOUS_PARAMETER value[%" B_PRIi32 1567 "] : %f\n", i, ((float*)value)[i])); 1568 } 1569 info.item_count = 1; 1570 values[0].id = control_id; 1571 values[0].gain = ((float*)value)[0]; 1572 1573 if (parameter->CountChannels() == 2) { 1574 info.item_count = 2; 1575 values[1].id = controls[id + 1 - 100].id; 1576 values[1].gain = ((float*)value)[1]; 1577 } 1578 } else if (parameter->Type() == BParameter::B_DISCRETE_PARAMETER) { 1579 for (uint32 i = 0; i < size / sizeof(int32); i++) { 1580 PRINT(("SetParameterValue B_DISCRETE_PARAMETER value[%" B_PRIi32 1581 "] : %" B_PRIi32 "\n", i, ((int32*)value)[i])); 1582 } 1583 1584 BDiscreteParameter* discrete = (BDiscreteParameter*)parameter; 1585 if (discrete->CountItems() <= 2) { 1586 info.item_count = 1; 1587 values[0].id = control_id; 1588 values[0].enable = ((int32*)value)[0] == 1; 1589 } else { 1590 info.item_count = 1; 1591 values[0].id = control_id; 1592 values[0].mux = ((uint32*)value)[0]; 1593 } 1594 } 1595 1596 if (info.item_count > 0) { 1597 status_t status = fDevice->SetMix(&info); 1598 if (status != B_OK) 1599 fprintf(stderr, "Failed on DRIVER_SET_MIX\n"); 1600 } 1601 } 1602 1603 1604 BParameterWeb* 1605 MultiAudioNode::MakeParameterWeb() 1606 { 1607 CALLED(); 1608 BParameterWeb* web = new BParameterWeb; 1609 1610 PRINT(("MixControlInfo().control_count : %" B_PRIi32 "\n", 1611 fDevice->MixControlInfo().control_count)); 1612 1613 BParameterGroup* generalGroup = web->MakeGroup(B_TRANSLATE("General")); 1614 1615 const multi_description& description = fDevice->Description(); 1616 1617 if (description.output_rates & B_SR_SAME_AS_INPUT) { 1618 _CreateFrequencyParameterGroup(generalGroup, B_TRANSLATE("Input & Output"), 1619 PARAMETER_ID_INPUT_FREQUENCY, description.input_rates); 1620 } else { 1621 _CreateFrequencyParameterGroup(generalGroup, B_TRANSLATE("Input"), 1622 PARAMETER_ID_INPUT_FREQUENCY, description.input_rates); 1623 _CreateFrequencyParameterGroup(generalGroup, B_TRANSLATE("Output"), 1624 PARAMETER_ID_OUTPUT_FREQUENCY, description.output_rates); 1625 } 1626 1627 multi_mix_control* controls = fDevice->MixControlInfo().controls; 1628 1629 for (int i = 0; i < fDevice->MixControlInfo().control_count; i++) { 1630 if (controls[i].flags & B_MULTI_MIX_GROUP && controls[i].parent == 0) { 1631 PRINT(("NEW_GROUP\n")); 1632 BParameterGroup* child = web->MakeGroup( 1633 _GetControlName(controls[i])); 1634 1635 int32 numParameters = 0; 1636 _ProcessGroup(child, i, numParameters); 1637 } 1638 } 1639 1640 return web; 1641 } 1642 1643 1644 const char* 1645 MultiAudioNode::_GetControlName(multi_mix_control& control) 1646 { 1647 if (control.string != S_null) 1648 return kMultiControlString[control.string]; 1649 1650 return control.name; 1651 } 1652 1653 1654 void 1655 MultiAudioNode::_ProcessGroup(BParameterGroup* group, int32 index, 1656 int32& numParameters) 1657 { 1658 CALLED(); 1659 multi_mix_control* parent = &fDevice->MixControlInfo().controls[index]; 1660 multi_mix_control* controls = fDevice->MixControlInfo().controls; 1661 1662 for (int32 i = 0; i < fDevice->MixControlInfo().control_count; i++) { 1663 if (controls[i].parent != parent->id) 1664 continue; 1665 1666 const char* name = _GetControlName(controls[i]); 1667 1668 if (controls[i].flags & B_MULTI_MIX_GROUP) { 1669 PRINT(("NEW_GROUP\n")); 1670 BParameterGroup* child = group->MakeGroup(name); 1671 child->MakeNullParameter(100 + i, B_MEDIA_RAW_AUDIO, name, 1672 B_WEB_BUFFER_OUTPUT); 1673 1674 int32 num = 1; 1675 _ProcessGroup(child, i, num); 1676 } else if (controls[i].flags & B_MULTI_MIX_MUX) { 1677 PRINT(("NEW_MUX\n")); 1678 BDiscreteParameter* parameter = group->MakeDiscreteParameter( 1679 100 + i, B_MEDIA_RAW_AUDIO, name, B_INPUT_MUX); 1680 if (numParameters > 0) { 1681 (group->ParameterAt(numParameters - 1))->AddOutput( 1682 group->ParameterAt(numParameters)); 1683 numParameters++; 1684 } 1685 _ProcessMux(parameter, i); 1686 } else if (controls[i].flags & B_MULTI_MIX_GAIN) { 1687 PRINT(("NEW_GAIN\n")); 1688 group->MakeContinuousParameter(100 + i, 1689 B_MEDIA_RAW_AUDIO, "", B_MASTER_GAIN, "dB", 1690 controls[i].gain.min_gain, controls[i].gain.max_gain, 1691 controls[i].gain.granularity); 1692 1693 if (i + 1 < fDevice->MixControlInfo().control_count 1694 && controls[i + 1].master == controls[i].id 1695 && controls[i + 1].flags & B_MULTI_MIX_GAIN) { 1696 group->ParameterAt(numParameters)->SetChannelCount( 1697 group->ParameterAt(numParameters)->CountChannels() + 1); 1698 i++; 1699 } 1700 1701 PRINT(("num parameters : %" B_PRId32 "\n", numParameters)); 1702 if (numParameters > 0) { 1703 (group->ParameterAt(numParameters - 1))->AddOutput( 1704 group->ParameterAt(numParameters)); 1705 numParameters++; 1706 } 1707 } else if (controls[i].flags & B_MULTI_MIX_ENABLE) { 1708 PRINT(("NEW_ENABLE\n")); 1709 if (controls[i].string == S_MUTE) { 1710 group->MakeDiscreteParameter(100 + i, 1711 B_MEDIA_RAW_AUDIO, name, B_MUTE); 1712 } else { 1713 group->MakeDiscreteParameter(100 + i, 1714 B_MEDIA_RAW_AUDIO, name, B_ENABLE); 1715 } 1716 if (numParameters > 0) { 1717 (group->ParameterAt(numParameters - 1))->AddOutput( 1718 group->ParameterAt(numParameters)); 1719 numParameters++; 1720 } 1721 } 1722 } 1723 } 1724 1725 1726 void 1727 MultiAudioNode::_ProcessMux(BDiscreteParameter* parameter, int32 index) 1728 { 1729 CALLED(); 1730 multi_mix_control* parent = &fDevice->MixControlInfo().controls[index]; 1731 multi_mix_control* controls = fDevice->MixControlInfo().controls; 1732 int32 itemIndex = 0; 1733 1734 for (int32 i = 0; i < fDevice->MixControlInfo().control_count; i++) { 1735 if (controls[i].parent != parent->id) 1736 continue; 1737 1738 if (controls[i].flags & B_MULTI_MIX_MUX_VALUE) { 1739 PRINT(("NEW_MUX_VALUE\n")); 1740 parameter->AddItem(itemIndex, _GetControlName(controls[i])); 1741 itemIndex++; 1742 } 1743 } 1744 } 1745 1746 1747 void 1748 MultiAudioNode::_CreateFrequencyParameterGroup(BParameterGroup* parentGroup, 1749 const char* name, int32 parameterID, uint32 rateMask) 1750 { 1751 BParameterGroup* group = parentGroup->MakeGroup(name); 1752 BDiscreteParameter* frequencyParam = group->MakeDiscreteParameter( 1753 parameterID, B_MEDIA_NO_TYPE, BString(name) << B_TRANSLATE(" frequency:"), 1754 B_GENERIC); 1755 1756 for (int32 i = 0; kSampleRateInfos[i].name != NULL; i++) { 1757 const sample_rate_info& info = kSampleRateInfos[i]; 1758 if ((rateMask & info.multiAudioRate) != 0) { 1759 frequencyParam->AddItem(info.multiAudioRate, 1760 BString(info.name) << " Hz"); 1761 } 1762 } 1763 } 1764 1765 1766 // #pragma mark - MultiAudioNode specific functions 1767 1768 1769 int32 1770 MultiAudioNode::_OutputThread() 1771 { 1772 CALLED(); 1773 multi_buffer_info bufferInfo; 1774 bufferInfo.info_size = sizeof(multi_buffer_info); 1775 bufferInfo.playback_buffer_cycle = 0; 1776 bufferInfo.record_buffer_cycle = 0; 1777 1778 // init the performance time computation 1779 { 1780 BAutolock locker(fBufferLock); 1781 fTimeComputer.Init(fOutputPreferredFormat.u.raw_audio.frame_rate, 1782 system_time()); 1783 } 1784 1785 while (true) { 1786 // TODO: why this semaphore?? 1787 if (acquire_sem_etc(fBufferFreeSem, 1, B_RELATIVE_TIMEOUT, 0) 1788 == B_BAD_SEM_ID) { 1789 return B_OK; 1790 } 1791 1792 BAutolock locker(fBufferLock); 1793 // make sure the buffers don't change while we're playing with them 1794 1795 // send buffer 1796 fDevice->BufferExchange(&bufferInfo); 1797 1798 //PRINT(("MultiAudioNode::RunThread: buffer exchanged\n")); 1799 //PRINT(("MultiAudioNode::RunThread: played_real_time : %Ld\n", bufferInfo.played_real_time)); 1800 //PRINT(("MultiAudioNode::RunThread: played_frames_count : %Ld\n", bufferInfo.played_frames_count)); 1801 //PRINT(("MultiAudioNode::RunThread: buffer_cycle : %li\n", bufferInfo.playback_buffer_cycle)); 1802 1803 for (int32 i = 0; i < fInputs.CountItems(); i++) { 1804 node_input* input = (node_input*)fInputs.ItemAt(i); 1805 1806 if (bufferInfo.playback_buffer_cycle >= 0 1807 && bufferInfo.playback_buffer_cycle 1808 < fDevice->BufferList().return_playback_buffers 1809 && (input->fOldBufferInfo.playback_buffer_cycle 1810 != bufferInfo.playback_buffer_cycle 1811 || fDevice->BufferList().return_playback_buffers == 1) 1812 && (input->fInput.source != media_source::null 1813 || input->fChannelId == 0)) { 1814 //PRINT(("playback_buffer_cycle ok input : %li %ld\n", i, bufferInfo.playback_buffer_cycle)); 1815 1816 input->fBufferCycle = (bufferInfo.playback_buffer_cycle - 1 1817 + fDevice->BufferList().return_playback_buffers) 1818 % fDevice->BufferList().return_playback_buffers; 1819 1820 // update the timesource 1821 if (input->fChannelId == 0) { 1822 //PRINT(("updating timesource\n")); 1823 _UpdateTimeSource(bufferInfo, input->fOldBufferInfo, 1824 *input); 1825 } 1826 1827 input->fOldBufferInfo = bufferInfo; 1828 1829 if (input->fBuffer != NULL) { 1830 _FillNextBuffer(*input, input->fBuffer); 1831 input->fBuffer->Recycle(); 1832 input->fBuffer = NULL; 1833 } else { 1834 // put zeros in current buffer 1835 if (input->fInput.source != media_source::null) 1836 _WriteZeros(*input, input->fBufferCycle); 1837 //PRINT(("MultiAudioNode::Runthread WriteZeros\n")); 1838 } 1839 1840 // mark buffer free 1841 release_sem(fBufferFreeSem); 1842 } else { 1843 //PRINT(("playback_buffer_cycle non ok input : %i\n", i)); 1844 } 1845 } 1846 1847 PRINT(("MultiAudioNode::RunThread: recorded_real_time : %" B_PRIdBIGTIME 1848 "\n", bufferInfo.recorded_real_time)); 1849 PRINT(("MultiAudioNode::RunThread: recorded_frames_count : %" 1850 B_PRId64 "\n", bufferInfo.recorded_frames_count)); 1851 PRINT(("MultiAudioNode::RunThread: record_buffer_cycle : %" B_PRIi32 1852 "\n", bufferInfo.record_buffer_cycle)); 1853 1854 for (int32 i = 0; i < fOutputs.CountItems(); i++) { 1855 node_output* output = (node_output*)fOutputs.ItemAt(i); 1856 1857 // make sure we're both started *and* connected before delivering a 1858 // buffer 1859 if (RunState() == BMediaEventLooper::B_STARTED 1860 && output->fOutput.destination != media_destination::null) { 1861 if (bufferInfo.record_buffer_cycle >= 0 1862 && bufferInfo.record_buffer_cycle 1863 < fDevice->BufferList().return_record_buffers 1864 && (output->fOldBufferInfo.record_buffer_cycle 1865 != bufferInfo.record_buffer_cycle 1866 || fDevice->BufferList().return_record_buffers == 1)) { 1867 //PRINT(("record_buffer_cycle ok\n")); 1868 1869 output->fBufferCycle = bufferInfo.record_buffer_cycle; 1870 1871 // Get the next buffer of data 1872 BBuffer* buffer = _FillNextBuffer(bufferInfo, *output); 1873 if (buffer != NULL) { 1874 // send the buffer downstream if and only if output is 1875 // enabled 1876 status_t err = B_ERROR; 1877 if (output->fOutputEnabled) { 1878 err = SendBuffer(buffer, output->fOutput.source, 1879 output->fOutput.destination); 1880 } 1881 if (err) { 1882 buffer->Recycle(); 1883 } else { 1884 // track how much media we've delivered so far 1885 size_t numSamples 1886 = output->fOutput.format.u.raw_audio.buffer_size 1887 / (output->fOutput.format.u.raw_audio.format 1888 & media_raw_audio_format::B_AUDIO_SIZE_MASK); 1889 output->fSamplesSent += numSamples; 1890 } 1891 } 1892 1893 output->fOldBufferInfo = bufferInfo; 1894 } else { 1895 //PRINT(("record_buffer_cycle non ok\n")); 1896 } 1897 } 1898 } 1899 } 1900 1901 return B_OK; 1902 } 1903 1904 1905 void 1906 MultiAudioNode::_WriteZeros(node_input& input, uint32 bufferCycle) 1907 { 1908 //CALLED(); 1909 /*int32 samples = input.fInput.format.u.raw_audio.buffer_size; 1910 if(input.fInput.format.u.raw_audio.format == media_raw_audio_format::B_AUDIO_UCHAR) { 1911 uint8 *sample = (uint8*)fDevice->BufferList().playback_buffers[input.fBufferCycle][input.fChannelId].base; 1912 for(int32 i = samples-1; i>=0; i--) 1913 *sample++ = 128; 1914 } else { 1915 int32 *sample = (int32*)fDevice->BufferList().playback_buffers[input.fBufferCycle][input.fChannelId].base; 1916 for(int32 i = (samples / 4)-1; i>=0; i--) 1917 *sample++ = 0; 1918 }*/ 1919 1920 uint32 channelCount = input.fFormat.u.raw_audio.channel_count; 1921 uint32 bufferSize = fDevice->BufferList().return_playback_buffer_size; 1922 size_t stride = fDevice->BufferList().playback_buffers[bufferCycle] 1923 [input.fChannelId].stride; 1924 1925 switch (input.fFormat.u.raw_audio.format) { 1926 case media_raw_audio_format::B_AUDIO_FLOAT: 1927 for (uint32 channel = 0; channel < channelCount; channel++) { 1928 char* dest = _PlaybackBuffer(bufferCycle, 1929 input.fChannelId + channel); 1930 for (uint32 i = bufferSize; i > 0; i--) { 1931 *(float*)dest = 0; 1932 dest += stride; 1933 } 1934 } 1935 break; 1936 1937 case media_raw_audio_format::B_AUDIO_DOUBLE: 1938 for (uint32 channel = 0; channel < channelCount; channel++) { 1939 char* dest = _PlaybackBuffer(bufferCycle, 1940 input.fChannelId + channel); 1941 for (uint32 i = bufferSize; i > 0; i--) { 1942 *(double*)dest = 0; 1943 dest += stride; 1944 } 1945 } 1946 break; 1947 1948 case media_raw_audio_format::B_AUDIO_INT: 1949 for (uint32 channel = 0; channel < channelCount; channel++) { 1950 char* dest = _PlaybackBuffer(bufferCycle, 1951 input.fChannelId + channel); 1952 for (uint32 i = bufferSize; i > 0; i--) { 1953 *(int32*)dest = 0; 1954 dest += stride; 1955 } 1956 } 1957 break; 1958 1959 case media_raw_audio_format::B_AUDIO_SHORT: 1960 for (uint32 channel = 0; channel < channelCount; channel++) { 1961 char* dest = _PlaybackBuffer(bufferCycle, 1962 input.fChannelId + channel); 1963 for (uint32 i = bufferSize; i > 0; i--) { 1964 *(int16*)dest = 0; 1965 dest += stride; 1966 } 1967 } 1968 break; 1969 1970 case media_raw_audio_format::B_AUDIO_UCHAR: 1971 for (uint32 channel = 0; channel < channelCount; channel++) { 1972 char* dest = _PlaybackBuffer(bufferCycle, 1973 input.fChannelId + channel); 1974 for (uint32 i = bufferSize; i > 0; i--) { 1975 *(uint8*)dest = 128; 1976 dest += stride; 1977 } 1978 } 1979 break; 1980 1981 case media_raw_audio_format::B_AUDIO_CHAR: 1982 for (uint32 channel = 0; channel < channelCount; channel++) { 1983 char* dest = _PlaybackBuffer(bufferCycle, 1984 input.fChannelId + channel); 1985 for (uint32 i = bufferSize; i > 0; i--) { 1986 *(int8*)dest = 0; 1987 dest += stride; 1988 } 1989 } 1990 break; 1991 1992 default: 1993 fprintf(stderr, "ERROR in WriteZeros format not handled\n"); 1994 } 1995 } 1996 1997 1998 void 1999 MultiAudioNode::_FillWithZeros(node_input& input) 2000 { 2001 CALLED(); 2002 for (int32 i = 0; i < fDevice->BufferList().return_playback_buffers; i++) 2003 _WriteZeros(input, i); 2004 } 2005 2006 2007 void 2008 MultiAudioNode::_FillNextBuffer(node_input& input, BBuffer* buffer) 2009 { 2010 uint32 channelCount = input.fInput.format.u.raw_audio.channel_count; 2011 size_t inputSampleSize = input.fInput.format.u.raw_audio.format 2012 & media_raw_audio_format::B_AUDIO_SIZE_MASK; 2013 2014 uint32 bufferSize = fDevice->BufferList().return_playback_buffer_size; 2015 2016 if (buffer->SizeUsed() / inputSampleSize / channelCount != bufferSize) { 2017 _WriteZeros(input, input.fBufferCycle); 2018 return; 2019 } 2020 2021 if (channelCount != input.fFormat.u.raw_audio.channel_count) { 2022 PRINT(("Channel count is different")); 2023 return; 2024 } 2025 2026 if (input.fResampler != NULL) { 2027 size_t srcStride = channelCount * inputSampleSize; 2028 2029 for (uint32 channel = 0; channel < channelCount; channel++) { 2030 char* src = (char*)buffer->Data() + channel * inputSampleSize; 2031 char* dst = _PlaybackBuffer(input.fBufferCycle, 2032 input.fChannelId + channel); 2033 size_t dstStride = _PlaybackStride(input.fBufferCycle, 2034 input.fChannelId + channel); 2035 2036 input.fResampler->Resample(src, srcStride, 2037 dst, dstStride, bufferSize); 2038 } 2039 } 2040 } 2041 2042 2043 status_t 2044 MultiAudioNode::_StartOutputThreadIfNeeded() 2045 { 2046 CALLED(); 2047 // the thread is already started ? 2048 if (fThread >= 0) 2049 return B_OK; 2050 2051 // allocate buffer free semaphore 2052 fBufferFreeSem = create_sem( 2053 fDevice->BufferList().return_playback_buffers - 1, 2054 "multi_audio out buffer free"); 2055 if (fBufferFreeSem < B_OK) 2056 return fBufferFreeSem; 2057 2058 PublishTime(-50, 0, 0); 2059 2060 fThread = spawn_thread(_OutputThreadEntry, "multi_audio audio output", 2061 B_REAL_TIME_PRIORITY, this); 2062 if (fThread < B_OK) { 2063 delete_sem(fBufferFreeSem); 2064 return fThread; 2065 } 2066 2067 resume_thread(fThread); 2068 return B_OK; 2069 } 2070 2071 2072 status_t 2073 MultiAudioNode::_StopOutputThread() 2074 { 2075 CALLED(); 2076 delete_sem(fBufferFreeSem); 2077 2078 status_t exitValue; 2079 wait_for_thread(fThread, &exitValue); 2080 fThread = -1; 2081 return B_OK; 2082 } 2083 2084 2085 void 2086 MultiAudioNode::_AllocateBuffers(node_output &channel) 2087 { 2088 CALLED(); 2089 2090 // allocate enough buffers to span our downstream latency, plus one 2091 size_t size = channel.fOutput.format.u.raw_audio.buffer_size; 2092 int32 count = int32(fLatency / BufferDuration() + 1 + 1); 2093 2094 PRINT(("\tlatency = %" B_PRIdBIGTIME ", buffer duration = %" B_PRIdBIGTIME 2095 "\n", fLatency, BufferDuration())); 2096 PRINT(("\tcreating group of %" B_PRId32 " buffers, size = %" B_PRIuSIZE 2097 "\n", count, size)); 2098 channel.fBufferGroup = new BBufferGroup(size, count); 2099 } 2100 2101 2102 void 2103 MultiAudioNode::_UpdateTimeSource(multi_buffer_info& info, 2104 multi_buffer_info& oldInfo, node_input& input) 2105 { 2106 //CALLED(); 2107 if (!fTimeSourceStarted || oldInfo.played_real_time == 0) 2108 return; 2109 2110 fTimeComputer.AddTimeStamp(info.played_real_time, 2111 info.played_frames_count); 2112 PublishTime(fTimeComputer.PerformanceTime(), fTimeComputer.RealTime(), 2113 fTimeComputer.Drift()); 2114 } 2115 2116 2117 BBuffer* 2118 MultiAudioNode::_FillNextBuffer(multi_buffer_info &info, node_output &output) 2119 { 2120 //CALLED(); 2121 // get a buffer from our buffer group 2122 //PRINT(("buffer size : %i, buffer duration : %i\n", fOutput.format.u.raw_audio.buffer_size, BufferDuration())); 2123 //PRINT(("MBI.record_buffer_cycle : %i\n", MBI.record_buffer_cycle)); 2124 //PRINT(("MBI.recorded_real_time : %i\n", MBI.recorded_real_time)); 2125 //PRINT(("MBI.recorded_frames_count : %i\n", MBI.recorded_frames_count)); 2126 if (!output.fBufferGroup) 2127 return NULL; 2128 2129 BBuffer* buffer = output.fBufferGroup->RequestBuffer( 2130 output.fOutput.format.u.raw_audio.buffer_size, BufferDuration()); 2131 if (buffer == NULL) { 2132 // If we fail to get a buffer (for example, if the request times out), 2133 // we skip this buffer and go on to the next, to avoid locking up the 2134 // control thread. 2135 fprintf(stderr, "Buffer is null"); 2136 return NULL; 2137 } 2138 2139 if (fDevice == NULL) 2140 fprintf(stderr, "fDevice NULL\n"); 2141 if (buffer->Header() == NULL) 2142 fprintf(stderr, "buffer->Header() NULL\n"); 2143 if (TimeSource() == NULL) 2144 fprintf(stderr, "TimeSource() NULL\n"); 2145 2146 uint32 channelCount = output.fOutput.format.u.raw_audio.channel_count; 2147 size_t outputSampleSize = output.fOutput.format.u.raw_audio.format 2148 & media_raw_audio_format::B_AUDIO_SIZE_MASK; 2149 2150 uint32 bufferSize = fDevice->BufferList().return_record_buffer_size; 2151 2152 if (output.fResampler != NULL) { 2153 size_t dstStride = channelCount * outputSampleSize; 2154 2155 uint32 channelId = output.fChannelId 2156 - fDevice->Description().output_channel_count; 2157 2158 for (uint32 channel = 0; channel < channelCount; channel++) { 2159 char* src = _RecordBuffer(output.fBufferCycle, 2160 channelId + channel); 2161 size_t srcStride = _RecordStride(output.fBufferCycle, 2162 channelId + channel); 2163 char* dst = (char*)buffer->Data() + channel * outputSampleSize; 2164 2165 output.fResampler->Resample(src, srcStride, dst, dstStride, 2166 bufferSize); 2167 } 2168 } 2169 2170 // fill in the buffer header 2171 media_header* header = buffer->Header(); 2172 header->type = B_MEDIA_RAW_AUDIO; 2173 header->size_used = output.fOutput.format.u.raw_audio.buffer_size; 2174 header->time_source = TimeSource()->ID(); 2175 header->start_time = PerformanceTimeFor(info.recorded_real_time); 2176 2177 return buffer; 2178 } 2179 2180 2181 status_t 2182 MultiAudioNode::GetConfigurationFor(BMessage* message) 2183 { 2184 CALLED(); 2185 2186 BParameter *parameter = NULL; 2187 void *buffer; 2188 size_t bufferSize = 128; 2189 bigtime_t lastChange; 2190 status_t err; 2191 2192 if (message == NULL) 2193 return B_BAD_VALUE; 2194 2195 buffer = malloc(bufferSize); 2196 if (buffer == NULL) 2197 return B_NO_MEMORY; 2198 2199 for (int32 i = 0; i < fWeb->CountParameters(); i++) { 2200 parameter = fWeb->ParameterAt(i); 2201 if (parameter->Type() != BParameter::B_CONTINUOUS_PARAMETER 2202 && parameter->Type() != BParameter::B_DISCRETE_PARAMETER) 2203 continue; 2204 2205 PRINT(("getting parameter %" B_PRIi32 "\n", parameter->ID())); 2206 size_t size = bufferSize; 2207 while ((err = GetParameterValue(parameter->ID(), &lastChange, buffer, 2208 &size)) == B_NO_MEMORY && bufferSize < 128 * 1024) { 2209 bufferSize += 128; 2210 free(buffer); 2211 buffer = malloc(bufferSize); 2212 if (buffer == NULL) 2213 return B_NO_MEMORY; 2214 } 2215 2216 if (err == B_OK && size > 0) { 2217 message->AddInt32("parameterID", parameter->ID()); 2218 message->AddData("parameterData", B_RAW_TYPE, buffer, size, false); 2219 } else { 2220 PRINT(("parameter err : %s\n", strerror(err))); 2221 } 2222 } 2223 2224 free(buffer); 2225 PRINT_OBJECT(*message); 2226 return B_OK; 2227 } 2228 2229 2230 node_output* 2231 MultiAudioNode::_FindOutput(media_source source) 2232 { 2233 node_output* channel = NULL; 2234 2235 for (int32 i = 0; i < fOutputs.CountItems(); i++) { 2236 channel = (node_output*)fOutputs.ItemAt(i); 2237 if (source == channel->fOutput.source) 2238 break; 2239 } 2240 2241 if (source != channel->fOutput.source) 2242 return NULL; 2243 2244 return channel; 2245 } 2246 2247 2248 node_input* 2249 MultiAudioNode::_FindInput(media_destination dest) 2250 { 2251 node_input* channel = NULL; 2252 2253 for (int32 i = 0; i < fInputs.CountItems(); i++) { 2254 channel = (node_input*)fInputs.ItemAt(i); 2255 if (dest == channel->fInput.destination) 2256 break; 2257 } 2258 2259 if (dest != channel->fInput.destination) 2260 return NULL; 2261 2262 return channel; 2263 } 2264 2265 2266 node_input* 2267 MultiAudioNode::_FindInput(int32 destinationId) 2268 { 2269 node_input* channel = NULL; 2270 2271 for (int32 i = 0; i < fInputs.CountItems(); i++) { 2272 channel = (node_input*)fInputs.ItemAt(i); 2273 if (destinationId == channel->fInput.destination.id) 2274 break; 2275 } 2276 2277 if (destinationId != channel->fInput.destination.id) 2278 return NULL; 2279 2280 return channel; 2281 } 2282 2283 2284 /*static*/ status_t 2285 MultiAudioNode::_OutputThreadEntry(void* data) 2286 { 2287 CALLED(); 2288 return static_cast<MultiAudioNode*>(data)->_OutputThread(); 2289 } 2290 2291 2292 status_t 2293 MultiAudioNode::_SetNodeInputFrameRate(float frameRate) 2294 { 2295 // check whether the frame rate is supported 2296 uint32 multiAudioRate = MultiAudio::convert_from_sample_rate(frameRate); 2297 if ((fDevice->Description().output_rates & multiAudioRate) == 0) 2298 return B_BAD_VALUE; 2299 2300 BAutolock locker(fBufferLock); 2301 2302 // already set? 2303 if (fDevice->FormatInfo().output.rate == multiAudioRate) 2304 return B_OK; 2305 2306 // set the frame rate on the device 2307 status_t error = fDevice->SetOutputFrameRate(multiAudioRate); 2308 if (error != B_OK) 2309 return error; 2310 2311 // it went fine -- update all formats 2312 fOutputPreferredFormat.u.raw_audio.frame_rate = frameRate; 2313 fOutputPreferredFormat.u.raw_audio.buffer_size 2314 = fDevice->BufferList().return_playback_buffer_size 2315 * (fOutputPreferredFormat.u.raw_audio.format 2316 & media_raw_audio_format::B_AUDIO_SIZE_MASK) 2317 * fOutputPreferredFormat.u.raw_audio.channel_count; 2318 2319 for (int32 i = 0; node_input* channel = (node_input*)fInputs.ItemAt(i); 2320 i++) { 2321 channel->fPreferredFormat.u.raw_audio.frame_rate = frameRate; 2322 channel->fPreferredFormat.u.raw_audio.buffer_size 2323 = fOutputPreferredFormat.u.raw_audio.buffer_size; 2324 2325 channel->fFormat.u.raw_audio.frame_rate = frameRate; 2326 channel->fFormat.u.raw_audio.buffer_size 2327 = fOutputPreferredFormat.u.raw_audio.buffer_size; 2328 2329 channel->fInput.format.u.raw_audio.frame_rate = frameRate; 2330 channel->fInput.format.u.raw_audio.buffer_size 2331 = fOutputPreferredFormat.u.raw_audio.buffer_size; 2332 } 2333 2334 // make sure the time base is reset 2335 fTimeComputer.SetFrameRate(frameRate); 2336 2337 // update internal latency 2338 _UpdateInternalLatency(fOutputPreferredFormat); 2339 2340 return B_OK; 2341 } 2342 2343 2344 status_t 2345 MultiAudioNode::_SetNodeOutputFrameRate(float frameRate) 2346 { 2347 // check whether the frame rate is supported 2348 uint32 multiAudioRate = MultiAudio::convert_from_sample_rate(frameRate); 2349 if ((fDevice->Description().input_rates & multiAudioRate) == 0) 2350 return B_BAD_VALUE; 2351 2352 BAutolock locker(fBufferLock); 2353 2354 // already set? 2355 if (fDevice->FormatInfo().input.rate == multiAudioRate) 2356 return B_OK; 2357 2358 // set the frame rate on the device 2359 status_t error = fDevice->SetInputFrameRate(multiAudioRate); 2360 if (error != B_OK) 2361 return error; 2362 2363 // it went fine -- update all formats 2364 fInputPreferredFormat.u.raw_audio.frame_rate = frameRate; 2365 fInputPreferredFormat.u.raw_audio.buffer_size 2366 = fDevice->BufferList().return_record_buffer_size 2367 * (fInputPreferredFormat.u.raw_audio.format 2368 & media_raw_audio_format::B_AUDIO_SIZE_MASK) 2369 * fInputPreferredFormat.u.raw_audio.channel_count; 2370 2371 for (int32 i = 0; node_output* channel = (node_output*)fOutputs.ItemAt(i); 2372 i++) { 2373 channel->fPreferredFormat.u.raw_audio.frame_rate = frameRate; 2374 channel->fPreferredFormat.u.raw_audio.buffer_size 2375 = fInputPreferredFormat.u.raw_audio.buffer_size; 2376 2377 channel->fFormat.u.raw_audio.frame_rate = frameRate; 2378 channel->fFormat.u.raw_audio.buffer_size 2379 = fInputPreferredFormat.u.raw_audio.buffer_size; 2380 2381 channel->fOutput.format.u.raw_audio.frame_rate = frameRate; 2382 channel->fOutput.format.u.raw_audio.buffer_size 2383 = fInputPreferredFormat.u.raw_audio.buffer_size; 2384 } 2385 2386 // make sure the time base is reset 2387 fTimeComputer.SetFrameRate(frameRate); 2388 2389 // update internal latency 2390 _UpdateInternalLatency(fInputPreferredFormat); 2391 2392 return B_OK; 2393 } 2394 2395 2396 void 2397 MultiAudioNode::_UpdateInternalLatency(const media_format& format) 2398 { 2399 // use half a buffer length latency 2400 fInternalLatency = format.u.raw_audio.buffer_size * 10000 / 2 2401 / ((format.u.raw_audio.format 2402 & media_raw_audio_format::B_AUDIO_SIZE_MASK) 2403 * format.u.raw_audio.channel_count) 2404 / ((int32)(format.u.raw_audio.frame_rate / 100)); 2405 2406 PRINT((" internal latency = %" B_PRIdBIGTIME "\n", fInternalLatency)); 2407 2408 SetEventLatency(fInternalLatency); 2409 } 2410