using System;
using System.IO;

namespace ProxyTunnel.Transcoder
{
    public class G711TranscoderFromTrans
    {
        static private void WriteG711ulaw8Bit8khzWavHeader(
               BinaryWriter writer,
               UInt32 numberOfPacketBytes)
        {
            UInt32 file_length = numberOfPacketBytes + 12 /* RIFF header */ + 8 /* fmt header */ + 18 /* fmt data */ + 8 /* data header */;

            // Write Data Length Header Information
            writer.Write(new char[4] { 'R', 'I', 'F', 'F' });
            writer.Write(file_length - 8);                          // Chunk size (4 bytes)
            writer.Write(new char[4] { 'W', 'A', 'V', 'E' });        // Chunk ID (i.e., chunk format) (4 bytes) 

            // Format sub-chunk
            writer.Write(new char[4] { 'f', 'm', 't', ' ' });       // Sub-chunk1 ID (4 bytes)
            writer.Write((int)18);                                  // extended format Sub-chunk Size (4 bytes)
            writer.Write((short)7);                                 // Audio Format - mu-law (2 bytes)  ("7" for g711 ulaw)
            writer.Write((short)1);                                 // Number of channels (2 bytes)
            writer.Write((int)8000);                                // Sample Rate (4 bytes)
            writer.Write((int)8000 * 1);                            // Byte Rate (4 bytes)
            writer.Write((short)(1 * 1));                           // Block Align (2 byte)
            writer.Write((short)8);                                 // Bits Per Sample (2 bytes)
            writer.Write((short)0);                                 // Extension size (no extension fields) (2 bytes)

            // Data sub-chunk
            writer.Write(new char[4] { 'd', 'a', 't', 'a' });       // Sub-chunk 2 ID 
            writer.Write(numberOfPacketBytes);                      // Sub chunk length (4 bytes)
        }
        public static MemoryStream AddG711HeaderToULawAudio(MemoryStream audioStream)
        {
            MemoryStream outputStream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(outputStream);

            WriteG711ulaw8Bit8khzWavHeader(writer, (UInt32)audioStream.Length);
            writer.Write(audioStream.ToArray());

            return outputStream;
        }
    }
}
