Create TCP/IP packets of audio file and evaluate the packet loss effect

Some Useful Instructions :

  • Recording speech of about N seconds at sampling frequency of 32kHz. You can use either ‘wavrecord()’ MATLAB function or windows    sound recorder for this purpose .If you use Sound Recorder, then you need to first set its properties for recording sound at 32kHz and single channel.
  • •Convert the recorded wave file into ASCII character file.
  • •Write a program that creates TCP/IP packets with all fields.
  • Now create multiple TCP/IP packets having data field filled with the data from the ASCII file.
  • •Recreate the ASCII files from TCP/IP packets. • Convert the ASCII file to wave file.
  • •Write a Program that drops the packets randomly for different percentage of packet loss.
  • • Recreate the ASCII files from the received packets, fill the dropped packets with some dummy data.
  • • Convert the ASCII file to wave file.
  • • Calculate the Mean square error (MSE) of original wavefile and decoded wavefile after packet loss.
  • • Plot the effect of different percentage Packet loss on the wave file.

These are the instructions according to which Matlab code was developed.


Code Explanation :

  • First I Recorded the voice using the following Matlab Commands.

recObj = audiorecorder(Fs, 8, 1);            %Create Recording Object


myRecording = getaudiodata(recObj,’uint8′);  %Storing Data in Array


  • Now my recording data is saved in myRecording array and this recording data is converted into Ascii Using fopen Command and then again Acii Data is saved in myRecording
  • Now TCP-Segment are build.For building the segment following events are done


1. All the headers in the TCP segment are initialized and an array is initialized with dummy data Tcp-Segment

2. Tcp-Segment array contains the segment which I built.

3. Now user enter how many bytes of data a segment will contain and this information is saved in variable setsize.

4. Now next we iterated two loops 1st loop is for iterating packets and 2nd loop is for iterating data.For 1st loop ends at sizeofData/setsize = NO of packets

5. Now in 1st iteration of these loops all values for header of first segments are assigned.

6. In the 1st loop all headers are added for checksum calculation for the first packet and saved into temp1 variable.

7. I am explaining this for creating 1st segment as the loop iterates all other segments are created.

8. Now in 2nd loop data is inserted into the Tcp_Segment 1

9. Now all data of 1st packet is added to temp1.Since temp1 contain sum of all headers of packet # 1.

  1. In this same loop wrap around is checked and using BitGet Matlab command and logic is defined in code.
  2. Now take 1’s compliment by subtracting all added data that’s temp1 from 2^16 = 65535 as checksum is of 16-bit that’s why subtracted from this value.
  3. Now Sequence Number is calculated by adding size of each segment i.e sequence_no = sequence_no+setsize;
  4. Now a random number is generated for random packet loss.
  5. Now same above two loops are used for iterating packets and dummy data is inserted on that Random number of loss packets generated
  6. 15.        Now IP-Datagram is created All the headers in the IP-Datagram are initialized and an array is initialized with dummy data IP_Datagram.
  7. Now two loops of IP-Datagram are use to initialize all header and header are also concatenated and inserted into IP_Datagram array and in 2nd loop 1st segment is inserted in the 1st IP_Datagram andin the same way 2nd segment is inserted in 2nd IP_Datagram and so on
  8. Now think at receiver side segment from the IP-Datagram is extracted.
  9. Now Data from TCP-Segment is extracted.
  10. Now Checksum of TCP-Segment is calculated by adding checksum field and data of segment # 1 and in the same this is done for 2,3 and so on.
  11. Now Checksum of IP-Datagram is calculated by adding checksum field and all headers.
  12. Now all data is decoded and packets are integrated and the final integrated Ascii file is converted into wave file for playing recording.


Plot of the MSE for different percentage of packet loss.

  mean square error

  • When percentage of packet loss increases no of packet drops increases so so rmc value also increases according to given above graph
  •  Rmc increases because when number of packets drops increases the difference between decode array and original myRecording array increases so value of rms increases.
  • This analysis has been made by watching the above diagram of % of lost packet and rms value.

Matlab Code :

clear all;

%——————————% Voice Recording saving in current directory—————————————————
EnterSec = input(‘Enter Number of Seconds of Recording’);
Fs=32000;                                                                                     %Sampling Rate
recObj = audiorecorder(Fs, 8, 1);                                              %Create Recording Object
disp(‘Start speaking.’)                                                                 %Display text in ”
recordblocking(recObj,EnterSec);                                            %Start Recording for N sec
disp(‘End of Recording.’);                                                          %Display text in ”
myRecording = getaudiodata(recObj,’uint8′);                        %Storing Data in Array and Coversion to ascii

