summaryrefslogtreecommitdiff
path: root/src/multiplexer.cc
blob: d479627769483e13c85b58736b55011f9d8eba8f (plain)
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/***************************************************************************
 *            multiplexer.cc
 *
 *  Wed Aug 31 13:05:18 CEST 2005
 *  Copyright  2005 Bent Bisballe Nyeng
 *  deva@aasimon.org
 ****************************************************************************/

/*
 *  This file is part of MIaV.
 *
 *  MIaV is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  MIaV is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MIaV; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */

#include "config.h"
#include "multiplexer.h"

#include <netinet/in.h>
#include <math.h>

#define SIZEOF(x) (sizeof(x)-1)

// Audio index lists
/*
static unsigned int frequency_index[4] = {44100, 48000, 32000, 0};
//static unsigned int slots [4] = {12, 144, 0, 0};
//static unsigned int slot_index [4] = {144, 144, 144, 0};
//static unsigned int sample_index [4] = {384, 1152, 0, 0};
static unsigned int bitrate_index [4][16] = {
  {0, 0, 0, 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,0}, // Reserved
  {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,0}, // Layer III
  {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,0}, // Layer II
  {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,0}  // Layer I
};
static char layer_index[4][12] = { "Reserved", "Layer III", "Layer II", "Layer I" };
static char mode_index[4][32] = { "Stereo", "Joint Stereo", "Dual Channel", "Single Channel"};
static char protection_index[2][32] = { "CRC check enabled", "CRC check disabled" };
*/
//static unsigned short int syncword = 0xFFF;

// Video index lists
/*
#define FORBIDDEN -1.0
#define RESERVED -2.0
static double picture_rate_index[16] = {
  FORBIDDEN, 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60,
  RESERVED, RESERVED, RESERVED, RESERVED, RESERVED, RESERVED, RESERVED
};
*/

Multiplexer::Multiplexer(File *f, Info *i, volatile bool *r,
                         FramePriorityQueue *v_q, pthread_mutex_t *v_m, sem_t *v_s, 
                         FramePriorityQueue *a_q, pthread_mutex_t *a_m, sem_t *a_s)
{
  running = r;
  file = f;
  info = i;

  queue[TYPE_VIDEO] = v_q;
  queue[TYPE_AUDIO] = a_q;

  sem[TYPE_VIDEO] = v_s;
  sem[TYPE_AUDIO] = a_s;

  mutex[TYPE_VIDEO] = v_m;
  mutex[TYPE_AUDIO] = a_m;

  frame[TYPE_VIDEO] = NULL;
  frame[TYPE_AUDIO] = NULL;

  frame_number[TYPE_VIDEO] = 0;
  frame_number[TYPE_AUDIO] = 0;

  write_system_header = 0;
  write_audio_packet = 0;

  audio_header_read = false;

  written[TYPE_VIDEO] = 0.0;
  written[TYPE_AUDIO] = 0.0;

  SCR = 3904;//0x40010003LL;//0x1E80;

}

Multiplexer::~Multiplexer()
{
}


int Multiplexer::read_stream(char *buf, unsigned int size, StreamType type)
{
  Frame *tmpframe;
  unsigned int copied = 0;

  while( copied < size ) {

    // If we read the entire frame, prepare to get a new one
    if(frame[type] && read[type] == frame[type]->size) {
      delete frame[type];
      frame[type] = NULL;
    }

    // If no frame is in the buffer, get one from the queue
    while( frame[type] == NULL ) {

      //      if(!*running) info->warn("Halt detected!");

      // If we are not running anymore, just process the last frames as fast as possible!
      if(*running) sem_wait(sem[type]); 

      // Lock output mutex
      pthread_mutex_lock( mutex[type] );
      tmpframe = queue[type]->top();
      if(tmpframe && tmpframe->number == frame_number[type] ) {
        queue[type]->pop();
        frame[type] = tmpframe;
        frame_number[type]++;
        read[type] = 0;
      }
      if(*running == false && frame[type] == NULL) {
        pthread_mutex_unlock( mutex[type] );
        //info->info("Bailed out early %d!", copied);
        return copied;
      }
      pthread_mutex_unlock( mutex[type] );
      // Unlock output mutex
    }

    // If a frame exists in the buffer copy it to the output buffer
    // (No frame ocurres when *running is set to false)
    if( frame[type] ) {
      unsigned int doread = (size - copied) < (frame[type]->size - read[type]) ?
        size - copied : (frame[type]->size - read[type]);
      
      //info->info("Requested: %d. Read: %d. Doread: %d. In buffer %d", size, (*read), doread, (*frame)->size);
      
      memcpy(buf + copied, frame[type]->data + read[type], doread);
      read[type] += doread;
      copied += doread;
    }
  }

  return copied;
}

