function varargout = Embedding(varargin)
% EMBEDDING MATLAB code for Embedding.fig
%      EMBEDDING, by itself, creates a new EMBEDDING or raises the existing
%      singleton*.
%
%      H = EMBEDDING returns the handle to a new EMBEDDING or the handle to
%      the existing singleton*.
%
%      EMBEDDING('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in EMBEDDING.M with the given input arguments.
%
%      EMBEDDING('Property','Value',...) creates a new EMBEDDING or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Embedding_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Embedding_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Embedding

% Last Modified by GUIDE v2.5 09-Jun-2021 10:53:36

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Embedding_OpeningFcn, ...
                   'gui_OutputFcn',  @Embedding_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Embedding is made visible.
function Embedding_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Embedding (see VARARGIN)

% Choose default command line output for Embedding
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Embedding wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Embedding_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in Browse_Audio.

%------------------------------------------------------------------------------------------------%
%Browse Audio%
function Browse_Audio(hObject, eventdata, handles)
%persiapan file audio
[filename, pathname] = uigetfile({'*.wav'});
fullpathname = fullfile (pathname, filename);
[X, Fs] = audioread(fullpathname);  %Fs adalah sampling

%check apakah user menekan cancel pada dialog
if isequal(filename,0) || isequal(pathname,0)
uiwait(msgbox ('User menekan Cancel','failed','modal') )
hold on;
else
uiwait(msgbox('Audio sudah dipilih','sucess','modal'));
hold off;
        X = X (:,1)
        N = length(X);
        t = (0:N-1)/Fs; 

         %plot
         axes(handles.axes6);
         plot(t,X)
         grid on
         xlabel('Time (s)')
         ylabel('Amplitudo')
end
handles.output = hObject;
handles.fullpathname = fullpathname;
handles.Fs = Fs;
handles.X = X;
guidata(hObject, handles);
%------------------------------------------------------------------------------------------------%

%------------------------------------------------------------------------------------------------%
%Browse Watermark1%
function Browse_Watermark1(hObject, eventdata, handles)
global watermark1;
[m, n] = uigetfile({'*.png'});
watermark1 = strcat(n, m);  
watermark1 = imread(watermark1);
axes(handles.axes2);
imshow(watermark1);

handles.watermark1 = watermark1;
guidata(hObject, handles);
%------------------------------------------------------------------------------------------------%


%------------------------------------------------------------------------------------------------%
%Browse Watermark2%
function Browse_Watermark2(hObject, eventdata, handles)
global watermark2;
[r, s] = uigetfile({'*.png'});
watermark2 = strcat(s, r);
watermark2 = imread(watermark2);
axes(handles.axes7);
imshow(watermark2);

handles.watermark2 = watermark2;
guidata(hObject, handles);


%------------------------------------------Fungsi Emmbedding------------------------------------------------------------------------------------------%

function Embed(hObject, eventdata, handles)
%Membagi matriks x ke dalam frame
if isfield(handles, 'fullpathname')
Fs = handles.Fs;
X = handles.X;
frame_size = 32; % jumlah sample per frames
temp = 0;
for i = 1 : length(X)/32
   frames(i, 1:32) = X(temp + 1 : temp + frame_size);
   temp = temp + frame_size;
end
%----------------------------------------------------------------------------------------------%
wintype = 'hamming';
winlen = 32;
winamp = [0.5,1]*(1/winlen);

%----------------------------------------------------------------------------------------------%
%Menghitung nilai STE perframe
temp = 0;
[a, b] = size(frames);
for i = 1 : a
   energy_frames(i,:) = energy(frames(i,:),wintype,winamp(2),winlen);
   temp = temp + frame_size;   
end
ste = sum(energy_frames.');
ste = ste';

%----------------------------------------------------------------------------------------------%
%Menghitung nilai ZCC perframe
temp = 0;
for i = 1 : a
   zcc_frames(i,:) = zerocross(frames(i,:),wintype,winamp(1),winlen);
   temp = temp + frame_size;   
end
zc = sum(zcc_frames.');
zc = zc';

%----------------------------------------------------------------------------------------------%
% Memisahkan Frame bersuara dengan Tidak Bersuara
ste_batas = max(ste)/8;             %Tracehold ditentukan
zcc_batas = max(zc)/2;              %Tracehold ditentukan
temp1 = 1;
temp2 = 1;
ste_index = [];                     %memberikan index frame bersuara tidak bersuara
voice_frame = [];                   %kumpulan frame bersuara
unvoice_frame = [];                 %kumpulan frame tidak bersuara
for i = 1 : length(ste)
    if ste(i) >= ste_batas
        if zc(i) <= zcc_batas            
            ste_index (i,1) = 1;          
            voice_frame(temp1,:) = frames(i,:);
            temp1 = temp1 + 1;          
        else
            ste_index(i,1) = 0;
            unvoice_frame(temp2, :) = frames(i,:);
            temp2 = temp2 + 1;
        end
    else
        ste_index(i,1) = 0;
        unvoice_frame(temp2, :) = frames(i,:);
        temp2 = temp2 + 1;        
    end    
end
%----------------------------------------------------------------------------------------------%

%----------------------------------------------------------------------------------------------%
%menyisipkan gambar ke frame bersuara
watermark1 = handles.watermark1;
watermark2 = handles.watermark2;
B1 = reshape(watermark1, [1 size(watermark1,1) * size(watermark1,2)]);
B2 = reshape(watermark2, [1 size(watermark2,1) * size(watermark2,2)]);  %kenapa B2 tidak digunakan?

voice_frame2 = voice_frame;        %panjang frame 32%
i = 0;
for j = 0 : length(B1)/12-1
        i = i + 1;
        x = voice_frame(i,1:16);        
        y = B1 (1+j*12 : 12*(j+1));
%----------------------------------------------------------------------------------------------%
        %Fungsi DCT dan SVD dari file embeed_function
        [Un1,Sn1,Vn1] = embeed_function(x,y);  
        
        %koresponden_Un = koleksi Un   
        U1 = reshape(Un1',[1 16]);
        koresponden_Un1(i,1:16) = U1;
        
        %koresponden_Vn = Koleksi Vn
        V1 = reshape(Vn1',[1 16]);
        koresponden_Vn1(i,1:16) = V1;
                
        %Hasil SVD Sn  
        voice_frame2(i,1:16) = Sn1; 
        
        
        
        x = voice_frame(i,17:32);        
        y = watermark2 (1+j*12 : 12*(j+1));        
        [Un2,Sn2,Vn2] = embeed_function(x,y);        
        
        %koresponden_Un = koleksi Un   
        U2 = reshape(Un2',[1 16]);
        koresponden_Un2(i,1:16) = U2;
        
        %koresponden_Vn = Koleksi Vn
        V2 = reshape(Vn2',[1 16]);
        koresponden_Vn2(i,1:16) = V2;
                 
        %hasil SVD Sn 
        voice_frame2(i,17:32) = Sn2;
end

%----------------------------------------------------------------------------------------------%
%Menggabungkan audio
audio_join = [];
temp1 = 1;
temp2 = 1;
for i = 1 : length(frames)    
    if ste_index(i) == 1
        audio_join(i, :) = voice_frame2(temp1, :);
        temp1 = temp1 + 1;                
    else 
        audio_join(i, :) = unvoice_frame(temp2, :);
        temp2 = temp2 + 1;        
    end    
end
        
frames_baru = reshape(frames.',1,[]);
audiojoin_baru = reshape(audio_join.',1,[]);
audiowrite('sesudah.wav', audiojoin_baru, Fs);
[X, Fs] = audioread('sesudah.wav');
        X = X (:,1)
        N = length(X);
        t = (0:N-1)/Fs; 

         %plot
         axes(handles.axes9);
         plot(t,X)
         grid on
         xlabel('Time (s)')
         ylabel('Amplitudo')
handles.output = hObject;
handles.audiojoin_baru = audiojoin_baru;
handles.Fs = Fs;
handles.X = X;
guidata(hObject, handles);
%------------------------------------------------------------------------------------------------%
%Simpan nilai Koresponden_Un1, Koresponden_Un2, Koresponden_Vn1, dan
%Koresponden_Vn2 ke dalam file .cvs
csvwrite('koresponden_Un1.csv', koresponden_Un1);
csvwrite('koresponden_Vn1.csv', koresponden_Vn1);
csvwrite('koresponden_Un2.csv', koresponden_Un2);
csvwrite('koresponden_Vn2.csv', koresponden_Vn2);
%------------------------------------------------------------------------------------------------%
end
%------------------------------------------------------------------------------------------------%
% Fungsi Menyimpan File audio berwatermark
function Save_Audio(hObject, eventdata, handles)
[filename, pathname] = uiputfile('*.wav');
if ~isequal(filename,0)
    Fs = handles.Fs;
    X = handles.X;
    audiojoin_baru = handles.audiojoin_baru;
    % menyimpan file audio berwatermark
    audiowrite(fullfile(pathname,filename),audiojoin_baru,Fs)
else
    return
end
%----------------------------------------------------------------------------------------------%

%----------------------------------------------------------------------------------------------%
function Back_Menu(hObject, eventdata, handles)
strGui4 = ('E:\KULIAH\semester6\TA 2\Code_TA-02\Home.fig'); %Lokasi GUI
open (strGui4);
closereq;
%----------------------------------------------------------------------------------------------%