%——————————————————Saving and Reading file In Ascii Characters——————————–
fwrite( fid,myRecording,’uint8′);

%——————————Header for TCP Multiple Packets & Initilizing Variables Making Header —————

Source_Port_No = 00000000000000000000000000000010;                                    %from TCP Segment Structure
Destination_Port_No = 00000000000000000000000000001100;                            %from TCP Segment Structure
Sequence_No = 00000000000000000000000000000000;                                         %from TCP Segment Structure
Acknoledge_No = 00000000000000000000000000000001;                                     %from TCP Segment Structure

%———————————————————–Now Making Packets named Tcp-segment——————————

limit = length(myRecording);                   %Calculating length of Audio data
Tcp_segment =[0 0 0 ];                             %Creating Dummy Segment to insert data later
Tcp_segment =uint32(Tcp_segment);  %Converting Each Tcp_sement into 32-bits
Data_location =1;                                     %Temp variable for accessing audio data in loop iterations
No_of_Packets =0;                                   %variable for calculating Number of Packets
setsize=input(‘Size in bytes’);                  %User Enter size of data in a paacket
for i = 1:limit/setsize                                  %Divided by setsize = my each packet will contain setsize bytes data
No_of_Packets=No_of_Packets+1;       % Increamenting for no of packets calculation
shift_left=bitshift(Source_Port_No,16); %making tcp segment structure row # 1
SrcOrDes = bitor(shift_left,Destination_Port_No); %making tcp segment structure row # 1

%———————————–Making Segment Structure of Packets—————————-

Tcp_segment(1,i) = SrcOrDes;                                                    %from TCP Segment Structure
Tcp_segment(2,i) = Sequence_No;                                            %from TCP Segment Structure
Tcp_segment(3,i) = Acknoledge_No;                                        %from TCP Segment Structure
Tcp_segment(4,i) = 00000000000000000000000000000000;     %from TCP Segment Structure
Tcp_segment(5,i) = 00000000000000000000000000000000;     %from TCP Segment Structure
Tcp_segment(6,i) = 00000000000000000000000000000000;     %from TCP Segment Structure

temp1=0;    %Temporary variable for storing extracted data from audio information for checksum calculation
temp1=uint8(temp1); %converting this variable into 8-bits

%——————Adding all headers for checksum calculation for a packet———————–
temp1= temp1+uint8(Tcp_segment(1,i)); %Port Header
temp1= temp1+uint8(Tcp_segment(2,i)); %Sequencing Number Header
temp1= temp1+uint8(Tcp_segment(3,i)); %Acknoldegment Number Header
temp1= temp1+uint8(Tcp_segment(4,i)); %Flag and window Header

%—Now Inserting Data in this Segment of Packet and Checksum Calclation in Parallel—–

for k=7:setsize+6 %loop for inserting data in packets data size depend on user input which is saved in setsize

Tcp_segment(k,i) = myRecording(Data_location); %storing data in tcp-segment

%—————-Now Calculating Checksum for Current Packet——————–

bit1=bitget(myRecording(Data_location),8); %Getting information for checking wraparround 1st operand
bit2=bitget(temp1,8); %Getting information for checking wraparround 2nd operand

temp1= temp1+ myRecording(Data_location); %wNow Adding all data in a packet for checksum calculation

if bit1==1 & bit2==1 %if Overflow
temp1= temp1+1; %then add 1 to the temp1

Data_location=Data_location+1; %increment for iterating loop


temp1=uint16(temp1); %Conversion to 16 bits as checksum is 16-bit and data stored in each row in a packet is %8-bit thats why this data is convert into 16-bits
temp1=65535-temp1; %Now taking 1’s Compliment now temp1 contain checksum of this packet
Tcp_segment(5,i) = temp1; %Now inserting this temp1 into checksum feild
Sequence_No=Sequence_No+setsize; %Calculating sequencing number for each packet starting from 0 %defined above

%Now Above program is making multiple packets and calculating checksum at
%each packet that is for each packet adding all data feilds and wrap around
%overflow and taking 1’s compliment.Now calculating random number for packet loss from user enter number of

%—————————————–packet to lost————————————————————————————–
mean_square = [0 0 0 0 0 0 0 0 0 0 ];
percent = [0 0 0 0 0 0 0 0 0 0 ]
disp(‘Note’);                                                                      %DisPlay number packets formed
No_of_Packets                                                                %DisPlay number packets formed
% while(x<10)
los=input(‘Now Enter %age of packet loss’);              %User Enter Input information for packet loss
percent(ite) = los;
loss =los * (No_of_Packets/100)                                  % Calculating loss information
random = ceil(No_of_Packets.*rand(loss,1));            %Generating random number for packet lost
dummyvalue=( No_of_Packets.*rand((setsize+6)*(limit/setsize),1));
if (los == 100)
for i = 1:limit/setsize                                                          %loop for iterating packets
for k=7:setsize+6
Tcp_segment(k,i) = uint32(dummyvalue(inc));            %if true then inserting dummy data in that %packet


