%% DL-SCH HARQ Modeling
% This example demonstrates Hybrid Automatic Repeat reQuest (Hybrid-ARQ)
% Incremental Redundancy (IR) in the Downlink Shared Channel (DL-SCH)
% transmission using the LTE Toolbox(TM).

% Copyright 2009-2018 The MathWorks, Inc.

%% Introduction
% The Downlink Shared Channel (DL-SCH) is described in TS36.212, Section
% 5.3.2 [ <#12 2> ]. This example demonstrates how a transmitter
% retransmits a single codeword over a single layer, using a different
% Redundancy Version (RV) each time until the CRC of the received codeword
% indicates a successful transmission. The DL-SCH transmission is 16QAM
% modulated with a 1/2 target coding rate transmitted over single antenna
% port. The setup used in this example is based on Fixed Reference Channel
% R.3 defined in Table A.3.3.1-2 of TS36.101 [ <#12 1> ].
%
% Hybrid Automatic Repeat reQuest (Hybrid-ARQ) is a combination of Forward
% Error Correction (FEC) and Automatic Repeat reQuest in an optimal manner.
% Hybrid-ARQ schemes are commonly used to facilitate reliable communication
% over noisy wireless channels. HARQ is able to compensate for link
% adaptation errors and provides a finer granularity of coding rate,
% resulting in better throughput performance than other FEC schemes.
% 
% There are three types of Hybrid ARQ: Type I, Type-II and Type-III.
%
%% Hybrid ARQ Type I
% The simplest method: Hybrid ARQ Type I uses the CRC to detect whether or
% not an error in transmission has occurred. If a packet is found to be in
% error a retransmission request will be sent to the transmitter and the
% erroneous packet will be discarded. The transmitter will then retransmit
% the same packet until the packet is successfully decoded by the receiver
% or the maximum retransmission limit is reached.
% 
% Hybrid ARQ Type I can be extended to include packet combining, this is
% known as Hybrid ARQ Type I with Packet Combing or Chase Combining. After
% each failed retransmission the erroneous packets are stored in a buffer.
% The receiver then uses maximum ratio combining to combine each received
% channel bit with any previous transmissions of the same bit and the
% combined signal is fed to the decoder. Chase combining does not give any
% additional coding gain, it only increases the accumulated received signal
% to noise ratio $\mathrm{Eb}/\mathrm{N0}$ for each retransmission.
% 
%% Hybrid ARQ Type II
% In Hybrid ARQ Type II, also known as full Incremental Redundancy (IR),
% each retransmission is not necessarily identical to the original
% transmission. Instead, multiple sets of coded bits are generated and
% whenever a retransmission is required the retransmitted data represents a
% different set of coded bits than the previous transmission. The receiver
% combines the retransmission with previous transmission attempts of the
% same packet. As the retransmission contains additional parity bits, not
% included in the previous transmission attempts, the resulting code rate
% is generally lowered by subsequent retransmissions. Each transmission
% contains a different set of parity bits resulting in a higher coding gain
% when compared to chase combining.
% 
%% Hybrid ARQ Type III
% The final method Hybrid ARQ Type III, also known as partial IR, decreases
% the coding rate by sending additional redundancy bits in each
% retransmission. It does however ensure that retransmissions are able to
% self-decode. This means the retransmitted packet can be chase combined
% with previous packets to increase the diversity gain.
%
%% HARQ Process in LTE
% LTE utilizes IR HARQ with a 1/3 turbo encoder used for FEC. The Transport
% Block (TB) CRC is used to detect errors. The receiver only receives
% different punctured versions of the same turbo-encoded data; each of
% these retransmissions are self decodable. Thus, it falls into category of
% a type III Hybrid ARQ.
% 
% In LTE retransmissions are sent with an initial coding rate of 1/2 or
% 3/4. The maximum number of simultaneous DL-HARQ processes (number of
% PDSCH transmissions catered for) is limited to 8 as specified in
% TS36.213, Section 7 [ <#12 3> ].
%
% In LTE, the N-channel stop-and-wait protocol is used as the Hybrid ARQ
% protocol as it offers low buffering requirements and low
% Acknowledgment (ACK)/Negative Acknowledgment (NACK) feedback overhead.
% 
%% DL-HARQ Process in the LTE Toolbox
% In this example a transport block is generated and undergoes DL-SCH
% coding to create a codeword. The codeword undergoes physical downlink
% shared channel coding to form complex modulated symbols.
% 
% Additive White Gaussian Noise is added to the symbols. The noisy symbols
% then undergo receiver processing to obtain the transmitted codeword. The
% codeword is then turbo rate recovered, code block desegmented and CRC
% block decoded to check if transmission was successful. If a CRC error is
% detected in the transport block then a retransmission is made using a
% different RV. This process continues until the transmission is successful
% or the retransmission limit is reached.

%% Cell-wide Settings 
% Cell wide settings are specified in a structure |enb|.

enb.NDLRB = 50;                % No of Downlink RBs in total BW
enb.CyclicPrefix = 'Normal';   % CP length
enb.PHICHDuration = 'Normal';  % PHICH duration
enb.NCellID = 10;              % Cell ID
enb.CellRefP = 1;              % Single antenna ports
enb.DuplexMode = 'FDD';        % FDD Duplex mode
enb.CFI = 2;                   % 2 PDCCH symbols
enb.Ng = 'sixth';              % HICH groups
enb.NSubframe = 0;             % Subframe number 0

%% PDSCH Transmission Mode Configuration
% The Physical Downlink Shared Channel (PDSCH) is configured using a
% structure |pdsch| for a single antenna transmission scheme.

pdsch.NLayers = 1;                % No of layers to map the transport block 
pdsch.TxScheme = 'Port0';         % Transmission scheme
pdsch.Modulation = {'16QAM'};     % Modulation
pdsch.RV = 0;                     % Initialize Redundancy Version
pdsch.RNTI = 500;                 % Radio Network Temporary Identifier
pdsch.NTurboDecIts = 5;           % Number of turbo decoder iterations
pdsch.PRBSet = (0:enb.NDLRB-1).'; % Define the PRBSet
pdsch.CSI = 'On';                 % CSI scaling of soft bits

%% Downlink Coding Configuration
% Define the parameters required for DL-SCH encoding. The transport block
% size used here is as defined for R.3 RMC in Table A.3.3.1-2 of TS36.101 [
% <#12 1> ]. The DL-SCH coded block size can be calculated by the
% <matlab:doc('ltePDSCHIndices') ltePDSCHIndices> function using |enb| and
% |pdsch|. <matlab:doc('ltePDSCHIndices') ltePDSCHIndices> returns an
% information structure as its second output, containing the parameter |G|
% which specifies the number of coded and rate-matched DL-SCH data bits to
% satisfy the physical PDSCH capacity.

rvIndex = 0;                                  % Redundancy Version index 
transportBlkSize = 12960;                     % Transport block size
[~,pdschIndicesInfo] = ltePDSCHIndices(enb,pdsch,pdsch.PRBSet);
codedTrBlkSize = pdschIndicesInfo.G;          % Available PDSCH bits
dlschTransportBlk = randi([0 1], transportBlkSize, 1); % DL-SCH data bits

% Possible redundancy versions (number of retransmissions)
redundancyVersions = 0:3;   

%% Retransmission Loop
% This example models a single HARQ process. After every transmission the
% value of |blkCRCerr| is used to check for a successful transmission of a
% transport block. If a CRC error is detected i.e. |blkCRCerr >=1| then a
% retransmission is performed using a different RV value.
%
% The first transmission is done using a RV of 0, this indicates the
% initialization stage. If a CRC error is detected by the User Equipment
% (UE) it sends a NACK to the Base Station (BS) so that a retransmission is
% initiated using a different RV value. A value of 1 or greater returned
% for the block CRC error.
% 
% The eNodeB will keep transmitting the same transport block using
% different RV values until the UE receives an error free transport block
% or the total retransmission limit occurs. In LTE the total number of HARQ
% processes which can be initiated at any given time is 8.
%
% To transmit and receive a transport block the following steps occur:
% 
% * _DL-SCH Channel Coding._ The DL-SCH bits are generated and undergo
% channel coding. Included in this process is transport block 24A-type CRC
% insertion, code block segmentation and code block CRC insertion, turbo
% coding, rate matching and code block concatenation. The number of code
% block segmentation and CRC insertions into each segment depends on the
% given transport block size. Each segmented block is separately turbo
% encoded and rate matched after a code block 24B-type CRC insertion. The
% concatenation process is applied on the rate matched turbo coded blocks
% to form a codeword. If the transmission results in error then the UE
% signals a NACK. The retransmission of an erroneous packet is done using
% different RVs. Each RV corresponds to a different set of parity bits from
% the same encoded block; the RV controls this variation. All these
% operations can be performed using the toolbox function
% <matlab:doc('lteDLSCH') lteDLSCH>.
%
% * _PDSCH Complex Symbols Generation._ Scrambling, modulation, layer
% mapping and precoding are applied to the coded transport block to
% generate the PDSCH complex symbols. This is achieved using
% <matlab:doc('ltePDSCH') ltePDSCH>.
%
% * _Noise Addition._ Generated noise is then added to PDSCH complex
% symbols. By varying the value of the variance |nVariance| the number of
% retransmissions will also vary, this is because the number of errors
% detected will fluctuate with the amount of noise present on the symbols.
%
% * _PDSCH Receiver Processing._ In the PDSCH receiver deprecoding, layer
% demapping, soft demodulation and descrambling are applied to the noisy
% PDSCH complex symbols.
%
% * _DL-SCH Channel Decoding._ The channel decoding is performed using
% <matlab:doc('lteDLSCHDecode') lteDLSCHDecode> which performs rate
% recovery, soft combining, code block desegmentation, CRC removal and
% block CRC decoding. This function takes a soft buffer as an input
% parameter which is then used in soft combining with received codeword
% soft bits prior the decoding of bits.

% Define soft buffer
decState = [];

% Noise power can be varied to see the different RV
SNR = 4; % dB

% Initial value
blkCRCerr = 1;

while blkCRCerr >= 1     
  
    % Increment redundancy version for every retransmission
    rvIndex = rvIndex + 1;              
    if rvIndex > length(redundancyVersions)
        error('Failed transmission');
    end
    pdsch.RV = redundancyVersions(rvIndex);
        
    % PDSCH payload
    codedTrBlock = lteDLSCH(enb, pdsch, codedTrBlkSize, ...
                   dlschTransportBlk);

    % PDSCH symbol generation
    pdschSymbols = ltePDSCH(enb, pdsch, {codedTrBlock});
    
    % Add noise to pdschSymbols to create noisy complex modulated symbols
    pdschSymbolsNoisy = awgn(pdschSymbols,SNR);

    % PDSCH receiver processing
    rxCW = ltePDSCHDecode(enb, pdsch, pdschSymbolsNoisy);
    
    % DL-SCH channel decoding
    [rxBits, blkCRCerr, decState] = lteDLSCHDecode(enb, ...
        pdsch, transportBlkSize, rxCW, decState);

end

%%
% |blkCRCerr| is the block CRC error for the received transport block. The
% UE sends a NACK if it detects CRC error on received transport block.
% Also, the new soft buffer, |decState|, contents are available at the
% output of this function to be used next time around.
% 
% Using this example it is possible to observe the effect that the noise
% has on the number of retransmissions required for successful reception.
% In this example, for the given level of noise added to the transmitted
% symbols, a total of 1 retransmission is required to successfully receive
% the data.

fprintf(['\n\nTransmission successful, total number of Redundancy ' ...
    'Versions used is ' num2str(redundancyVersions(rvIndex) + 1) ' \n\n']);

%% Selected Bibliography
% # 3GPP TS 36.101 "User Equipment (UE) radio transmission and reception"
% # 3GPP TS 36.212 "Multiplexing and channel coding"
% # 3GPP TS 36.213 "Physical layer procedures"
