%% LTE HDL MIB Recovery
% This example shows the design of a LTE MIB recovery
% system optimized for HDL code generation and hardware implementation. 
% 
% Copyright 2018 The MathWorks, Inc.

%% Introduction
% The model presented in this example can be used to locate and decode the
% MIB from LTE downlink signals. It builds upon the
% <docid:whdl_ug#example-ltehdlCellSearch LTE HDL Cell Search> example, adding
% processing stages to decode the MIB. The  Master Information Block (MIB)
% message is transmitted in the Physical Broadcast Channel (PBCH), and
% carries essential system information:
% 
% * Number of Downlink Resource Blocks (NDLRB), indicating the system
% bandwidth
% * System Frame Number (SFN)
% * PHICH (Physical HARQ Indicator Channel) Configuration
% 
% The design is optimized for HDL code generation and the architecture is
% extensible, allowing additional processing stages to be added, such as
% indexing and decoding for the PCFICH, PDCCH and PDSCH (see
% <docid:whdl_ug#example-ltehdlSIB1Recovery LTE HDL SIB1 Recovery>).
%

%% MIB Processing Stages
% In order to decode the MIB message this example performs these operations:
% 
% * Cell search and OFDM demodulation
% * Buffering grid data
% * Channel estimation and equalization
% * PBCH Indexing - locating PBCH within the grid
% * PBCH Decoding - decoding PBCH, BCH, and MIB
%
% *Cell Search and OFDM Demodulation*
% 
% LTE signal detection, timing and frequency synchronization, and OFDM
% demodulation are performed on the received data. This produces the grid
% data and provides information on the subframe number and cell ID of the
% received waveform. The MIB message is always carried in subframe 0, and
% the cellID is used to determine the location of the cell-specific
% reference signals (CRS) for channel estimation, as well as being used to
% initialize the descrambling sequence for PBCH Decoder.
%
% *Buffering Grid Data*
% 
% As the MIB message is always carried in subframe 0 of the downlink
% signal, subframe 0 is buffered in a memory bank. At the same time as the
% subframe is being written to the memory bank, the location of the CRS are
% calculated using the cellID, and CRS are sent to the channel estimator. 
%
% *Channel Estimation*
% 
% The CRS from the received grid are then compared to the expected values,
% and the phase offset calculated. The channel estimates for each CRS are
% averaged across time, and linear interpolation is used to estimate the
% channel for subcarriers which do not contain CRS. The channel estimate for
% the subframe is used to equalize data when it is read from the grid memory.
%
% *PBCH Indexing*
% 
% The PBCH is always allocated to the central 6 Resource Blocks (RBs) of
% subframe 0, within the first 4 OFDM symbols of the 2nd slot. It occupies
% all of the Resource Elements (REs) within this region, excluding the
% locations allocated to CRS. The locations of the CRS are calculated using
% the cellID, then the addresses of the REs occupied by the PBCH can be
% calculated (240 locations in total), and the data retrieved from the grid
% memory bank. 
%
% *PBCH Decoding*
% 
% As the PBCH data is read from the grid memory bank it is equalized using
% the channel estimate. The 240 equalized PBCH symbols are buffered, and
% PBCH and BCH decoding are attempted for each of the 4 possible versions
% of the MIB within a PBCH transport block. Each of these versions requires
% a different descrambling sequence, so descrambling, demodulation, rate
% recovery, convolutional decoding, and CRC check must be attempted for each.
% If successfully decoded, the CRC value gives the cellRefP value - the
% number of transmit antennas, and the MIB bits can be parsed to give
% the system parameters.
% 
%% Model Architecture
% 
% The architecture of the LTE HDL Cell Search and MIB Recovery
% implementation is shown in the diagram below.
%
% <<../ltehdlMIBRecoveryArchDiagram.png>>
%
% The input to the receiver is baseband I/Q data, sampled at 30.72 Msps.
% A 2048-point FFT is used for OFDM demodulation, and is sufficient to
% decode all of the supported LTE bandwidths. The resource grid buffer is
% capable of storing one subframe of LTE data. Once the receiver has
% synchronized to a cell, data from the OFDM demodulator is written into
% the grid buffer. The PBCH indexing block then generates the indices of
% the resource elements which carry the PBCH. Those resource elements are
% read out of the grid buffer and equalized, before being passed
% through the PBCH decoder. This architecture is designed to be extensible
% and scalable so that additional channel indexing and decoding functions
% can be inserted as needed. For example it can be extended to perform SIB1
% recovery as shown in the
% <docid:whdl_ug#example-ltehdlSIB1Recovery LTE HDL SIB1 Recovery> example.
%
% The top level of the *ltehdlMIBRecovery* model is shown below.
% HDL code can be generated for the *HDL LTE MIB Recovery* subsystem.

models.top = 'ltehdlMIBRecovery';
open_system(models.top);
set_param(models.top, 'Open', 'on');
set(allchild(0),'Visible', 'off');

%%
% 
% The |ltehdlMIBRecovery_init.m| script is executed automatically by the
% model's |InitFcn| callback. This script generates the _dataIn_ and _startIn_
% stimulus signals as well as any of the constants needed to
% initialize the model.
% Input data can be loaded from a file which, for this example, is
% <docid:xilinxzynqbasedradio_ug#example-zynqRadioLTEReceiverAD9361AD9364ML
% LTE Receiver Using Analog Devices AD9361/AD9364>.
% Alternatively, an LTE waveform can be synthesized using LTE Toolbox
% functions.  To select an input source, change the |loadfromfile|
% parameter in |ltehdlMIBRecovery_init.m|.
%
%   SamplingRate = 30.72e6;
%   simParams.Ts = 1/SamplingRate;
% 
%   loadfromfile = true;
% 
%   if loadfromfile
%       load('eNodeBWaveform.mat');
%       dataIn = resample(rxWaveform,SamplingRate,fs);
%   else
%       dataIn = hGenerateDLRXWaveform();
%   end
%

%% HDL Optimized LTE MIB Recovery
% 
% The structure of the *HDL LTE MIB Recovery* subsystem is shown below.
% The *Downlink Sync Demod* block performs frequency and time synchronization,
% PSS/SSS signal detection, and OFDM demodulation. The *MIB Decoder*
% subsystem buffers subframe 0 of the incoming data, performs channel
% estimation, and attempts to decode the PBCH to recover the MIB information.
open_system([models.top '/HDL LTE MIB Recovery']);

%%
% *Downlink Synchronization and Demodulation*
%
% The *Downlink Sync Demod* subsystem takes in I/Q data at 30.72 Msps,
% and outputs the unequalized downlink resource grid data.
% It is an instance of the *ltehdlDownlinkSyncDemod* model reference,
% which implements the following functions:
%
% * Frequency recovery
% * Primary Synchronization Signal (PSS) detection
% * Secondary Synchronization Signal (SSS) detection
% * Timing recovery, based on the PSS and SSS signals
% * OFDM demodulation (using a 2048 point FFT)
% * Cell ID calculation, based on PSS and SSS detection results
%
% The operation of the *ltehdlDownlinkSyncDemod* is described in more
% detail in the  <docid:whdl_ug#example-ltehdlCellSearch LTE HDL Cell Search> example.

%%
%
% *MIB Decoder*
%
% The *MIB Decoder* subsystem is shown below. It consists of
% four subsystems: *PBCH Indexing*, *Resource Grid
% Memory*, *Channel Equalization*, and *PBCH Decoder*.
% The order of operations is as follows:
%
% # The _cellDetected_ input is asserted, preparing the subsystem to
% receive and process data. 
% # OFDM data is streamed into the *MIB Decoder* subsystem, and subframe 0
% is stored in the *Resource Grid Memory*. 
% # The *Channel Equalization* subsystem calculates a channel estimate for
% subframe 0
% # The *PBCH Indexing* block starts generating PBCH resource element indices. 
% # Those resource elements are then read out of the *Resource Grid Memory*
% and equalized by the *Channel Equalization* block. 
% # Finally the equalized PBCH data is passed through the *PBCH Decoder*
% block and the MIB is extracted. 

set_param([models.top '/HDL LTE MIB Recovery/MIB Decoder'], 'Open', 'on');

%%
%
% *Resource Grid Memory*
%
% The *Resource Grid Memory* block contains a memory bank, logic to control
% reading and writing of the grid memory bank, and logic to locate and
% output the CRS. The memory bank capacity is one subframe of demodulated
% OFDM data at the largest supported LTE bandwidth (20MHz).
%
% The *MemoryBank Write Controller* is responsible for writing
% subframes of data to the memory bank.
% The _writeSubframe_ input enables the write controller for the
% appropriate subframes; subframe 0 in the case of the present example.
% The *LTE Memory Bank* contains RAM of dimensions 14 x 2048 x 16 bit
% complex values; that is 14 ODFM symbols, each containing 2048 complex
% values. The *rsOutputGen* subsystem calculates the locations of the cell
% reference symbols, extracts these from the data as it is written to the
% grid memory, and outputs these via the _gridData_ output signal.
%
% The _gridData_ output port carries the CRS signals, from *rsOutputGen*,
% when data is being written to the grid memory (_gridWriteDone_ output
% port is low) and carries data from the *LTE Memory Bank* when the write
% to the grid memory is complete (_gridWriteDone_ output port is high).

models.resourceGrid = 'ltehdlResourceGrid';
open_system(models.resourceGrid);

%%
%
% *PBCH Indexing*
%
% The *PBCH Indexing* block computes the memory addresses required
% to retrieve the PBCH from the grid memory buffer. This is equivalent
% to the LTE Toolbox |ltePBCHIndices| function. The data retrieved from
% the grid memory is then equalized and passed to the *PBCH Decoder* for 
% processing. The PBCH Indexing subsystem becomes active after the data for
% subframe 0 has been written to the grid memory, as indicated by the
% _gridWriteDone_ output of the *Resource Grid Memory* subsystem.
% The PBCH is always 240 symbols in length, centered in the middle
% subcarriers, in the first 4 symbols within the 2nd slot of subframe 0.

models.PBCHIndexing = 'ltehdlPBCHIndexing';
open_system(models.PBCHIndexing);

%%
%
% *Channel Estimation and Equalization*
%
% The *Channel Equalization* block contains three main subsystems.
% *cellRefGen* generates the cell-specific reference signal (CRS)
% symbols using a Gold Sequence generator.
% *chEst* performs channel estimation assuming two transmit antennas by
% using a simple, hardware-friendly channel estimation algorithm.
% *TxDivDecode* performs transmit diversity decoding to equalize the phase
% of the received data, using the channel estimates.
% 
% The channel estimator assumes the transmitter is using two antennas,
% generating a channel estimate for each antenna. For each antenna the
% channel estimator generates a single complex-valued channel estimate for
% each subcarrier of the subframe using the following algorithm:
%
% # Estimate the channel at each CRS resource element by comparing the
% received value to the expected symbol value (generated by
% *cellRefGen*).
% # Average these channel estimates across time (for the duration
% of the subframe) to generate a single complex-valued channel estimate for
% each subcarrier that contains CRS symbols.
% # Use linear interpolation to estimate the channel
% for subcarriers which do not contain CRS symbols.
% 
% The simple time average algorithm used for the channel estimation assumes
% low channel mobility. Therefore, the channel estimate may not be of
% sufficient quality to decode waveforms that were transmitted through fast
% fading channels. The algorithm also avoids using a division operation when
% calculating the channel estimate at each CRS. This means that the
% amplitude of the received signal will not be corrected, which is suitable
% for QPSK applications, but will not work for QAM, where accurate
% amplitude correction is required for reliable decoding.
% 
% Once the channel estimates are calculated for each of the transmit
% antennas they are used to equalize the _gridData_ as it is read out from
% the *Resource Grid Memory*. 
% *TxDivDecode* performs the inverse of the precoding for transmit diversity
% (as described in of TS 36.211 Section 6.3.4.3 [ <#15 1> ]) and produces
% an equalized output signal, which is then passed to the *PBCH Decoder*.

models.channelEqualizer = 'ltehdlChannelEqualizer';
open_system(models.channelEqualizer);

%%
%
% *PBCH Decoder*
%
% The *PBCH Decoder* performs
% QPSK demodulation, descrambling, rate recovery, and BCH decoding. It then
% extracts the MIB output parameters using the *MIB Interpretation* function
% block. These operations are equivalent to the
% |ltePBCHDecode| and |lteMIB| functions in the LTE Toolbox.
%
% The |PBCH Controller| stores the equalized data in memory for iterative
% convolutional decoding attempts. The 4 attempts made at decoding the MIB
% correspond to the 4 repetitions of the MIB data per PBCH transport block.

models.PBCHDecoder = 'ltehdlPBCHDecoder';
open_system(models.PBCHDecoder);

%%
%
% *BCH Decoder*
%
% The *BCH Decoder* quantizes the soft decisions and then decodes the
% data using the
% <docid:whdl_ref#mw_be7d8c05-d534-4c18-b93f-8d21dabc8fbb LTE
% Convolutional Decoder> and
% <docid:whdl_ref#mw_09b0b7d0-372a-4a2a-bddd-9b160c82bba5 LTE CRC
% Decoder> blocks.
% The recommended wordlength of soft decisions at the input to the 
% convolutional decoder is 4 bits.
% However, the *BCH Decoder* block receives 20-bit soft decisions as input.
% Therefore the *softBitScalingUnit* block dynamically scales the data
% so that it utilizes the full dynamic range of the 4 bit soft decisions.
% The CRC decoder block is configured to
% return the full checksum mismatch value. The CRC mask, once checked
% against the allowed values, provides _cellRefP_; the number of
% cell-specific reference signal antenna ports at the transmitter. If the
% CRC checksum does not match one of the accepted values then 
% MIB has not been successfully decoded and the PBCH Controller
% decides whether or not to initiate another decoding attempt.
%
% When a MIB has been successfully decoded, the *MIB Interpretation* subsystem
% extracts and outputs the fields of the message.

set_param([models.PBCHDecoder '/BCH Decoder'], 'Open', 'on');

%% Performance Analysis
% 
% Quality of the input waveform is an important factor that impacts the
% decoding performance. Common factors that affect signal quality are
% multi-path propagation conditions, channel attenuation and interference
% from other cells. The quality of the input waveform can be measured using
% the |cellQualitySearch| function. This function detects LTE cells in the
% input waveform and returns a structure per LTE cell containing the
% following fields: 
%
% * FrequencyOffset:  Frequency offset obtained by |lteFrequencyOffsets| function
% * NCellID:   Physical layer cell identity
% * TimingOffset: Timing offset of the first frame in the input waveform
% * RSRQdB:    Reference Signal Received Quality (RSRQ) value in dB per TS
% 36.214 Section 5.1.3 [ <#15 2> ]
% * ReportedRSRQ:    RSRQ measurement report (integer between 0 and 34) per
% TS 36.133 Section 9.1.7 [ <#15 3> ]
%
% Applying the |cellQualitySearch| function to the captured waveform
% |eNodeBWaveform.mat| used in |ltehdlMIBRecovery_init.m| returns the
% following report:
%
%   FrequencyOffset: 536.8614
%   NCellID: 76
%   TimingOffset: 12709
%   RSRQdB: -5.3654
%   ReportedRSRQ: 29
% 
%   FrequencyOffset: 536.8614
%   NCellID: 160
%   TimingOffset: 3108
%   RSRQdB: -18.1206
%   ReportedRSRQ: 3
%
% There are two cells in the captured waveform, one with cell ID 76
% and one with cell ID 160. The cell with NCellID = 76 has a much higher
% ReportedRSRQ, indicating that it is a stronger signal. In this example
% the Simulink model decodes the MIB for NCellID = 76.
%
%% Results and Display
%
% The scope below shows the key control signals for this example.
% After a pulse is asserted on the _start_ signal the cell search process
% is started. Successful detection of a cell is indicated by the
% _cellDetected_ signal. When the _cellDetected_ signal is asserted the
% _NCellID_ and _TDDMode_ signal become active, indicating the cell ID
% number and whether the cell is using TDD (1) or FDD (0).
% After the cell has been detected the OFDM demodulator waits until
% subframe 0 of the next frame to start outputting the grid data, hence
% there is a gap between _cellDetected_ going high, and grid data being
% output as indicated by the _gridDataValid_ signal. When _gridDataValid_ is
% first asserted _subFrameNum_ will be zero, and will increment for
% subsequent subframes. The simulation stops on the _MIBDetected_ or
% _mibError_ signals being asserted.
%
% <<../ltehdlMIBRecoveryScope.png>>
%
% Once MIB has been detected the _NDLRB_, _PHICH_, _Ng_, _nFrame_, and
% _CellRefP_ signals all become active, indicating the key parameters of
% the cell. These parameters are displayed in the model, as they are static
% values when the simulation is stopped.
%
% The following MIB information is decoded when decoding the captured waveform:
%
%  NCellID (Cell ID): 76
%  TDDMode (0 = FDD, 1 = TDD) : 0 
%  NDLRB (Number of downlink resource blocks): 25
%  PHICH (PHICH duration) index: 0 
%  Ng (HICH group multiplier): 2
%  NFrame (Frame number): 262
%  CellRefP (Cell-specific reference signals): 2
%
% This indicates that the duplex mode used by the cell is FDD, the MIB was
% decoded in frame number 262, the PHICH duration is 'Normal' and the HICH
% group multiplier value is 'One'.
% 
%% HDL Code Generation and Verification
% To generate the HDL code for this example you must have an HDL
% Coder(TM) license. Use the |makehdl| and |makehdltb| commands to generate
% HDL code and HDL testbench for the *HDL LTE MIB Recovery* subsystem.
% Because the input waveform in this example contains at least 40 subframes
% to complete the cell search and MIB recovery, test bench generation takes
% a long time.
%
% The *HDL LTE MIB Recovery* subsystem was synthesized on a Xilinx(R)
% Zynq(R)-7000 ZC706 evaluation board. The post place and route resource
% utilization results are shown in the table below. The design met timing
% with a clock frequency of 140 MHz.

T = table(...
    categorical({'Slice Registers'; 'Slice LUTs'; 'RAMB18'; 'RAMB36'; 'DSP48'}),...
    [51582; 29859; 38; 39; 134],...
    'VariableNames',{'Resource','Usage'});

disp(T);

%%
% For more information see
% <docid:whdl_ug#mw_76ad4164-0270-406e-88ca-1d7b74f510ad Prototype LTE
% Algorithms on Hardware>.

%% References
% # 3GPP TS 26.211 "Physical Channels and Modulation"
% # 3GPP TS 36.214 "Physical layer"
% # 3GPP TS 36.133 "Requirements for support of radio resource management"
%

fields = fieldnames(models);
for k=1:length(fields)
    close_system(models.(fields{k}));
end