for i = 1:limit/setsize                                                   %loop for iterating packets
for i1=1:length(random)                                            %loop for random array iterations
if random(i1)==i                                                          %checking if i is present in that random array
for k=7:setsize+6                                                        %loop for accesing all data in packet that’s all 16 rows of data
Tcp_segment(k,i) = uint32(dummyvalue(inc));    %if true then inserting dummy data in that %packet

%——————————————————–Making IP-DataGram———————————————————–

version = 0000;                                              %IP-Datagram IPv4 Datagram format
header_length = 0000;                                  %IP-Datagram IPv4 Datagram format
Type_of_service = 0000;                             %IP-Datagram IPv4 Datagram format

Datagram_length = uint16(0);                     %IP-Datagram IPv4 Datagram format

Identifier = uint16(0);                                    %IP-Datagram IPv4 Datagram format
FlagsOffset = uint16(0);                               %IP-Datagram IPv4 Datagram format

Time_live = uint8(0);                                    %IP-Datagram IPv4 Datagram format
Upper_layer_Protocol = uint8(0);              %IP-Datagram IPv4 Datagram format
Header_Checksum = uint16(0);                  %IP-Datagram IPv4 Datagram format

Source_IP = uint32(0);                                 %IP-Datagram IPv4 Datagram format

Des_IP = uint32(0);                                      %IP-Datagram IPv4 Datagram format

IP_Datagram = [0 0 0];                                 %IP-Datagram IPv4 Datagram format
IP_Datagram = uint32(IP_Datagram);       %IP-Datagram IPv4 Datagram format

addheaders = 0;                                            %temporary Varaible for adding headers
for i = 1:limit/setsize
%———————Combining all data by shifting and using or logic to save all feilds in ip—————————–
version = uint32(version);
header_length = uint32(header_length);
Type_of_service = uint32(Type_of_service);
Datagram_length = uint32(Datagram_length);

left_shift_Version = bitshift(version,28);
left_shift_header_length = bitshift(header_length,23);
left_shift_Type_of_service = bitshift(Type_of_service,15);
or1 = bitor(left_shift_Version,left_shift_header_length);
or2 = bitor(or1,Datagram_length);

IP_Datagram(1,i) = or1;

Identifier = uint32(Identifier);
FlagsOffset = uint32(FlagsOffset);
left_shift_Identifier = bitshift(Identifier,16);
or3 = bitor(left_shift_Identifier,FlagsOffset);

IP_Datagram(2,i) = or3;

Time_live = uint32(Time_live);
Upper_layer_Protocol = uint32(Upper_layer_Protocol);
Header_Checksum = uint32(Header_Checksum);
left_shift_Time_live = bitshift(Time_live,24);
left_shift_Time_live_Upper_layer_Protocol = bitshift(Upper_layer_Protocol,15);
or4 = bitor(left_shift_Time_live,left_shift_Time_live_Upper_layer_Protocol);
or5 = bitor(or4,Header_Checksum);

IP_Datagram(3,i) = or5;
IP_Datagram(4,i) = Source_IP;
IP_Datagram(5,i) = Des_IP;

%——————————Adding all headers for checksum calculation for a packet————————————-

CheckSum_IP_Datagram = 0;                              % Adding Row 1 of IP Datagram from ip datgram segment table
CheckSum_IP_Datagram = uint16(CheckSum_IP_Datagram); % Adding Row 1 of IP %Datagram from ip %datgram segment table
Right_shift = bitshift(IP_Datagram(1,i),-16); % Adding Row 1 of IP Datagram from ip %datgram segment table
checksum_calc1 = bitor(Right_shift,IP_Datagram(1,i)); % Adding Row 1 of IP Datagram from ip datgram %segment table
CheckSum_IP_Datagram = CheckSum_IP_Datagram + uint16(checksum_calc1); % Adding Row 1 of IP Datagram from ip datgram segment table (version header length type and datgram length )

Right_shift = bitshift(IP_Datagram(2,i),-16); % Adding Row 2 of IP Datagram from ip datgram segment table
checksum_calc2 = bitor(Right_shift,IP_Datagram(2,i)); % Adding Row 2 of IP Datagram from ip datgram %segment table
CheckSum_IP_Datagram = CheckSum_IP_Datagram + uint16(checksum_calc2); % Adding Row 2 of IP %Datagram from ip datgram segment table (identifier ,flags )