bool Multiplexer::packet(StreamType type)
{
  char buf[PACKET_SIZE];

  // Write data
  info->info("\t\t[%sPacket]", type==TYPE_AUDIO?"Audio\0":"Video\0");

  unsigned short int framesize = read_stream(buf, PACKET_SIZE, type);

  file->Write((void*)ISO11172_1::packet_start_code_prefix, SIZEOF(ISO11172_1::packet_start_code_prefix));
  switch(type) {
  case TYPE_VIDEO:
    file->Write((void*)ISO11172_1::stream_id_video1, SIZEOF(ISO11172_1::stream_id_video1));
    break;
  case TYPE_AUDIO:
    file->Write((void*)ISO11172_1::stream_id_audio1, SIZEOF(ISO11172_1::stream_id_audio1));
    break;
  }

  unsigned short int hton_framesize = framesize + 1; // Need space for dims too!
  hton_framesize = htons(hton_framesize);
  file->Write((char*)&hton_framesize, sizeof(hton_framesize));

  char dims[] = "\x0F";
  file->Write(dims, 1);

  file->Write(buf, framesize);

  if(framesize != PACKET_SIZE) return false;

  written[type] += (double)PACKET_SIZE / (double)frame[type]->bitrate;

  return true;
}

/**
 * Create and write a packet
 */
bool Multiplexer::packet()
{
  //info->info("\t\tWritten[A]: %f, Written[V]: %f", written[TYPE_AUDIO], written[TYPE_VIDEO]);

  StreamType type;

  // New switching mechanism
  if(written[TYPE_AUDIO] < written[TYPE_VIDEO]) {
    type = TYPE_AUDIO;
  } else {
    type = TYPE_VIDEO;
  }

  if(!packet(type)) {
    // Flush the other stream too...
    if(type == TYPE_AUDIO) type = TYPE_VIDEO;
    else type = TYPE_AUDIO;
    while(packet(type));
    return false;
  }
  return true;
  
  /*
  // Count this up here, we want audio packets in packet 4, 9, ... NOT 0, 3, ...
  
  write_audio_packet++;
  if(write_audio_packet % AUDIO_PACKET_FREQUENCY == 0) {
    packet(TYPE_AUDIO);
  } else {
    packet(TYPE_VIDEO);
  }
  */
}

/**
 * Create and write the system header
 */
void Multiplexer::system_header()
{
  info->info("\t\t[System Header]");
  
  // system_header_start_code (32 bits)
  file->Write((void*)ISO11172_1::system_header_start_code, SIZEOF(ISO11172_1::system_header_start_code));
  
  // header_length (16 bits)
  char system_header_length[]     = "\x00\x0C";
  file->Write(system_header_length, SIZEOF(system_header_length));
  
  // marker_bit (1 bit)   \.
  // rate_bound (22 bits)  ) (24 bits)
  // marker_bit (1 bit)   /
  char rate_bound[]     = "\x80\x1B\x83";
  file->Write(rate_bound, SIZEOF(rate_bound));
  
  // audio_bound (6 bits) \.
  // fixed_flag (1 bit)    ) (8 bits)
  // CSPS_flag (1 bit)    /
  char audio_bound[]     = "\x06"; // One audio stream, fixed bitrate and not iso costraint compliant
  file->Write(audio_bound, SIZEOF(audio_bound));

  // system_audio_lock_flag (1 bit) \.
  // system_video_lock_flag (1 bit)  \.
  // marker_bit (1 bit)               ) (8 bits)
  // video_bound (5 bits)           _/
  char video_bound[]     = "\x21"; // Audio and Video are not locked and there are only one video stream
  file->Write(video_bound, SIZEOF(video_bound));
 
  // reserved_byte (8 bit)
  char reserved_byte[]     = "\xFF";
  file->Write(reserved_byte, SIZEOF(reserved_byte));

  { // Audio
    // stream_id (8 bit)
    char stream_id[]     = "\xC0";
    file->Write(stream_id, SIZEOF(stream_id));
    
    // '11' (2 bits)                   \.
    // STD_buffer_bound_scale (1 bit)   ) (24 bits)
    // STD_buffer_size_bound (13 bits) /
    char reserved_byte[]     = "\xC0\x20";
    file->Write(reserved_byte, SIZEOF(reserved_byte));
  }

  { // Video
    // stream_id (8 bit)
    char stream_id[]     = "\xE3";
    file->Write(stream_id, SIZEOF(stream_id));
    
    // '11' (2 bits)                   \.
    // STD_buffer_bound_scale (1 bit)   ) (24 bits)
    // STD_buffer_size_bound (13 bits) /
    char reserved_byte[]     = "\xE0\x2E";
    file->Write(reserved_byte, SIZEOF(reserved_byte));
  }
}