Right_shift = bitshift(IP_Datagram(3,i),-16); % Adding Row 3 of IP Datagram from ip datgram segment table
checksum_calc3 = bitor(Right_shift,IP_Datagram(1,i)); % Adding Row 3 of IP Datagram from ip datgram %segment table
CheckSum_IP_Datagram = CheckSum_IP_Datagram + uint16(checksum_calc3); % Adding Row 3 of IP %Datagram from ip datgram segment table

Right_shift = bitshift(IP_Datagram(4,i),-16); % Adding Row 4 of IP Datagram from ip datgram segment table
checksum_calc4 = bitor(Right_shift,IP_Datagram(4,i)); % Adding Row 4 of IP Datagram from ip datgram %segment tabl
CheckSum_IP_Datagram = CheckSum_IP_Datagram + uint16(checksum_calc4); % Adding Row 4 of IP %Datagram from ip datgram segment table (identifier ,flags )

Right_shift = bitshift(IP_Datagram(5,i),-16); % Adding Row 5 of IP Datagram from ip datgram segment table
checksum_calc5 = bitor(Right_shift,IP_Datagram(5,i)); % Adding Row 5 of IP Datagram from ip datgram segment table
CheckSum_IP_Datagram = CheckSum_IP_Datagram + uint16(checksum_calc5); % Adding Row 5 of IP Datagram from ip datgram segment table (identifier ,flags )

CheckSum_IP_Datagram = 65535-CheckSum_IP_Datagram; % taking compliment of all added headers
CheckSum_IP_Datagram = uint32(CheckSum_IP_Datagram);% 32bit conversion for adding to lower bit of %header 3 thats checksum
checksum_calc6 = bitor(CheckSum_IP_Datagram,IP_Datagram(3,i)); % Adding Row 3 of IP Datagram from ip datgram segment table
IP_Datagram(5,i) = checksum_calc6;
addheaders(i) = checksum_calc6;

for j=1:setsize
IP_Datagram(5+j,i) = Tcp_segment(j+6,i); %Assigning tcp packet to tcp segment data
%——————————————————Now tcp segment and ip datagrams are constrcuted——————–

%Now think all data is transmitted and now receving data at reciver and
%checksum caculation of tcp-packet

temp = 1; %Checksum calculation adding all data and checksum feild which will be equal to %1111111111111111 =65536 as checksum is 16 bits 2^16=65536 indicates no error
decode = [0 0]; %dummy variable for data store
decode = uint32(decode); %converting into 32-bit
Extract_TCP = [0 0]; %Tcp extraction from IP-Segment
Extract_TCP = uint32(Extract_TCP); %Tcp extraction from IP-Segment
checksumtemp = [zeros(1,No_of_Packets)]; %dummy varaible for checksum calculation
checksumtemp = uint16(checksumtemp); %converting into 16-bit
checksum_IP_output = [zeros(1,No_of_Packets)];
for i = 1:limit/setsize %loop for packet iteration

checksum_IP_output(i) = IP_Datagram(3,i) +addheaders(i);

for l=1:setsize
Extract_TCP(l,i) = IP_Datagram(l+5,i);
checksumtemp(i) = checksumtemp(i)+uint16(Tcp_segment(5,i)); %adding checksum feild of packet in a dummr variable
for k=1:setsize %loop for data iteration in each packet
decode(temp)= Extract_TCP(k,i); % decoding data fro segment

checksumtemp(i)=checksumtemp(i)+uint16(decode(temp)); %adding data and checksum header for error detection
temp=temp+1; %loop iteration



decode=decode’; %taking transose
decode=uint8(decode); %converting into 8-bits as wave play donot support 32-bits
wavplay(decode,Fs); %Play Recording
% end
% decode=decode’
% for i=1:10
% mean_square = myRecording – decode;
% mean_square=mean_square.*mean_square;
% sum1=0;
% for j=1:limit
% sum1=sum1+mean_square(j);
% end
% rms(i)=sum1/limit;
% end
% plot(percent,rms)
Random1 =ceil( 3.*rand((setsize+6)*(limit/setsize),1));
disp(‘Final Output Details’);
disp(‘Size of audio file is = ‘);
disp(‘No of Packet’);
disp(‘CheckSum of 3 Random Tcp packets at receving end’);
for i=1:3
disp(‘CheckSum of 3 Random Ip Segments at receving end’);
for i=1:3