#define MASK3 0x7
#define MASK15 0x7FFF
#define TIMECODE32_30(x) ((x >> 30) & MASK3 )
#define TIMECODE29_15(x) ((x >> 15) & MASK15)
#define TIMECODE14_0(x)  ((x >>  0) & MASK15)

/**
 * Create and write a pack
 */
bool Multiplexer::pack()
{
  info->info("\t[Pack");

  file->Write((void*)ISO11172_1::pack_start_code, SIZEOF(ISO11172_1::pack_start_code));
  
  ISO11172_1::pack_header header;
  // Set marker bits to 1
  header.marker_bit1 =
    header.marker_bit2 =
    header.marker_bit3 =
    header.marker_bit4 =
    header.marker_bit5 = 1;

  header.padding = 0x2;

  unsigned int video_data_rate;
  unsigned int audio_data_rate;

  if(frame[TYPE_AUDIO]) audio_data_rate = frame[TYPE_AUDIO]->bitrate;
  else audio_data_rate = 112000;
  
  if(frame[TYPE_VIDEO]) video_data_rate = frame[TYPE_VIDEO]->bitrate;
  else video_data_rate = 1100000;

  unsigned int Rmux = ISO11172_1::Rmux(video_data_rate,
                                     audio_data_rate,
                                     20, // packet_header_size,
                                     12, // pack_header_size,
                                     PACKETS_PER_PACK, // packets_per_pack,
                                     PACKET_SIZE);// packet_data_size)

  header.mux_rate = Rmux;
  //0x1B82;

  SCR = ISO11172_1::SCR(SCR,
                        12, //pack_header_size,
                        PACKETS_PER_PACK, //packets_per_pack,
                        PACKET_SIZE, //packet_data_size,
                        Rmux);

  //  SCR = 0x40010003LL;

  header.system_clock_reference1 = TIMECODE32_30(SCR);
  header.system_clock_reference2 = TIMECODE29_15(SCR);
  header.system_clock_reference3 = TIMECODE14_0(SCR);
  /*
  info->info("timecode All: %lld, 1: %lld, 2: %lld, 3: %lld", 
             SCR,
             (unsigned long long int)header.system_clock_reference1,
             (unsigned long long int)header.system_clock_reference2,
             (unsigned long long int)header.system_clock_reference3
             );
  */
  unsigned int *hton_header_u = (unsigned int *)&header;
  unsigned int *hton_header_l = (unsigned int *)((char*)&header + sizeof(unsigned int));

  *hton_header_u = htonl(*hton_header_u);
  *hton_header_l = htonl(*hton_header_l);

  file->Write((char*)hton_header_u, sizeof(*hton_header_u));
  file->Write((char*)hton_header_l, sizeof(*hton_header_l));

  if(write_system_header % SYSTEM_HEADER_FREQUENCY == 0) system_header();
  // Count this up here, we want a system header in pack 0, 5, ... NOT 4, 9, ...
  write_system_header++;

  for(int cnt = 0; cnt < PACKETS_PER_PACK; cnt++) 
    if(!packet()) return false;

  info->info("\t]");

  return true;
}

/**
 *
 */
void Multiplexer::iso11172_stream()
{
  info->info("[iso11172_stream");

  while(pack());

  info->info("]");
  info->info("[iso11172_end_code]");
  file->Write((void*)ISO11172_1::end_code, SIZEOF(ISO11172_1::end_code));

  /*
  info->info("false && false = %d", false && false);
  info->info("true && false = %d", true && false);
  info->info("true && true = %d", true && true);
  */
}

//#define BYPASS TYPE_VIDEO
//#define BYPASS TYPE_AUDIO
void Multiplexer::multiplex()
{
#ifdef BYPASS

  char buf[1024];
  while(*running) file->Write(buf, read_stream(buf, sizeof(buf), BYPASS));
  return;

#else/*BYPASS*/

  iso11172_stream();

#endif/*BYPASS*/
}